diff --git a/internal/api/server.go b/internal/api/server.go index d955d945..c048a02d 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -1109,7 +1109,7 @@ func (s *Server) handleSMSDelivery(c *gin.Context) { if svc == nil { continue } - status, err := svc.GetSMSDeliveryStatus(c.Request.Context(), messageID) + status, err := svc.GetSMSDeliveryStatusContext(c.Request.Context(), messageID) if err != nil { continue } diff --git a/internal/vowifihost/runtime_start.go b/internal/vowifihost/runtime_start.go index 38a0bb92..266d9dbf 100644 --- a/internal/vowifihost/runtime_start.go +++ b/internal/vowifihost/runtime_start.go @@ -15,7 +15,7 @@ import ( type runtimeStartFunc func(context.Context, runtimehost.StartRequest) (*runtimehost.Instance, error) func buildVoWiFiSIMAdapter(override runtimehost.SIMAdapter) (runtimehost.SIMAdapter, error) { - if override == nil || override.AKAProvider() == nil { + if override == nil { return nil, fmt.Errorf("vowifi runtime start requires an injected SIM AKA provider") } return override, nil diff --git a/third_party/vowifi-go/runtimehost/abi_restoration_test.go b/third_party/vowifi-go/runtimehost/abi_restoration_test.go new file mode 100644 index 00000000..7b934a35 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/abi_restoration_test.go @@ -0,0 +1,178 @@ +package runtimehost + +import ( + "context" + "reflect" + "sync" + "testing" + "time" + + "github.com/iniwex5/vowifi-go/internal/vowifi/access" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" + "github.com/iniwex5/vowifi-go/runtimehost/eventhost" + "github.com/iniwex5/vowifi-go/runtimehost/identity" + "github.com/iniwex5/vowifi-go/runtimehost/messaging" + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" +) + +func TestRecoveredRootStructPrefixes(t *testing.T) { + assertRootPrefix(t, reflect.TypeOf(State{}), reflect.TypeOf(recoveredStatePrefix{})) + assertRootPrefix(t, reflect.TypeOf(Event{}), reflect.TypeOf(recoveredEventPrefix{})) + assertRootPrefix(t, reflect.TypeOf(Instance{}), reflect.TypeOf(recoveredInstancePrefix{})) + assertRootPrefix(t, reflect.TypeOf(StartRequest{}), reflect.TypeOf(recoveredStartRequestPrefix{})) + assertRootPrefix(t, reflect.TypeOf(SessionConfig{}), reflect.TypeOf(recoveredSessionConfigPrefix{})) + assertRootPrefix(t, reflect.TypeOf(DataplanePolicy{}), reflect.TypeOf(recoveredDataplanePrefix{})) +} + +func TestRecoveredRootInterfacesAndMethods(t *testing.T) { + var _ Observer = ObserverFunc(nil) + var _ messaging.Service = serviceAdapter{} + var _ messaging.Service = (*serviceAdapter)(nil) + var _ SIMAdapter = simAdapter{} + var _ SIMAdapter = (*simAdapter)(nil) + var _ access.Adapter = accessAdapter{} + var _ access.SIMAdapter = NewReaderSIMAdapter(startAKAProvider{}).runtimeSIMAdapter() + + var addObserver func(*Instance, Observer) func() = (*Instance).AddObserver + var getDelivery func(*Instance, string) (*messaging.DeliveryStatus, error) = (*Instance).GetSMSDeliveryStatus + var service func(*Instance) messaging.Service = (*Instance).Service + if addObserver == nil || getDelivery == nil || service == nil { + t.Fatal("recovered Instance methods are unavailable") + } + + assertInterfaceMethods(t, reflect.TypeOf((*Observer)(nil)).Elem(), []string{"OnRuntimeHostEvent"}) + assertInterfaceMethods(t, reflect.TypeOf((*SIMAdapter)(nil)).Elem(), []string{"runtimeSIMAdapter"}) + assertInterfaceMethods(t, reflect.TypeOf((*Modem)(nil)).Elem(), []string{ + "CloseLogicalChannel", "DeviceID", "ExecuteATSilent", "GetNetworkMode", "GetRegStatus", + "IsHealthy", "IsSimInserted", "OpenLogicalChannel", "QuerySIMInserted", "Stop", "TransmitAPDU", + }) +} + +func TestRecoveredReconnectDelays(t *testing.T) { + wait, delay := (StartRequest{}).startPolicy() + if !wait || time.Duration(delay(0)) != 5*time.Second { + t.Fatalf("default start policy wait=%v delay=%s", wait, time.Duration(delay(0))) + } + wait, delay = (StartRequest{Mode: StartModeReader}).startPolicy() + if wait || time.Duration(delay(0)) != 30*time.Second { + t.Fatalf("reader start policy wait=%v delay=%s", wait, time.Duration(delay(0))) + } + if got := time.Duration(defaultMainReconnectDelay(0)); got != 5*time.Second { + t.Fatalf("main delay 0 = %s", got) + } + if got := time.Duration(defaultMainReconnectDelay(1)); got != 30*time.Second { + t.Fatalf("main delay 1 = %s", got) + } + wantReader := []time.Duration{30 * time.Second, 60 * time.Second, 120 * time.Second} + for attempt, want := range wantReader { + if got := time.Duration(defaultReaderReconnectDelay(attempt)); got != want { + t.Fatalf("reader delay %d = %s, want %s", attempt, got, want) + } + } +} + +func assertRootPrefix(t *testing.T, actual, prefix reflect.Type) { + t.Helper() + if actual.NumField() < prefix.NumField() { + t.Fatalf("%s has %d fields, want prefix %d", actual, actual.NumField(), prefix.NumField()) + } + for index := 0; index < prefix.NumField(); index++ { + got, want := actual.Field(index), prefix.Field(index) + if got.Name != want.Name || got.Type != want.Type || got.Offset != want.Offset { + t.Fatalf("%s field %d = %s %s @%d, want %s %s @%d", + actual, index, got.Name, got.Type, got.Offset, want.Name, want.Type, want.Offset) + } + } +} + +func assertInterfaceMethods(t *testing.T, value reflect.Type, names []string) { + t.Helper() + if value.NumMethod() != len(names) { + t.Fatalf("%s has %d methods, want %d", value, value.NumMethod(), len(names)) + } + for index, name := range names { + if got := value.Method(index).Name; got != name { + t.Fatalf("%s method %d = %s, want %s", value, index, got, name) + } + } +} + +type recoveredStatePrefix struct { + Phase string + DeviceID string + DataplaneMode string + NetworkMode string + SIMReady bool + AccessReady bool + TunnelReady bool + IMSReady bool + SMSReady bool + RegStatus int + RegStatusText string + LastEvent string + LastReason string + LastRedirectEPDG string + LastErrorClass string + LastError string + UpdatedAt time.Time +} + +type recoveredEventPrefix struct { + Kind string + DeviceID string + TraceID string + Reason string + Attempt int + RetryDelay int64 + RedirectEPDG string + State State +} + +type recoveredInstancePrefix struct { + mu sync.RWMutex + state State + service messaging.Service + session *runtimecore.SessionResult + startedAt time.Time + cancel func() + observers []Observer + onNotify func(string) + onSMS func(string, string, string, time.Time) +} + +type recoveredStartRequestPrefix struct { + Mode string + DeviceID string + TraceID string + Profile identity.Profile + Prepared *identity.PreparedSession + IMSIdentity identity.IMSIdentityResult + NetworkMode string + VoiceGateway *voicehost.Gateway + SIM SIMAdapter + Access identity.AccessAdapter + Dataplane DataplanePolicy + Proxy *ProxyConfig + DNSServer string + DeliveryStore messaging.DeliveryStore + Dispatch eventhost.Dispatcher + BeforeStart func(context.Context, SessionConfig) error + ShouldRun func() bool + runner func(context.Context, runtimecore.RuntimeStartRequest) (StartResult, error) +} + +type recoveredSessionConfigPrefix struct { + Ctx context.Context + DeviceID string + TraceID string + Prepared identity.PreparedSession + DataplaneMode string + TUNName string + Proxy *ProxyConfig + DNSServer string +} + +type recoveredDataplanePrefix struct { + Mode string + TUNName string +} diff --git a/third_party/vowifi-go/runtimehost/access_adapters.go b/third_party/vowifi-go/runtimehost/access_adapters.go new file mode 100644 index 00000000..a33edfa8 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/access_adapters.go @@ -0,0 +1,62 @@ +package runtimehost + +import ( + enginesim "github.com/iniwex5/vowifi-go/engine/sim" + "github.com/iniwex5/vowifi-go/internal/vowifi/access" + "github.com/iniwex5/vowifi-go/internal/vowifi/profile" +) + +func (adapter accessAdapter) Capabilities() access.Capabilities { + if adapter.host == nil { + return access.Capabilities{} + } + value := adapter.host.Capabilities() + return access.Capabilities{ + SIM: value.SIM || value.HasUSIM, ISIMIdentity: value.ISIMIdentity || value.HasISIM, + ISIMAKA: value.ISIMAKA, Modem: value.Modem, Reader: value.Reader, + } +} + +func (adapter accessAdapter) IMSIdentityProvider() profile.Provider { + if adapter.host == nil { + return nil + } + provider := adapter.host.IMSIdentityProvider() + if provider == nil { + return nil + } + return identityProviderAdapter{provider: provider} +} + +func (adapter identityProviderAdapter) GetISIMIdentity() (profile.Identity, error) { + if adapter.provider == nil { + return profile.Identity{}, nil + } + value, err := adapter.provider.GetISIMIdentity() + if err != nil { + return profile.Identity{}, err + } + return profile.Identity{ + IMPI: value.IMPI, IMPU: append([]string(nil), value.IMPU...), Domain: value.Domain, + }, nil +} + +func (adapter modemAccessAdapter) Capabilities() ModemCapabilities { + if adapter.modem == nil { + return ModemCapabilities{} + } + _, hasIdentity := adapter.modem.(IMSIdentityProvider) + _, hasISIMAKA := adapter.modem.(enginesim.ISIMAKAProvider) + return ModemCapabilities{ + SIM: true, ISIMIdentity: hasIdentity, ISIMAKA: hasISIMAKA, Modem: true, + HasISIM: hasIdentity, HasUSIM: true, + } +} + +func (adapter modemAccessAdapter) IMSIdentityProvider() IMSIdentityProvider { + if adapter.modem == nil { + return nil + } + provider, _ := adapter.modem.(IMSIdentityProvider) + return provider +} diff --git a/third_party/vowifi-go/runtimehost/adapters.go b/third_party/vowifi-go/runtimehost/adapters.go index ffa1d152..897feea4 100644 --- a/third_party/vowifi-go/runtimehost/adapters.go +++ b/third_party/vowifi-go/runtimehost/adapters.go @@ -6,10 +6,11 @@ import ( "time" enginesim "github.com/iniwex5/vowifi-go/engine/sim" + "github.com/iniwex5/vowifi-go/internal/vowifi/access" "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" + "github.com/iniwex5/vowifi-go/internal/vowifi/profile" "github.com/iniwex5/vowifi-go/internal/vowifi/smsdelivery" "github.com/iniwex5/vowifi-go/internal/vowifi/voice" - "github.com/iniwex5/vowifi-go/runtimehost/identity" "github.com/iniwex5/vowifi-go/runtimehost/messaging" ) @@ -22,7 +23,7 @@ func attachVoiceAgent(req StartRequest, inst *Instance, lifecycle IMSLifecycle) if req.VoiceGateway == nil { return nil } - adapter, ok := lifecycle.(*serviceAdapter) + adapter, ok := lifecycle.(*imscoreLifecycleAdapter) if !ok || adapter.svc == nil { return errors.New("runtimehost: voice requires the registered IMS service") } @@ -49,29 +50,29 @@ func newServiceAdapter(svc *imscore.Service) *serviceAdapter { } // Register runs the real IMS REGISTER flow. -func (a *serviceAdapter) Register(ctx context.Context) error { - if a == nil || a.svc == nil { +func (a serviceAdapter) Register(ctx context.Context) error { + if a.svc == nil { return errNoService } return a.svc.Register(ctx) } -func (a *serviceAdapter) RegistrationErrors() <-chan error { - if a == nil || a.svc == nil { +func (a serviceAdapter) RegistrationErrors() <-chan error { + if a.svc == nil { return nil } return a.svc.RegistrationErrors() } -func (a *serviceAdapter) SMSReadiness() SMSReadiness { - if a == nil || a.svc == nil { +func (a serviceAdapter) SMSReadiness() SMSReadiness { + if a.svc == nil { return SMSReadiness{Reason: "IMS service is unavailable"} } return adaptSMSReadiness(a.svc.SMSReadiness()) } -func (a *serviceAdapter) SetOnSMSReadinessChanged(fn func(SMSReadiness)) { - if a == nil || a.svc == nil { +func (a serviceAdapter) SetOnSMSReadinessChanged(fn func(SMSReadiness)) { + if a.svc == nil { return } a.svc.SetOnSMSReadinessChanged(func(readiness imscore.SMSReadiness) { @@ -90,8 +91,8 @@ func adaptSMSReadiness(readiness imscore.SMSReadiness) SMSReadiness { } // SendSMSWithOptions sends an SMS with options. -func (a *serviceAdapter) SendSMSWithOptions(ctx context.Context, to, text string, opts messaging.SendOptions) (messaging.SendOutcome, error) { - if a == nil || a.svc == nil { +func (a serviceAdapter) SendSMSWithOptions(ctx context.Context, to, text string, opts messaging.SendOptions) (messaging.SendOutcome, error) { + if a.svc == nil { return messaging.SendOutcome{}, errNoService } if opts.SuppressSendTGSuccess { @@ -102,8 +103,8 @@ func (a *serviceAdapter) SendSMSWithOptions(ctx context.Context, to, text string } // SendSMSWithResult sends an SMS. -func (a *serviceAdapter) SendSMSWithResult(ctx context.Context, to, text string) (messaging.SendOutcome, error) { - if a == nil || a.svc == nil { +func (a serviceAdapter) SendSMSWithResult(ctx context.Context, to, text string) (messaging.SendOutcome, error) { + if a.svc == nil { return messaging.SendOutcome{}, errNoService } out, err := a.svc.SendSMSWithResult(ctx, to, text) @@ -120,11 +121,11 @@ func adaptSMSSendOutcome(out imscore.SendOutcome) messaging.SendOutcome { } // GetSMSDeliveryStatus returns the delivery status of an SMS. -func (a *serviceAdapter) GetSMSDeliveryStatus(ctx context.Context, ref string) (*messaging.DeliveryStatus, error) { - if a == nil || a.svc == nil { +func (a serviceAdapter) GetSMSDeliveryStatus(ref string) (*messaging.DeliveryStatus, error) { + if a.svc == nil { return nil, errNoService } - st, err := a.svc.GetSMSDeliveryStatusContext(ctx, ref) + st, err := a.svc.GetSMSDeliveryStatus(ref) if err != nil { return nil, deliveryStoreErrorFromInternal(err) } @@ -132,8 +133,8 @@ func (a *serviceAdapter) GetSMSDeliveryStatus(ctx context.Context, ref string) ( } // SendUSSD sends a USSD request. -func (a *serviceAdapter) SendUSSD(ctx context.Context, code string) (*messaging.USSDResult, error) { - if a == nil || a.svc == nil { +func (a serviceAdapter) SendUSSD(ctx context.Context, code string) (*messaging.USSDResult, error) { + if a.svc == nil { return nil, errNoService } res, err := a.svc.SendUSSD(ctx, code) @@ -144,8 +145,8 @@ func (a *serviceAdapter) SendUSSD(ctx context.Context, code string) (*messaging. } // ContinueUSSD continues a USSD session. -func (a *serviceAdapter) ContinueUSSD(ctx context.Context, sessionID, input string) (*messaging.USSDResult, error) { - if a == nil || a.svc == nil { +func (a serviceAdapter) ContinueUSSD(ctx context.Context, sessionID, input string) (*messaging.USSDResult, error) { + if a.svc == nil { return nil, errNoService } res, err := a.svc.ContinueUSSD(ctx, sessionID, input) @@ -166,33 +167,28 @@ func messagingUSSDResult(result *imscore.USSDResult) *messaging.USSDResult { } // CancelUSSD cancels a USSD session. -func (a *serviceAdapter) CancelUSSD(ctx context.Context, sessionID string) error { - if a == nil || a.svc == nil { +func (a serviceAdapter) CancelUSSD(ctx context.Context, sessionID string) error { + if a.svc == nil { return errNoService } return a.svc.CancelUSSD(ctx, sessionID) } -// Status returns the runtime status. -func (a *serviceAdapter) Status() Status { - if a == nil || a.svc == nil { - return Status{} +// Status returns the original map projection. +func (a serviceAdapter) Status() map[string]interface{} { + if a.svc == nil { + return nil } status := a.messagingStatusSnapshot() - sms := a.svc.SMSReadiness() - return Status{State: State{ - SessionState: "established", - IMSState: status.RegState, - RegStatus: boolStatus(status.IsRegistered()), - DeviceID: status.DeviceID, - IMSReady: status.IsRegistered(), - SMSReady: sms.Ready, - SMSReadyReason: sms.Reason, - }} + return map[string]interface{}{ + "enabled": status.Enabled, "device_id": status.DeviceID, + "registered": status.IsRegistered(), "reg_status": status.RegStatus, + "registrar": status.Registrar, "local_addr": status.LocalAddr, + } } -func (a *serviceAdapter) messagingStatusSnapshot() messaging.ServiceStatus { - if a == nil || a.svc == nil { +func (a serviceAdapter) messagingStatusSnapshot() messaging.ServiceStatus { + if a.svc == nil { return messaging.ServiceStatus{} } status := a.svc.StatusSnapshot() @@ -213,22 +209,60 @@ func boolStatus(value bool) int { return 0 } -// StatusSnapshot returns the runtime status snapshot. -func (a *serviceAdapter) StatusSnapshot() Status { - return a.Status() +// StatusSnapshot returns the original structured status snapshot. +func (a serviceAdapter) StatusSnapshot() messaging.ServiceStatus { + return a.messagingStatusSnapshot() } // Stop shuts the service down. -func (a *serviceAdapter) Stop() { - if a == nil || a.svc == nil { - return +func (a serviceAdapter) Stop(ctx context.Context) error { + if a.svc == nil { + return nil } - a.svc.StopCurrent() + return a.svc.Stop(ctx) } // TriggerRegisterImmediate triggers an immediate re-registration. -func (a *serviceAdapter) TriggerRegisterImmediate() error { - if a == nil || a.svc == nil { +func (a serviceAdapter) TriggerRegisterImmediate(reason string) { + if a.svc != nil { + a.svc.TriggerRegisterImmediate(reason) + } +} + +func (a serviceAdapter) GetSMSDeliveryStatusContext( + ctx context.Context, + ref string, +) (*messaging.DeliveryStatus, error) { + if a.svc == nil { + return nil, errNoService + } + status, err := a.svc.GetSMSDeliveryStatusContext(ctx, ref) + if err != nil { + return nil, deliveryStoreErrorFromInternal(err) + } + return deliveryStatusFromInternal(status), nil +} + +func (a serviceAdapter) StatusCurrent() Status { + status := a.messagingStatusSnapshot() + sms := SMSReadiness{} + if a.svc != nil { + sms = adaptSMSReadiness(a.svc.SMSReadiness()) + } + return Status{State: State{ + Phase: "ready", DeviceID: status.DeviceID, + IMSReady: status.IsRegistered(), SMSReady: sms.Ready, + RegStatus: boolStatus(status.IsRegistered()), RegStatusText: status.RegStatus, + SessionState: "established", IMSState: status.RegState, SMSReadyReason: sms.Reason, + }} +} + +func (a serviceAdapter) StopCurrent() { + _ = a.Stop(context.Background()) +} + +func (a serviceAdapter) TriggerRegisterImmediateCurrent() error { + if a.svc == nil { return errNoService } return a.svc.TriggerRegisterImmediateCurrent() @@ -482,19 +516,6 @@ func deliveryStatusToInternal(st *messaging.DeliveryStatus) *imscore.DeliverySta return out } -// instanceObserver observes runtime events. -type instanceObserver struct { - inst *Instance -} - -// OnRuntimeEvent handles a runtime event. -func (o *instanceObserver) OnRuntimeEvent(ev Event) { - if o == nil || o.inst == nil { - return - } - o.inst.publish(ev) -} - // OnRuntimeHostEvent implements ObserverFunc as a method. func (f ObserverFunc) OnRuntimeHostEvent(ctx context.Context, ev Event) { if f != nil { @@ -504,23 +525,19 @@ func (f ObserverFunc) OnRuntimeHostEvent(ctx context.Context, ev Event) { // simAdapter adapts a SIM provider. type simAdapter struct { - provider SIMProvider + inner access.SIMAdapter } -// runtimeSIMAdapter returns the underlying SIM provider. -func (a *simAdapter) runtimeSIMAdapter() SIMProvider { - if a == nil { - return nil - } - return a.provider +func (a simAdapter) runtimeSIMAdapter() access.SIMAdapter { + return a.inner } -// AKAProvider returns the injected production SIM AKA provider. -func (a *simAdapter) AKAProvider() enginesim.AKAProvider { - if a == nil { +// AKAProvider preserves source compatibility for concrete adapter users. +func (a simAdapter) AKAProvider() enginesim.AKAProvider { + if a.inner == nil { return nil } - return a.provider + return a.inner.EPDGSIMProvider(profile.AuthPlan{}) } // SIMProvider computes AKA through the injected SIM implementation. @@ -531,19 +548,24 @@ func apiErrorToInternal(err error) error { return err } -// authPlanToInternal converts an auth plan to an internal value. -func authPlanToInternal(plan string) string { - return plan -} - // defaultMainReconnectDelay returns the default reconnect delay for main mode. -func defaultMainReconnectDelay() time.Duration { - return 5 * time.Second +func defaultMainReconnectDelay(attempt int) int64 { + if attempt < 1 { + return int64(5 * time.Second) + } + return int64(30 * time.Second) } // defaultReaderReconnectDelay returns the default reconnect delay for reader mode. -func defaultReaderReconnectDelay() time.Duration { - return 10 * time.Second +func defaultReaderReconnectDelay(attempt int) int64 { + switch { + case attempt < 1: + return int64(30 * time.Second) + case attempt == 1: + return int64(60 * time.Second) + default: + return int64(120 * time.Second) + } } // deliveryStoreErrorFromInternal converts an internal delivery error. @@ -561,43 +583,3 @@ func deliveryStoreErrorToInternal(err error) error { } return err } - -// preparedSessionFromInternal converts an internal prepared session. -func preparedSessionFromInternal(p *identity.PreparedSession) *identity.PreparedSession { - return p -} - -// preparedSessionPtrToInternal converts a prepared session pointer. -func preparedSessionPtrToInternal(p *identity.PreparedSession) *identity.PreparedSession { - return p -} - -// sessionConfigFromInternal converts an internal session config. -func sessionConfigFromInternal(c SessionConfig) SessionConfig { - return c -} - -// startInstance starts a runtime host instance. -func startInstance(ctx context.Context, req StartRequest) (*Instance, error) { - return Start(ctx, req) -} - -// startInstanceAsync starts a runtime host instance asynchronously. -func startInstanceAsync(ctx context.Context, req StartRequest) (<-chan *Instance, <-chan error) { - instCh := make(chan *Instance, 1) - errCh := make(chan error, 1) - go func() { - inst, err := Start(ctx, req) - if err != nil { - errCh <- err - return - } - instCh <- inst - }() - return instCh, errCh -} - -// startResultFromInternal converts an internal start result. -func startResultFromInternal(inst *Instance, err error) (*Instance, error) { - return inst, err -} diff --git a/third_party/vowifi-go/runtimehost/adapters_test.go b/third_party/vowifi-go/runtimehost/adapters_test.go index 0c366310..a61fd7a5 100644 --- a/third_party/vowifi-go/runtimehost/adapters_test.go +++ b/third_party/vowifi-go/runtimehost/adapters_test.go @@ -12,10 +12,10 @@ import ( "time" "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" "github.com/iniwex5/vowifi-go/internal/vowifi/smsdelivery" "github.com/iniwex5/vowifi-go/internal/vowifi/voice" "github.com/iniwex5/vowifi-go/runtimehost/eventhost" - "github.com/iniwex5/vowifi-go/runtimehost/identity" "github.com/iniwex5/vowifi-go/runtimehost/messaging" "github.com/iniwex5/vowifi-go/runtimehost/voicehost" ) @@ -110,7 +110,7 @@ func testSIPHeader(message, name string) string { func TestServiceAdapterStatus(t *testing.T) { svc := newTestService(t) adapter := newServiceAdapter(svc) - st := adapter.Status() + st := adapter.StatusCurrent() if st.State.RegStatus != 1 { t.Errorf("reg status = %d, want 1 (registered)", st.State.RegStatus) } @@ -177,7 +177,7 @@ func TestVoiceAgentAttachAndStopCleanup(t *testing.T) { inst := &Instance{} inst.setService(newServiceAdapter(svc)) req := StartRequest{DeviceID: "dev-1", VoiceGateway: gateway} - if err := attachVoiceAgent(req, inst, newServiceAdapter(svc)); err != nil { + if err := attachVoiceAgent(req, inst, &imscoreLifecycleAdapter{svc: svc}); err != nil { t.Fatalf("attachVoiceAgent: %v", err) } if gateway.GetAgent("dev-1") == nil || gateway.DeviceStatusCurrent("dev-1")["ready"] != true { @@ -207,7 +207,7 @@ func TestVoiceGatewaySimulateCallUsesProductionAdapterAndRTP(t *testing.T) { defer gateway.Stop() inst := &Instance{} inst.setService(newServiceAdapter(svc)) - if err := attachVoiceAgent(StartRequest{DeviceID: "dev-1", VoiceGateway: gateway}, inst, newServiceAdapter(svc)); err != nil { + if err := attachVoiceAgent(StartRequest{DeviceID: "dev-1", VoiceGateway: gateway}, inst, &imscoreLifecycleAdapter{svc: svc}); err != nil { t.Fatal(err) } defer inst.Stop(context.Background()) @@ -269,7 +269,7 @@ func TestVoiceGatewayReceivesAndRejectsProductionIncomingCall(t *testing.T) { gateway.SetIncomingCallHandler(func(call voicehost.IncomingCall) { incoming <- call }) inst := &Instance{} inst.setService(newServiceAdapter(svc)) - if err := attachVoiceAgent(StartRequest{DeviceID: "dev-1", VoiceGateway: gateway}, inst, newServiceAdapter(svc)); err != nil { + if err := attachVoiceAgent(StartRequest{DeviceID: "dev-1", VoiceGateway: gateway}, inst, &imscoreLifecycleAdapter{svc: svc}); err != nil { t.Fatal(err) } defer inst.Stop(context.Background()) @@ -723,26 +723,23 @@ func TestDeliveryStatusConversion(t *testing.T) { } func TestStartInstanceAsync(t *testing.T) { - prepared := &identity.PreparedSession{ - Profile: identity.Profile{IMSI: "310260123456789", MCC: "310", MNC: "260"}, - IMSIdentity: identity.IMSIdentity{IMPI: "310260123456789@ims.example", IMPU: "sip:310260123456789@ims.example", Domain: "ims.example"}, - EPDGAddr: "epdg.example.com", + ctx, cancel := context.WithCancel(context.Background()) + started := make(chan struct{}) + runner := func(ctx context.Context, _ runtimecore.RuntimeStartRequest) (StartResult, error) { + close(started) + <-ctx.Done() + return StartResult{TraceID: "trace-1"}, ctx.Err() + } + instance, err := startInstanceAsync(ctx, runtimecore.RuntimeStartRequest{ + DeviceID: "dev-1", TraceID: "trace-1", + }, runner, defaultReaderReconnectDelay) + if err != nil || instance == nil { + t.Fatalf("startInstanceAsync instance=%v err=%v", instance, err) } - req := runtimeTestRequest(prepared, newLifecycleTunnel(nil)) - req.Mode = StartModeReader - req.DeviceID = "dev-1" - instCh, errCh := startInstanceAsync(context.Background(), req) select { - case inst := <-instCh: - if inst == nil { - t.Fatal("nil instance") - } - if st := inst.State(); st.SessionState != "established" { - t.Errorf("session state = %q", st.SessionState) - } - case err := <-errCh: - t.Fatalf("start: %v", err) - case <-time.After(2 * time.Second): - t.Fatal("start timed out") + case <-started: + case <-time.After(time.Second): + t.Fatal("runtime runner was not started") } + cancel() } diff --git a/third_party/vowifi-go/runtimehost/current_lifecycle.go b/third_party/vowifi-go/runtimehost/current_lifecycle.go new file mode 100644 index 00000000..51cac2f0 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/current_lifecycle.go @@ -0,0 +1,169 @@ +package runtimehost + +import ( + "context" + + "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" + "github.com/iniwex5/vowifi-go/runtimehost/messaging" +) + +// lifecycleServiceAdapter exposes an injected current lifecycle through the +// recovered messaging.Service contract stored by Instance. +type lifecycleServiceAdapter struct { + lifecycle IMSLifecycle +} + +func (adapter lifecycleServiceAdapter) CancelUSSD(ctx context.Context, sessionID string) error { + return adapter.lifecycle.CancelUSSD(ctx, sessionID) +} + +func (adapter lifecycleServiceAdapter) ContinueUSSD( + ctx context.Context, + sessionID, input string, +) (*messaging.USSDResult, error) { + return adapter.lifecycle.ContinueUSSD(ctx, sessionID, input) +} + +func (adapter lifecycleServiceAdapter) GetSMSDeliveryStatus( + messageID string, +) (*messaging.DeliveryStatus, error) { + return adapter.lifecycle.GetSMSDeliveryStatus(context.Background(), messageID) +} + +func (adapter lifecycleServiceAdapter) SendSMSWithOptions( + ctx context.Context, + to, text string, + options messaging.SendOptions, +) (messaging.SendOutcome, error) { + return adapter.lifecycle.SendSMSWithOptions(ctx, to, text, options) +} + +func (adapter lifecycleServiceAdapter) SendSMSWithResult( + ctx context.Context, + to, text string, +) (messaging.SendOutcome, error) { + return adapter.lifecycle.SendSMSWithResult(ctx, to, text) +} + +func (adapter lifecycleServiceAdapter) SendUSSD( + ctx context.Context, + code string, +) (*messaging.USSDResult, error) { + return adapter.lifecycle.SendUSSD(ctx, code) +} + +func (adapter lifecycleServiceAdapter) Status() map[string]interface{} { + state := adapter.lifecycle.Status().State + return map[string]interface{}{ + "device_id": state.DeviceID, "phase": state.Phase, + "ims_ready": state.IMSReady, "sms_ready": state.SMSReady, + } +} + +func (adapter lifecycleServiceAdapter) StatusSnapshot() messaging.ServiceStatus { + state := adapter.lifecycle.StatusSnapshot().State + return messaging.ServiceStatus{ + Enabled: true, DeviceID: state.DeviceID, Registered: state.IMSReady, + RegStatus: state.RegStatusText, State: state.Phase, RegState: state.IMSState, + } +} + +func (adapter lifecycleServiceAdapter) Stop(context.Context) error { + adapter.lifecycle.Stop() + return nil +} + +func (adapter lifecycleServiceAdapter) TriggerRegisterImmediate(string) { + _ = adapter.lifecycle.TriggerRegisterImmediate() +} + +// imscoreLifecycleAdapter retains the explicitly injected current lifecycle API. +type imscoreLifecycleAdapter struct { + svc *imscore.Service +} + +func (adapter *imscoreLifecycleAdapter) Register(ctx context.Context) error { + if adapter == nil || adapter.svc == nil { + return errNoService + } + return adapter.svc.Register(ctx) +} + +func (adapter *imscoreLifecycleAdapter) RegistrationErrors() <-chan error { + if adapter == nil || adapter.svc == nil { + return nil + } + return adapter.svc.RegistrationErrors() +} + +func (adapter *imscoreLifecycleAdapter) SMSReadiness() SMSReadiness { + if adapter == nil || adapter.svc == nil { + return SMSReadiness{Reason: "IMS service is unavailable"} + } + return adaptSMSReadiness(adapter.svc.SMSReadiness()) +} + +func (adapter *imscoreLifecycleAdapter) SetOnSMSReadinessChanged(fn func(SMSReadiness)) { + if adapter == nil || adapter.svc == nil { + return + } + adapter.svc.SetOnSMSReadinessChanged(func(value imscore.SMSReadiness) { + if fn != nil { + fn(adaptSMSReadiness(value)) + } + }) +} + +func (adapter *imscoreLifecycleAdapter) SendSMSWithOptions( + ctx context.Context, + to, text string, + options messaging.SendOptions, +) (messaging.SendOutcome, error) { + return newServiceAdapter(adapter.svc).SendSMSWithOptions(ctx, to, text, options) +} + +func (adapter *imscoreLifecycleAdapter) SendSMSWithResult( + ctx context.Context, + to, text string, +) (messaging.SendOutcome, error) { + return newServiceAdapter(adapter.svc).SendSMSWithResult(ctx, to, text) +} + +func (adapter *imscoreLifecycleAdapter) GetSMSDeliveryStatus( + ctx context.Context, + messageID string, +) (*messaging.DeliveryStatus, error) { + return newServiceAdapter(adapter.svc).GetSMSDeliveryStatusContext(ctx, messageID) +} + +func (adapter *imscoreLifecycleAdapter) SendUSSD( + ctx context.Context, + code string, +) (*messaging.USSDResult, error) { + return newServiceAdapter(adapter.svc).SendUSSD(ctx, code) +} + +func (adapter *imscoreLifecycleAdapter) ContinueUSSD( + ctx context.Context, + sessionID, input string, +) (*messaging.USSDResult, error) { + return newServiceAdapter(adapter.svc).ContinueUSSD(ctx, sessionID, input) +} + +func (adapter *imscoreLifecycleAdapter) CancelUSSD(ctx context.Context, sessionID string) error { + return newServiceAdapter(adapter.svc).CancelUSSD(ctx, sessionID) +} + +func (adapter *imscoreLifecycleAdapter) Status() Status { + return newServiceAdapter(adapter.svc).StatusCurrent() +} + +func (adapter *imscoreLifecycleAdapter) StatusSnapshot() Status { return adapter.Status() } + +func (adapter *imscoreLifecycleAdapter) Stop() { + newServiceAdapter(adapter.svc).StopCurrent() +} + +func (adapter *imscoreLifecycleAdapter) TriggerRegisterImmediate() error { + return newServiceAdapter(adapter.svc).TriggerRegisterImmediateCurrent() +} diff --git a/third_party/vowifi-go/runtimehost/instance.go b/third_party/vowifi-go/runtimehost/instance.go index c847526a..48ae6273 100644 --- a/third_party/vowifi-go/runtimehost/instance.go +++ b/third_party/vowifi-go/runtimehost/instance.go @@ -5,9 +5,11 @@ import ( "errors" "fmt" "net" + "sync" "time" "github.com/iniwex5/vowifi-go/internal/vowifi/common" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" "github.com/iniwex5/vowifi-go/runtimehost/messaging" ) @@ -26,23 +28,37 @@ func (i *Instance) Service() Service { } // AddObserver registers an observer that receives runtime events. -func (i *Instance) AddObserver(obs ObserverFunc) { +func (i *Instance) AddObserver(obs Observer) func() { + if i == nil || obs == nil { + return func() {} + } i.mu.Lock() - defer i.mu.Unlock() i.observers = append(i.observers, obs) + index := len(i.observers) - 1 + i.mu.Unlock() + var once sync.Once + return func() { + once.Do(func() { + i.mu.Lock() + if index < len(i.observers) { + i.observers[index] = nil + } + i.mu.Unlock() + }) + } } // SetNotifier installs the session notifier. func (i *Instance) SetNotifier(n Notifier) { i.mu.Lock() - i.notifier = n + i.onNotify = n i.mu.Unlock() } // SetSMSNotifier installs the SMS notifier. func (i *Instance) SetSMSNotifier(n SMSNotifier) { i.mu.Lock() - i.smsNotifier = n + i.onSMS = n i.mu.Unlock() } @@ -64,6 +80,8 @@ func (i *Instance) Stop(ctx context.Context) error { tunnel := i.tunnel cancel := i.cancel voiceDetach := i.voiceDetach + i.service = nil + i.session = nil i.tunnel = nil i.cancel = nil i.voiceDetach = nil @@ -76,12 +94,14 @@ func (i *Instance) Stop(ctx context.Context) error { stopErr = voiceDetach() } if svc != nil { - svc.Stop() + stopErr = errors.Join(stopErr, svc.Stop(ctx)) } if tunnel != nil { tunnel.Shutdown() } - i.updateState(func(state *State) { + i.updateStateWithEvent(ctx, "stopped", func(state *State) { + state.Phase = "stopped" + state.LastEvent = "stopped" state.SessionState = "stopped" state.DataPlaneUp = false state.TunnelReady = false @@ -108,19 +128,25 @@ func (i *Instance) RuntimeState() State { // Status returns a human-readable status string. func (i *Instance) Status() string { st := i.State() - if st.Error != "" { - return "VoWiFi: " + st.Error + if st.LastError != "" { + return "VoWiFi: " + st.LastError } - if st.SessionState == "" { + phase := firstNonEmptyString(st.Phase, st.SessionState) + if phase == "" { return "VoWiFi: STOPPED" } - return "VoWiFi: " + st.SessionState + return "VoWiFi: " + phase } // Obs returns an observation map of the runtime state. func (i *Instance) Obs() map[string]interface{} { st := i.State() return map[string]interface{}{ + "phase": st.Phase, + "device_id": st.DeviceID, + "tunnel_ready": st.TunnelReady, + "ims_ready": st.IMSReady, + "sms_ready": st.SMSReady, "session_state": st.SessionState, "ims_state": st.IMSState, "epdg": st.EPDGAddress, @@ -128,22 +154,35 @@ func (i *Instance) Obs() map[string]interface{} { } } -// setState updates the runtime state and publishes the change. +// setState updates the runtime state. func (i *Instance) setState(s State) { - s.UpdatedAt = time.Now() + if s.UpdatedAt.IsZero() { + s.UpdatedAt = time.Now() + } i.mu.Lock() i.state = s i.mu.Unlock() - i.publish(Event{Type: "state", Detail: s.SessionState, State: s, Session: i}) } func (i *Instance) updateState(update func(*State)) { + i.updateStateWithEvent(context.Background(), "state", update) +} + +func (i *Instance) updateStateWithEvent( + ctx context.Context, + kind string, + update func(*State), +) { i.mu.Lock() update(&i.state) i.state.UpdatedAt = time.Now() state := i.state i.mu.Unlock() - i.publish(Event{Type: "state", Detail: state.SessionState, State: state, Session: i}) + detail := firstNonEmptyString(state.Phase, state.SessionState) + i.publish(ctx, Event{ + Kind: kind, DeviceID: state.DeviceID, Reason: state.LastReason, State: state, + Type: kind, Detail: detail, Session: i, + }) } func (i *Instance) attachTunnel(tunnel Tunnel, cancel context.CancelFunc) { @@ -155,6 +194,8 @@ func (i *Instance) attachTunnel(tunnel Tunnel, cancel context.CancelFunc) { func (i *Instance) updateTunnelState(sessionState string) { i.updateState(func(state *State) { + state.Phase = sessionState + state.LastEvent = sessionState state.SessionState = sessionState state.TunnelReady = sessionState == "established" state.DataPlaneUp = state.TunnelReady @@ -170,6 +211,8 @@ func (i *Instance) updateTunnelState(sessionState string) { func (i *Instance) markTunnelReadyForIMS() { i.updateState(func(state *State) { + state.Phase = "ipsec_up" + state.LastEvent = "ipsec_up" state.SessionState = "registering" state.IMSState = "registering" state.TunnelReady = true @@ -180,6 +223,8 @@ func (i *Instance) markTunnelReadyForIMS() { func (i *Instance) markIMSRegistered() { i.updateState(func(state *State) { + state.Phase = "ims_ready" + state.LastEvent = "ims_registered" state.SessionState = "established" state.IMSState = "registered" state.IMSReady = true @@ -195,11 +240,17 @@ func (i *Instance) updateSMSReadiness(readiness SMSReadiness) { i.updateState(func(state *State) { state.SMSReady = state.IMSReady && readiness.Ready state.SMSReadyReason = readiness.Reason + if state.SMSReady { + state.Phase = "sms_ready" + state.LastEvent = "sms_ready" + } }) } func (i *Instance) setStartFailure(err error) { i.updateState(func(state *State) { + state.Phase = "error" + state.LastEvent = "terminal_error" state.SessionState = "error" state.Error = err.Error() state.LastError = err.Error() @@ -212,6 +263,8 @@ func (i *Instance) setStartFailure(err error) { func (i *Instance) setIMSFailure(err error) { i.updateState(func(state *State) { + state.Phase = "error" + state.LastEvent = "terminal_error" state.SessionState = "error" state.IMSState = "failed" state.Error = err.Error() @@ -229,6 +282,8 @@ func (i *Instance) setIMSFailure(err error) { func (i *Instance) setIMSRefreshFailure(err error) { i.updateState(func(state *State) { + state.Phase = "error" + state.LastEvent = "terminal_error" state.SessionState = "error" state.IMSState = "failed" state.Error = err.Error() @@ -244,6 +299,8 @@ func (i *Instance) setIMSRefreshFailure(err error) { func (i *Instance) setTunnelControlFailure(err error) { i.updateState(func(state *State) { + state.Phase = "error" + state.LastEvent = "terminal_error" state.SessionState = "error" state.IMSState = "failed" state.Error = err.Error() @@ -261,6 +318,8 @@ func (i *Instance) setTunnelControlFailure(err error) { func (i *Instance) setTunnelReauthenticationRequired(err error) { i.updateState(func(state *State) { + state.Phase = "restarting" + state.LastEvent = "interrupted" state.SessionState = "error" state.IMSState = "restarting" state.Error = err.Error() @@ -277,7 +336,7 @@ func (i *Instance) setTunnelReauthenticationRequired(err error) { } // setService installs the IMS service. -func (i *Instance) setService(s Service) { +func (i *Instance) setService(s messaging.Service) { i.mu.Lock() i.service = s i.mu.Unlock() @@ -290,28 +349,31 @@ func (i *Instance) setVoiceDetach(detach func() error) { } // setSession wires a new session into the host. -func (i *Instance) setSession(s Service) { - i.setService(s) +func (i *Instance) setSession(session *runtimecore.SessionResult) { + i.mu.Lock() + i.session = session + if session != nil && i.startedAt.IsZero() { + i.startedAt = time.Now() + } + i.mu.Unlock() } -// publish delivers an event to all observers and the notifier. -func (i *Instance) publish(ev Event) { +// publish delivers an event to a stable observer snapshot. +func (i *Instance) publish(ctx context.Context, ev Event) { + if i == nil { + return + } + if ctx == nil { + ctx = context.Background() + } i.mu.RLock() - obs := append([]ObserverFunc{}, i.observers...) - notifier := i.notifier - smsNotifier := i.smsNotifier + obs := append([]Observer(nil), i.observers...) i.mu.RUnlock() for _, o := range obs { if o != nil { - o(context.Background(), ev) + o.OnRuntimeHostEvent(ctx, ev) } } - if notifier != nil { - notifier(ev.Detail) - } - if smsNotifier != nil { - smsNotifier("", "", ev.Detail, time.Now()) - } } // --- SMS/USSD service delegation --- @@ -335,12 +397,29 @@ func (i *Instance) SendSMSWithOptions(ctx context.Context, to, text string, opts } // GetSMSDeliveryStatus returns the delivery status of a previously sent SMS. -func (i *Instance) GetSMSDeliveryStatus(ctx context.Context, ref string) (*messaging.DeliveryStatus, error) { +func (i *Instance) GetSMSDeliveryStatus(ref string) (*messaging.DeliveryStatus, error) { svc := i.Service() if svc == nil { return nil, errNoService } - return svc.GetSMSDeliveryStatus(ctx, ref) + return svc.GetSMSDeliveryStatus(ref) +} + +// GetSMSDeliveryStatusContext retains the displaced context-aware query API. +func (i *Instance) GetSMSDeliveryStatusContext( + ctx context.Context, + ref string, +) (*messaging.DeliveryStatus, error) { + svc := i.Service() + if svc == nil { + return nil, errNoService + } + if contextual, ok := svc.(interface { + GetSMSDeliveryStatusContext(context.Context, string) (*messaging.DeliveryStatus, error) + }); ok { + return contextual.GetSMSDeliveryStatusContext(ctx, ref) + } + return svc.GetSMSDeliveryStatus(ref) } // SendUSSD sends a USSD request. @@ -379,11 +458,18 @@ func (i *Instance) TriggerMOBIKE(oldIP, newIP string) error { } i.mu.RLock() tunnel := i.tunnel + session := i.session i.mu.RUnlock() - if tunnel == nil { + if tunnel == nil && (session == nil || session.Session == nil) { return errors.New("runtimehost: no SWu tunnel installed") } - if err := tunnel.UpdateAddresses(oldAddress, newAddress); err != nil { + var err error + if tunnel != nil { + err = tunnel.UpdateAddresses(oldAddress, newAddress) + } else { + err = session.Session.UpdateAddresses(oldAddress, newAddress) + } + if err != nil { wrapped := fmt.Errorf("runtimehost: MOBIKE address update failed: %w", err) i.setTunnelControlFailure(wrapped) return wrapped diff --git a/third_party/vowifi-go/runtimehost/instance_test.go b/third_party/vowifi-go/runtimehost/instance_test.go index 50395806..c7bee6f6 100644 --- a/third_party/vowifi-go/runtimehost/instance_test.go +++ b/third_party/vowifi-go/runtimehost/instance_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/iniwex5/vowifi-go/internal/vowifi/common" + "github.com/iniwex5/vowifi-go/runtimehost/messaging" ) type stubService struct { @@ -22,7 +23,7 @@ func (s *stubService) SendSMSWithOptions(ctx context.Context, to, text string, o func (s *stubService) SendSMSWithResult(ctx context.Context, to, text string) (SendOutcome, error) { return s.SendSMSWithOptions(ctx, to, text, SendOptions{}) } -func (s *stubService) GetSMSDeliveryStatus(ctx context.Context, ref string) (*DeliveryStatus, error) { +func (s *stubService) GetSMSDeliveryStatus(ref string) (*DeliveryStatus, error) { return &DeliveryStatus{State: "delivered"}, nil } func (s *stubService) SendUSSD(ctx context.Context, code string) (*USSDResult, error) { @@ -33,10 +34,10 @@ func (s *stubService) ContinueUSSD(ctx context.Context, sessionID, input string) return &USSDResult{}, nil } func (s *stubService) CancelUSSD(ctx context.Context, sessionID string) error { return nil } -func (s *stubService) Status() Status { return Status{} } -func (s *stubService) StatusSnapshot() Status { return Status{} } -func (s *stubService) Stop() {} -func (s *stubService) TriggerRegisterImmediate() error { return s.registerErr } +func (s *stubService) Status() map[string]interface{} { return nil } +func (s *stubService) StatusSnapshot() messaging.ServiceStatus { return messaging.ServiceStatus{} } +func (s *stubService) Stop(context.Context) error { return nil } +func (s *stubService) TriggerRegisterImmediate(string) {} func TestInstanceStateAndService(t *testing.T) { i := &Instance{} @@ -60,8 +61,8 @@ func TestInstanceStateAndService(t *testing.T) { func TestInstanceObservers(t *testing.T) { i := &Instance{} var got []Event - i.AddObserver(func(_ context.Context, ev Event) { got = append(got, ev) }) - i.setState(State{SessionState: "connecting"}) + i.AddObserver(ObserverFunc(func(_ context.Context, ev Event) { got = append(got, ev) })) + i.updateState(func(state *State) { state.SessionState = "connecting" }) if len(got) != 1 || got[0].Detail != "connecting" { t.Errorf("observer events = %+v", got) } @@ -79,7 +80,7 @@ func TestInstanceSMSDelegation(t *testing.T) { if err != nil || out.Ref != "ref-1" || !svc.sentSMS { t.Errorf("SendSMSWithResult = %+v err %v", out, err) } - ds, err := i.GetSMSDeliveryStatus(ctx, "ref-1") + ds, err := i.GetSMSDeliveryStatus("ref-1") if err != nil || ds.State != "delivered" { t.Errorf("delivery status = %+v err %v", ds, err) } @@ -106,7 +107,7 @@ func TestInstanceStopReleasesIMSBeforeTunnel(t *testing.T) { tunnel := newLifecycleTunnel(nil) tunnel.onShutdown = func() { order = append(order, "tunnel") } service := &lifecycleIMS{onStop: func() { order = append(order, "ims") }} - instance := &Instance{tunnel: tunnel, service: service} + instance := &Instance{tunnel: tunnel, service: lifecycleServiceAdapter{lifecycle: service}} if err := instance.Stop(context.Background()); err != nil { t.Fatalf("Stop: %v", err) } diff --git a/third_party/vowifi-go/runtimehost/reader.go b/third_party/vowifi-go/runtimehost/reader.go index cec26f2d..656f3b13 100644 --- a/third_party/vowifi-go/runtimehost/reader.go +++ b/third_party/vowifi-go/runtimehost/reader.go @@ -1,7 +1,9 @@ package runtimehost +import "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" + // NewReaderSIMAdapter returns a SIM adapter for reader-mode hosts, backed by // the given SIM provider. func NewReaderSIMAdapter(provider SIMProvider) SIMAdapter { - return &simAdapter{provider: provider} + return &simAdapter{inner: runtimecore.NewReaderSIMAdapter(provider)} } diff --git a/third_party/vowifi-go/runtimehost/reader_test.go b/third_party/vowifi-go/runtimehost/reader_test.go index e94e5020..c0387757 100644 --- a/third_party/vowifi-go/runtimehost/reader_test.go +++ b/third_party/vowifi-go/runtimehost/reader_test.go @@ -15,7 +15,11 @@ func (*readerAKAProviderStub) CalculateAKA(rand16, autn16 []byte) (enginesim.AKA func TestNewReaderSIMAdapterExposesInjectedAKAProvider(t *testing.T) { provider := &readerAKAProviderStub{} adapter := NewReaderSIMAdapter(provider) - if adapter == nil || adapter.AKAProvider() != provider { - t.Fatalf("AKAProvider() = %T, want injected provider", adapter.AKAProvider()) + if adapter == nil || adapter.runtimeSIMAdapter() == nil { + t.Fatal("runtime SIM adapter is unavailable") + } + got := adapter.runtimeSIMAdapter().EPDGSIMProvider(runtimeAuthPlan(nil)) + if got != provider { + t.Fatalf("EPDGSIMProvider() = %T, want injected provider", got) } } diff --git a/third_party/vowifi-go/runtimehost/runtime_restoration_test.go b/third_party/vowifi-go/runtimehost/runtime_restoration_test.go new file mode 100644 index 00000000..81d9c960 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/runtime_restoration_test.go @@ -0,0 +1,234 @@ +package runtimehost + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/iniwex5/vowifi-go/engine/swu" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" + "github.com/iniwex5/vowifi-go/runtimehost/identity" +) + +func TestObserverUnsubscribeAndContextPropagation(t *testing.T) { + instance := &Instance{} + key := struct{}{} + ctx := context.WithValue(context.Background(), key, "runtime-context") + var first, second atomic.Int32 + unsubscribe := instance.AddObserver(ObserverFunc(func(got context.Context, _ Event) { + if got.Value(key) != "runtime-context" { + t.Error("observer lost event context") + } + first.Add(1) + })) + instance.AddObserver(ObserverFunc(func(context.Context, Event) { second.Add(1) })) + instance.publish(ctx, Event{Kind: "prepared"}) + unsubscribe() + unsubscribe() + instance.publish(ctx, Event{Kind: "prepared"}) + if first.Load() != 1 || second.Load() != 2 { + t.Fatalf("observer calls first=%d second=%d", first.Load(), second.Load()) + } +} + +func TestMainStartWaitsForRecoveredIPSecReadyEvent(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + release := make(chan struct{}) + started := make(chan struct{}) + finished := make(chan struct{}) + request := restoredRuntimeRequest() + request.runner = func(ctx context.Context, core runtimecore.RuntimeStartRequest) (StartResult, error) { + defer close(finished) + if !core.Reconnect || time.Duration(core.ReconnectDelay(0)) != 5*time.Second { + return StartResult{}, errors.New("runtime core reconnect policy was not installed") + } + core.Observer.OnRuntimeEvent(ctx, runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "prepared", DeviceID: core.DeviceID, TraceID: core.TraceID, + }) + close(started) + <-release + session := &runtimecore.SessionResult{DeviceID: core.DeviceID} + core.Observer.OnRuntimeEvent(ctx, runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "established", Handle: session, DeviceID: core.DeviceID, + TraceID: core.TraceID, Snapshot: runtimecore.Snapshot{Established: true}, + }) + <-ctx.Done() + core.Observer.OnRuntimeEvent(ctx, runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "stopped", Handle: session, DeviceID: core.DeviceID, TraceID: core.TraceID, + }) + return StartResult{TraceID: core.TraceID}, ctx.Err() + } + + type result struct { + instance *Instance + err error + } + resultChannel := make(chan result, 1) + go func() { + instance, err := Start(ctx, request) + resultChannel <- result{instance: instance, err: err} + }() + <-started + select { + case got := <-resultChannel: + t.Fatalf("Start returned before ipsec_up: %+v", got) + default: + } + close(release) + got := <-resultChannel + if got.err != nil || got.instance == nil { + t.Fatalf("Start instance=%v err=%v", got.instance, got.err) + } + state := got.instance.State() + if !state.TunnelReady || state.LastEvent != "ipsec_up" || state.NetworkMode != "wifi" { + t.Fatalf("runtime state = %+v", state) + } + if state.EPDGAddress != "epdg.example.com" || state.DataplaneMode != swu.DataplaneModeUserspace { + t.Fatalf("runtime metadata = %+v", state) + } + got.instance.mu.RLock() + hasSession := got.instance.session != nil + got.instance.mu.RUnlock() + if !hasSession { + t.Fatal("ipsec_up did not retain the runtime session") + } + if err := got.instance.Stop(context.Background()); err != nil { + t.Fatalf("Stop: %v", err) + } + <-finished +} + +func TestReaderStartReturnsBeforeRuntimeReady(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + started := make(chan struct{}) + finished := make(chan struct{}) + request := restoredRuntimeRequest() + request.Mode = StartModeReader + request.runner = func(ctx context.Context, core runtimecore.RuntimeStartRequest) (StartResult, error) { + defer close(finished) + if time.Duration(core.ReconnectDelay(1)) != 60*time.Second { + return StartResult{}, errors.New("reader reconnect policy was not installed") + } + close(started) + <-ctx.Done() + return StartResult{TraceID: core.TraceID}, ctx.Err() + } + instance, err := Start(ctx, request) + if err != nil || instance == nil { + t.Fatalf("reader Start instance=%v err=%v", instance, err) + } + <-started + if state := instance.State(); state.Phase != "starting" || state.TunnelReady { + t.Fatalf("reader initial state = %+v", state) + } + cancel() + <-finished + if err := instance.Stop(context.Background()); err != nil { + t.Fatalf("reader Stop: %v", err) + } +} + +func TestMainStartExposesRunnerFailureBeforeReady(t *testing.T) { + want := errors.New("core start rejected") + request := restoredRuntimeRequest() + request.runner = func(context.Context, runtimecore.RuntimeStartRequest) (StartResult, error) { + return StartResult{TraceID: request.TraceID}, want + } + instance, err := Start(context.Background(), request) + if instance != nil || !errors.Is(err, want) { + t.Fatalf("Start instance=%v err=%v, want %v", instance, err, want) + } +} + +func TestCoreRequestConvertsCompleteBeforeStartConfig(t *testing.T) { + request := restoredRuntimeRequest() + request.Dataplane.TUNName = "vowifi-test0" + request.DNSServer = "192.0.2.53" + request.Proxy = &ProxyConfig{ID: "p1", Addr: "127.0.0.1:1080", Enabled: true} + var received SessionConfig + request.BeforeStart = func(_ context.Context, config SessionConfig) error { + received = config + return nil + } + core := request.coreRequest() + if core.BeforeSessionStart == nil || core.Prepared == nil { + t.Fatal("core request dropped prepared session or BeforeStart") + } + ctx := context.Background() + err := core.BeforeSessionStart(ctx, runtimecore.SessionConfig{ + Ctx: ctx, DeviceID: core.DeviceID, TraceID: core.TraceID, Prepared: *core.Prepared, + DataplaneMode: core.Dataplane.Mode, TUNName: core.Dataplane.TUNName, + Proxy: core.Proxy, DNSServer: core.DNSServer, + }) + if err != nil { + t.Fatalf("BeforeSessionStart: %v", err) + } + if received.Ctx != ctx || received.DeviceID != request.DeviceID || received.TraceID != request.TraceID { + t.Fatalf("BeforeStart identity = %+v", received) + } + if received.Prepared.Profile.IMSI != request.Prepared.Profile.IMSI || received.TUNName != "vowifi-test0" { + t.Fatalf("BeforeStart prepared/dataplane = %+v", received) + } + if received.Proxy == nil || received.Proxy.Addr != request.Proxy.Addr || received.DNSServer != request.DNSServer { + t.Fatalf("BeforeStart network = %+v", received) + } +} + +func TestRecoveredPreparedSessionConversionsDetachCarrierData(t *testing.T) { + request := restoredRuntimeRequest() + request.Prepared.EffectiveCarrier.MCC = request.Prepared.Profile.MCC + request.Prepared.EffectiveCarrier.MNC = request.Prepared.Profile.MNC + request.Prepared.EffectiveCarrier.IKEProposals = []string{"aes128-sha256-modp2048"} + request.Prepared.AuthPlan = identity.AuthPlan{EPDGApp: "ISIM", IMSApp: "invalid"} + internal := preparedSessionPtrToInternal(request.Prepared) + if internal == nil || internal.AuthPlan.EPDGApp != "isim" || internal.AuthPlan.IMSApp != "usim" { + t.Fatalf("internal auth plan = %+v", internal) + } + request.Prepared.EffectiveCarrier.IKEProposals[0] = "changed" + if got := internal.CarrierPlan.IKE.IKEProposals[0]; got != "aes128-sha256-modp2048" { + t.Fatalf("internal proposal retained caller alias: %q", got) + } + external := preparedSessionFromInternal(*internal) + internal.CarrierPlan.IKE.IKEProposals[0] = "changed-again" + if got := external.EffectiveCarrier.IKEProposals[0]; got != "aes128-sha256-modp2048" { + t.Fatalf("external proposal retained internal alias: %q", got) + } +} + +func TestRuntimeEventNamesAndStateAreRecovered(t *testing.T) { + instance := &Instance{} + observer := &instanceObserver{inst: instance, deviceID: "dev-1"} + observer.OnRuntimeEvent(context.Background(), runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "retry", Attempt: 2, RetryDelay: int64(time.Second), RedirectEPDG: "epdg-2.example", + }) + state := instance.State() + if state.LastEvent != "retrying" || state.Phase != "retrying" || state.LastRedirectEPDG != "epdg-2.example" { + t.Fatalf("retry state = %+v", state) + } + observer.OnRuntimeEvent(context.Background(), runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "error", Message: "authentication rejected", + }) + state = instance.State() + if state.LastEvent != "terminal_error" || state.LastError != "authentication rejected" { + t.Fatalf("terminal state = %+v", state) + } +} + +func restoredRuntimeRequest() StartRequest { + return StartRequest{ + Mode: StartModeMain, DeviceID: "dev-1", TraceID: "trace-1", NetworkMode: "wifi", + Prepared: &identity.PreparedSession{ + Profile: identity.Profile{IMSI: "310260123456789", MCC: "310", MNC: "260"}, + IMSIdentity: identity.IMSIdentityResult{ + IMPI: "310260123456789@ims.example", IMPU: "sip:310260123456789@ims.example", + Domain: "ims.example", Applied: true, + }, + EPDGAddr: "epdg.example.com", + }, + SIM: NewReaderSIMAdapter(startAKAProvider{}), + Dataplane: DataplanePolicy{Mode: swu.DataplaneModeUserspace}, + } +} diff --git a/third_party/vowifi-go/runtimehost/runtimecore_adapters.go b/third_party/vowifi-go/runtimehost/runtimecore_adapters.go index aa728a93..c31dce75 100644 --- a/third_party/vowifi-go/runtimehost/runtimecore_adapters.go +++ b/third_party/vowifi-go/runtimehost/runtimecore_adapters.go @@ -3,27 +3,12 @@ package runtimehost import ( "time" - enginesim "github.com/iniwex5/vowifi-go/engine/sim" "github.com/iniwex5/vowifi-go/internal/vowifi/events" - "github.com/iniwex5/vowifi-go/internal/vowifi/profile" - "github.com/iniwex5/vowifi-go/internal/vowifi/simauth" "github.com/iniwex5/vowifi-go/internal/vowifi/smsdelivery" "github.com/iniwex5/vowifi-go/runtimehost/eventhost" "github.com/iniwex5/vowifi-go/runtimehost/messaging" ) -type runtimeCoreSIMAdapter struct{ aka enginesim.AKAProvider } - -func (adapter runtimeCoreSIMAdapter) EPDGSIMProvider(profile.AuthPlan) enginesim.AKAProvider { - return adapter.aka -} - -func (adapter runtimeCoreSIMAdapter) IMSAKAProvider(profile.AuthPlan) simauth.AKAProvider { - return adapter.aka -} - -func (runtimeCoreSIMAdapter) IMSIdentityProvider() profile.Provider { return nil } - func runtimeCoreDispatcher(dispatcher eventhost.Dispatcher) events.EventDispatcher { if dispatcher == nil { return nil diff --git a/third_party/vowifi-go/runtimehost/runtimecore_conversion.go b/third_party/vowifi-go/runtimehost/runtimecore_conversion.go new file mode 100644 index 00000000..549ea329 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/runtimecore_conversion.go @@ -0,0 +1,88 @@ +package runtimehost + +import ( + "github.com/iniwex5/vowifi-go/internal/runtimehostcarrier" + "github.com/iniwex5/vowifi-go/internal/vowifi/policy" + internalprofile "github.com/iniwex5/vowifi-go/internal/vowifi/profile" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" + "github.com/iniwex5/vowifi-go/runtimehost/identity" +) + +func sessionConfigFromInternal(config runtimecore.SessionConfig) SessionConfig { + return SessionConfig{ + Ctx: config.Ctx, DeviceID: config.DeviceID, TraceID: config.TraceID, + Prepared: preparedSessionFromInternal(config.Prepared), + DataplaneMode: config.DataplaneMode, TUNName: config.TUNName, + Proxy: proxyFromInternal(config.Proxy), DNSServer: config.DNSServer, + } +} + +func authPlanToInternal(value identity.AuthPlan) internalprofile.AuthPlan { + return internalprofile.AuthPlan{ + EPDGApp: internalprofile.NormalizeAKAApp(value.EPDGApp), + IMSApp: internalprofile.NormalizeAKAApp(value.IMSApp), + } +} + +func preparedSessionFromInternal(value internalprofile.PreparedSession) identity.PreparedSession { + carrierConfig := runtimehostcarrier.FromInternal( + policy.EffectiveCarrierConfigFromCarrierPlan(value.CarrierPlan), + ) + return identity.PreparedSession{ + Profile: identity.Profile{ + IMSI: value.Profile.IMSI, MCC: value.Profile.MCC, MNC: value.Profile.MNC, + IMEI: value.Profile.IMEI, UserAgent: value.Profile.UserAgent, + SMSC: value.Profile.SMSC, IMSDomain: value.Profile.IMSDomain, + }, + EffectiveCarrier: carrierConfig, + IMSIdentity: identity.IMSIdentityResult{ + RequestedSource: value.IMSIdentity.RequestedSource, + ActualSource: value.IMSIdentity.ActualSource, + AKAAppPreference: value.IMSIdentity.AKAAppPreference, + Applied: value.IMSIdentity.Applied, IMPI: value.IMSIdentity.IMPI, + IMPU: value.IMSIdentity.IMPU, Domain: value.IMSIdentity.Domain, + }, + AuthPlan: identity.AuthPlan{ + EPDGApp: value.AuthPlan.EPDGApp, IMSApp: value.AuthPlan.IMSApp, + }, + EPDGAddr: value.EPDGAddr, EPDGSource: value.EPDGSource, + IdentityIMEISource: value.IdentityIMEISource, CarrierConfig: carrierConfig, + } +} + +func preparedSessionPtrToInternal(value *identity.PreparedSession) *internalprofile.PreparedSession { + if value == nil { + return nil + } + carrierConfig := runtimehostcarrier.ToInternal(value.ResolvedCarrierConfig()) + return &internalprofile.PreparedSession{ + Profile: internalprofile.Profile{ + IMSI: value.Profile.IMSI, MCC: value.Profile.MCC, MNC: value.Profile.MNC, + IMEI: value.Profile.IMEI, UserAgent: value.Profile.UserAgent, + SMSC: value.Profile.SMSC, IMSDomain: value.Profile.IMSDomain, + }, + CarrierPlan: policy.CarrierPlanFromEffectiveConfig(carrierConfig), + IMSIdentity: internalprofile.IMSIdentityResult{ + RequestedSource: value.IMSIdentity.RequestedSource, + ActualSource: value.IMSIdentity.ActualSource, + AKAAppPreference: value.IMSIdentity.AKAAppPreference, + Applied: value.IMSIdentity.Applied, + IMPI: value.IMSIdentity.IMPI, + IMPU: value.IMSIdentity.IMPU, + Domain: value.IMSIdentity.Domain, + }, + AuthPlan: authPlanToInternal(value.AuthPlan), + EPDGAddr: value.EPDGAddr, EPDGSource: value.EPDGSource, + IdentityIMEISource: value.IdentityIMEISource, + } +} + +func proxyFromInternal(proxy *runtimecore.ProxyConfig) *ProxyConfig { + if proxy == nil { + return nil + } + return &ProxyConfig{ + ID: proxy.ID, Addr: proxy.Addr, Username: proxy.Username, + Password: proxy.Password, Enabled: proxy.Enabled, + } +} diff --git a/third_party/vowifi-go/runtimehost/runtimecore_observer.go b/third_party/vowifi-go/runtimehost/runtimecore_observer.go new file mode 100644 index 00000000..357424f0 --- /dev/null +++ b/third_party/vowifi-go/runtimehost/runtimecore_observer.go @@ -0,0 +1,146 @@ +package runtimehost + +import ( + "context" + "strings" + "sync" + "time" + + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" +) + +type instanceObserver struct { + inst *Instance + deviceID string + ready chan struct{} + readyOnce sync.Once +} + +func (observer *instanceObserver) OnRuntimeEvent( + ctx context.Context, + event runtimecore.RuntimeEvent[*runtimecore.SessionResult], +) { + if observer == nil || observer.inst == nil { + return + } + kind := recoveredEventKind(event.Kind) + state := observer.inst.State() + if state.DeviceID == "" { + state.DeviceID = observer.deviceID + } + if strings.TrimSpace(event.DeviceID) != "" { + state.DeviceID = strings.TrimSpace(event.DeviceID) + } + if strings.TrimSpace(event.RedirectEPDG) != "" { + state.LastRedirectEPDG = strings.TrimSpace(event.RedirectEPDG) + } + observer.applyEvent(kind, event, &state) + state.LastEvent = kind + state.UpdatedAt = time.Now() + observer.inst.setState(state) + observer.inst.publish(ctx, Event{ + Kind: kind, DeviceID: state.DeviceID, TraceID: event.TraceID, + Reason: event.Reason, Attempt: event.Attempt, RetryDelay: event.RetryDelay, + RedirectEPDG: event.RedirectEPDG, State: state, + Type: kind, Detail: event.Reason, Session: observer.inst, + }) +} + +func (observer *instanceObserver) applyEvent( + kind string, + event runtimecore.RuntimeEvent[*runtimecore.SessionResult], + state *State, +) { + switch kind { + case "prepared": + state.Phase = PhaseSIMReady + state.SIMReady = true + case "ipsec_up": + observer.installSession(event) + state.Phase = readyPhase(*state) + state.SessionState = "established" + state.TunnelReady = event.Snapshot.Established || event.Handle != nil + state.DataPlaneUp = state.TunnelReady + if observer.ready != nil { + observer.readyOnce.Do(func() { close(observer.ready) }) + } + case "ims_registered": + observer.installService(event) + state.Phase = "ims_ready" + state.IMSState = "registered" + state.IMSReady = true + state.RegStatus = 1 + state.RegStatusText = "registered" + case "sms_ready": + state.Phase = "sms_ready" + state.SMSReady = true + case "interrupted": + state.Phase = "interrupted" + state.TunnelReady = false + state.IMSReady = false + state.SMSReady = false + state.DataPlaneUp = false + state.LastReason = strings.TrimSpace(event.Reason) + state.LastRedirectEPDG = strings.TrimSpace(event.RedirectEPDG) + case "retrying": + state.Phase = "retrying" + state.LastReason = strings.TrimSpace(event.Reason) + case "terminal_error": + state.Phase = "error" + state.SessionState = "error" + state.LastErrorClass = "runtime" + state.LastError = firstNonEmptyString(event.Message, event.Reason) + state.Error = state.LastError + case "stopped": + observer.inst.setService(nil) + observer.inst.setSession(nil) + state.Phase = "stopped" + state.SessionState = "stopped" + state.TunnelReady = false + state.IMSReady = false + state.SMSReady = false + state.DataPlaneUp = false + } +} + +func readyPhase(state State) string { + if state.SMSReady { + return "sms_ready" + } + if state.IMSReady { + return "ims_ready" + } + return "ipsec_up" +} + +func (observer *instanceObserver) installSession( + event runtimecore.RuntimeEvent[*runtimecore.SessionResult], +) { + observer.inst.setSession(event.Handle) + observer.installService(event) +} + +func (observer *instanceObserver) installService( + event runtimecore.RuntimeEvent[*runtimecore.SessionResult], +) { + service := event.Service + if service == nil && event.Handle != nil { + service = event.Handle.IMSService + } + if service != nil { + observer.inst.setService(newServiceAdapter(service)) + } +} + +func recoveredEventKind(kind string) string { + switch strings.TrimSpace(kind) { + case "established": + return "ipsec_up" + case "retry": + return "retrying" + case "error": + return "terminal_error" + default: + return strings.TrimSpace(kind) + } +} diff --git a/third_party/vowifi-go/runtimehost/runtimecore_start.go b/third_party/vowifi-go/runtimehost/runtimecore_start.go index c6fd171f..881aca71 100644 --- a/third_party/vowifi-go/runtimehost/runtimecore_start.go +++ b/third_party/vowifi-go/runtimehost/runtimecore_start.go @@ -3,77 +3,150 @@ package runtimehost import ( "context" "errors" - "fmt" + "strings" + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" + "github.com/iniwex5/vowifi-go/internal/vowifi/profile" "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" ) -func startRuntimeCore(ctx context.Context, req StartRequest) (*Instance, error) { - inst := &Instance{} - inst.setState(initialState(req)) - runCtx, cancel := context.WithCancel(ctx) - coreRequest, err := runtimeCoreStartRequest(req, inst) - if err != nil { - cancel() - inst.setStartFailure(err) - return inst, err - } - result, err := (runtimecore.Runtime{}).Start(runCtx, coreRequest) - if err != nil { - cancel() - startErr := fmt.Errorf("runtimehost: runtime core start failed: %w", err) - inst.setStartFailure(startErr) - return inst, startErr - } - installation := runtimeCoreInstallation{ - ctx: runCtx, request: req, instance: inst, cancel: cancel, - } - if err := installation.install(result); err != nil { - cancel() - runtimecore.StopSession(context.Background(), result.Session) - return failIMSStart(inst, err) - } - go stopRuntimeOnContext(runCtx, inst) - return inst, nil -} +type coreRunner func(context.Context, runtimecore.RuntimeStartRequest) (StartResult, error) +type reconnectDelay func(int) int64 -func runtimeCoreStartRequest( - req StartRequest, - inst *Instance, -) (runtimecore.RuntimeStartRequest, error) { - prepared, err := runtimecore.AdaptCompatibilityPreparedSession( - preparedForRuntimeCore(req.Prepared), - ) - if err != nil { - return runtimecore.RuntimeStartRequest{}, err - } - return runtimecore.RuntimeStartRequest{ - DeviceID: req.DeviceID, - TraceID: req.TraceID, - Prepared: &prepared, - SIM: runtimeCoreSIMAdapter{aka: req.SIM.AKAProvider()}, +func (req StartRequest) coreRequest() runtimecore.RuntimeStartRequest { + request := runtimecore.RuntimeStartRequest{ + DeviceID: strings.TrimSpace(req.DeviceID), TraceID: strings.TrimSpace(req.TraceID), + Profile: profile.Profile{ + IMSI: req.Profile.IMSI, MCC: req.Profile.MCC, MNC: req.Profile.MNC, + IMEI: req.Profile.IMEI, UserAgent: req.Profile.UserAgent, + SMSC: req.Profile.SMSC, IMSDomain: req.Profile.IMSDomain, + }, + Prepared: preparedSessionPtrToInternal(req.Prepared), + IMSIdentity: profile.IMSIdentityResult{ + RequestedSource: req.IMSIdentity.RequestedSource, + ActualSource: req.IMSIdentity.ActualSource, + AKAAppPreference: req.IMSIdentity.AKAAppPreference, + Applied: req.IMSIdentity.Applied, IMPI: req.IMSIdentity.IMPI, + IMPU: req.IMSIdentity.IMPU, Domain: req.IMSIdentity.Domain, + }, + SIM: req.SIM.runtimeSIMAdapter(), Dataplane: runtimecore.RuntimeDataplanePolicy{ - Mode: req.Dataplane.Mode, + Mode: req.Dataplane.Mode, TUNName: req.Dataplane.TUNName, }, - Proxy: runtimeCoreProxy(req.Proxy), + Proxy: runtimeCoreProxy(req.Proxy), DNSServer: req.DNSServer, DeliveryStore: runtimeCoreDeliveryStore(req.DeliveryStore), - Dispatch: runtimeCoreDispatcher(req.Dispatch), - Hooks: runtimecore.RuntimeHostHooks{ - OnConnecting: func(context.Context) { inst.updateTunnelState("connecting") }, - }, - BeforeSessionStart: runtimeCoreBeforeStart(req.BeforeStart), - }, nil + Dispatch: runtimeCoreDispatcher(req.Dispatch), ShouldRun: req.ShouldRun, + } + if req.BeforeStart != nil { + hook := req.BeforeStart + request.BeforeSessionStart = func(ctx context.Context, config runtimecore.SessionConfig) error { + return apiErrorToInternal(hook(ctx, sessionConfigFromInternal(config))) + } + } + if req.Access != nil { + request.Access = accessAdapter{host: req.Access} + } + if req.VoiceGateway != nil { + request.Options.Voice = voiceRuntimeLifecycle{gateway: req.VoiceGateway} + } + return request } -func runtimeCoreBeforeStart( - hook func(context.Context, SessionConfig) error, -) func(context.Context, runtimecore.SessionConfig) error { - if hook == nil { - return nil +func startInstance( + ctx context.Context, + request runtimecore.RuntimeStartRequest, + runner coreRunner, + delay reconnectDelay, +) (*Instance, error) { + instance, ready, done := launchRuntimeCore(ctx, request, runner, delay) + select { + case <-ctx.Done(): + _ = instance.Stop(context.Background()) + return nil, ctx.Err() + case err := <-done: + _ = instance.Stop(context.Background()) + if err == nil { + err = errors.New("runtimehost: runtime core stopped before IPsec became ready") + } + return nil, err + case <-ready: + return instance, nil } - return func(ctx context.Context, cfg runtimecore.SessionConfig) error { - return hook(ctx, SessionConfig{DataplaneMode: cfg.DataplaneMode}) +} + +func startInstanceAsync( + ctx context.Context, + request runtimecore.RuntimeStartRequest, + runner coreRunner, + delay reconnectDelay, +) (*Instance, error) { + instance, _, _ := launchRuntimeCore(ctx, request, runner, delay) + return instance, nil +} + +func launchRuntimeCore( + ctx context.Context, + request runtimecore.RuntimeStartRequest, + runner coreRunner, + delay reconnectDelay, +) (*Instance, <-chan struct{}, <-chan error) { + runCtx, cancel := context.WithCancel(ctx) + instance := &Instance{cancel: cancel} + instance.setState(coreInitialState(request)) + ready := make(chan struct{}) + observer := &instanceObserver{ + inst: instance, deviceID: request.DeviceID, ready: ready, } + request.Observer = observer + request.Reconnect = true + request.ReconnectDelay = delay + chainSMSReadyHook(&request, observer) + if runner == nil { + runner = defaultCoreRunner + } + done := make(chan error, 1) + go func() { + _, err := runner(runCtx, request) + done <- apiErrorToInternal(err) + }() + return instance, ready, done +} + +func coreInitialState(request runtimecore.RuntimeStartRequest) State { + return State{ + Phase: "starting", DeviceID: request.DeviceID, + DataplaneMode: request.Dataplane.Mode, SIMReady: request.SIM != nil, + AccessReady: request.Access != nil, LastEvent: "starting", + SessionState: "starting", + } +} + +func chainSMSReadyHook( + request *runtimecore.RuntimeStartRequest, + observer *instanceObserver, +) { + previous := request.Hooks.OnSMSReady + request.Hooks.OnSMSReady = func(ctx context.Context) { + if previous != nil { + previous(ctx) + } + observer.OnRuntimeEvent(ctx, runtimecore.RuntimeEvent[*runtimecore.SessionResult]{ + Kind: "sms_ready", DeviceID: request.DeviceID, TraceID: request.TraceID, + }) + } +} + +func defaultCoreRunner( + ctx context.Context, + request runtimecore.RuntimeStartRequest, +) (StartResult, error) { + result, err := (runtimecore.Runtime{}).Start(ctx, request) + return startResultFromInternal(result), err +} + +func startResultFromInternal(result runtimecore.RuntimeStartResult) StartResult { + return StartResult{TraceID: result.TraceID} } func runtimeCoreProxy(proxy *ProxyConfig) *runtimecore.ProxyConfig { @@ -86,35 +159,17 @@ func runtimeCoreProxy(proxy *ProxyConfig) *runtimecore.ProxyConfig { } } -type runtimeCoreInstallation struct { - ctx context.Context - request StartRequest - instance *Instance - cancel context.CancelFunc +type voiceRuntimeLifecycle struct { + gateway *voicehost.Gateway } -func (installation runtimeCoreInstallation) install(result runtimecore.RuntimeStartResult) error { - if result.Session == nil || result.Session.Session == nil || result.Session.EPDGMgr == nil { - return errors.New("runtimehost: runtime core returned no active SWu session") - } - if result.Session.IMSService == nil { - return errors.New("runtimehost: runtime core returned no IMS service") - } - tunnel := &swuTunnelAdapter{ - Session: result.Session.Session, manager: result.Session.EPDGMgr, - deviceID: installation.request.DeviceID, - } - service := newServiceAdapter(result.Session.IMSService) - installation.instance.attachTunnel(tunnel, installation.cancel) - installation.instance.setService(service) - wireSMSReadiness(installation.instance, service) - installation.instance.markTunnelReadyForIMS() - installation.instance.markIMSRegistered() - syncSMSReadiness(installation.instance, service) - if err := attachVoiceAgent(installation.request, installation.instance, service); err != nil { - return fmt.Errorf("runtimehost: attach voice agent: %w", err) - } - go monitorTunnelFailure(installation.ctx, installation.instance, tunnel) - go monitorRegistrationFailures(installation.ctx, installation.instance, service) - return nil +func (adapter voiceRuntimeLifecycle) AttachDevice( + deviceID string, + endpoint imsendpoint.Endpoint, +) error { + return adapter.gateway.AttachDeviceCurrent(deviceID, endpoint) +} + +func (adapter voiceRuntimeLifecycle) DetachDevice(deviceID string) { + adapter.gateway.DetachDeviceCurrent(deviceID) } diff --git a/third_party/vowifi-go/runtimehost/start.go b/third_party/vowifi-go/runtimehost/start.go index b8dad4fc..74659083 100644 --- a/third_party/vowifi-go/runtimehost/start.go +++ b/third_party/vowifi-go/runtimehost/start.go @@ -28,45 +28,39 @@ const ( defaultIMSSIPPort = 5060 ) -// StartMode selects the runtime host mode. -type StartMode string +// StartMode preserves the additive name without changing the recovered string field. +type StartMode = string const ( // StartModeMain runs the full IMS host. - StartModeMain StartMode = "main" + StartModeMain = "main" // StartModeReader runs a SIM-reader-only host. - StartModeReader StartMode = "reader" + StartModeReader = "reader" ) -// DeliveryStore persists SMS delivery state. -type DeliveryStore interface { - // (recovered as needed) -} - -// EventDispatcher dispatches runtime events. -type EventDispatcher interface { - Dispatch(event Event) -} - // StartRequest configures a runtime host start. type StartRequest struct { - Mode StartMode + Mode string DeviceID string TraceID string Profile identity.Profile Prepared *identity.PreparedSession + IMSIdentity identity.IMSIdentityResult NetworkMode string VoiceGateway *voicehost.Gateway SIM SIMAdapter - Access ModemAccessAdapter + Access identity.AccessAdapter Dataplane DataplanePolicy Proxy *ProxyConfig + DNSServer string DeliveryStore messaging.DeliveryStore Dispatch eventhost.Dispatcher - TunnelFactory TunnelFactory - IMSFactory IMSFactory BeforeStart func(context.Context, SessionConfig) error ShouldRun func() bool + runner func(context.Context, runtimecore.RuntimeStartRequest) (StartResult, error) + + TunnelFactory TunnelFactory + IMSFactory IMSFactory } // ModemAccessAdapter preserves the current name for the identity access ABI. @@ -85,17 +79,40 @@ func Start(ctx context.Context, req StartRequest) (*Instance, error) { if ctx == nil { ctx = context.Background() } + if err := validateCommonStartRequest(req); err != nil { + return nil, err + } + if req.TunnelFactory != nil || req.IMSFactory != nil { + return startCurrent(ctx, req) + } + waitForReady, delay := req.startPolicy() + coreRequest := req.coreRequest() + if !waitForReady { + instance, err := startInstanceAsync(ctx, coreRequest, req.runner, delay) + applyRequestMetadata(instance, req) + return instance, err + } + instance, err := startInstance(ctx, coreRequest, req.runner, delay) + applyRequestMetadata(instance, req) + return instance, err +} + +func (req StartRequest) startPolicy() (bool, reconnectDelay) { + if req.Mode == StartModeReader { + return false, defaultReaderReconnectDelay + } + return true, defaultMainReconnectDelay +} + +func startCurrent(ctx context.Context, req StartRequest) (*Instance, error) { if req.ShouldRun != nil && !req.ShouldRun() { return nil, errors.New("runtimehost: start cancelled by ShouldRun") } - if err := validateStartRequest(req); err != nil { + if err := validateCurrentStartRequest(req); err != nil { return nil, err } - if req.TunnelFactory == nil && req.IMSFactory == nil { - return startRuntimeCore(ctx, req) - } if req.BeforeStart != nil { - if err := req.BeforeStart(ctx, SessionConfig{DataplaneMode: req.Dataplane.Mode}); err != nil { + if err := req.BeforeStart(ctx, currentSessionConfig(ctx, req)); err != nil { return nil, err } } @@ -121,7 +138,7 @@ func Start(ctx context.Context, req StartRequest) (*Instance, error) { if err != nil { return failIMSStart(inst, err) } - inst.setService(ims) + inst.setService(lifecycleServiceAdapter{lifecycle: ims}) wireSMSReadiness(inst, ims) registrationCtx, registrationCancel := context.WithTimeout(runCtx, imsRegistrationTimeout) err = ims.Register(registrationCtx) @@ -140,6 +157,19 @@ func Start(ctx context.Context, req StartRequest) (*Instance, error) { return inst, nil } +func applyRequestMetadata(instance *Instance, request StartRequest) { + if instance == nil { + return + } + instance.mu.Lock() + instance.state.NetworkMode = request.NetworkMode + instance.state.EPDGAddress = epdgOf(request) + if instance.state.DataplaneMode == "" { + instance.state.DataplaneMode = request.Dataplane.Mode + } + instance.mu.Unlock() +} + func monitorTunnelFailure(ctx context.Context, inst *Instance, tunnel Tunnel) { waitErr := tunnel.WaitDoneContext(ctx) if ctx.Err() != nil { @@ -207,17 +237,11 @@ func failIMSStart(inst *Instance, err error) (*Instance, error) { return inst, err } -func validateStartRequest(req StartRequest) error { +func validateCommonStartRequest(req StartRequest) error { if strings.TrimSpace(req.DeviceID) == "" { return errors.New("runtimehost: device_id is empty") } - if req.Prepared == nil { - return errors.New("runtimehost: prepared session is required") - } - if strings.TrimSpace(req.Prepared.EPDGAddr) == "" { - return errors.New("runtimehost: prepared session has no ePDG address") - } - if req.SIM == nil || req.SIM.AKAProvider() == nil { + if req.SIM == nil || req.SIM.runtimeSIMAdapter() == nil { return errors.New("runtimehost: SIM AKA provider is required") } mode := strings.TrimSpace(req.Dataplane.Mode) @@ -230,17 +254,40 @@ func validateStartRequest(req StartRequest) error { return nil } +func validateCurrentStartRequest(req StartRequest) error { + if req.Prepared == nil { + return errors.New("runtimehost: prepared session is required") + } + if strings.TrimSpace(req.Prepared.EPDGAddr) == "" { + return errors.New("runtimehost: prepared session has no ePDG address") + } + provider := req.SIM.runtimeSIMAdapter().EPDGSIMProvider(runtimeAuthPlan(req.Prepared)) + if provider == nil { + return errors.New("runtimehost: SIM AKA provider is required") + } + return nil +} + +func currentSessionConfig(ctx context.Context, req StartRequest) SessionConfig { + return SessionConfig{ + Ctx: ctx, DeviceID: req.DeviceID, TraceID: req.TraceID, Prepared: *req.Prepared, + DataplaneMode: req.Dataplane.Mode, TUNName: req.Dataplane.TUNName, + Proxy: req.Proxy, DNSServer: req.DNSServer, + } +} + func initialState(req StartRequest) State { return State{ - SessionState: "starting", - DeviceID: req.DeviceID, EPDGAddress: epdgOf(req), NetworkMode: req.NetworkMode, + Phase: "starting", SessionState: "starting", LastEvent: "starting", + DeviceID: req.DeviceID, EPDGAddress: epdgOf(req), NetworkMode: req.NetworkMode, DataplaneMode: req.Dataplane.Mode, SIMReady: true, AccessReady: req.Access != nil, } } func newTunnel(req StartRequest, inst *Instance) (Tunnel, error) { prepared := preparedForRuntimeCore(req.Prepared) - cfg, err := runtimecore.BuildCompatibilitySWUConfig(prepared, req.SIM.AKAProvider()) + provider := req.SIM.runtimeSIMAdapter().EPDGSIMProvider(runtimeAuthPlan(req.Prepared)) + cfg, err := runtimecore.BuildCompatibilitySWUConfig(prepared, provider) if err != nil { return nil, err } @@ -270,10 +317,7 @@ func newTunnel(req StartRequest, inst *Instance) (Tunnel, error) { } func preparedForRuntimeCore(prepared *identity.PreparedSession) *runtimecore.PreparedSessionStart { - authPlan := profile.NewAuthPlan(prepared.AuthPlan.EPDGApp, prepared.AuthPlan.IMSApp) - if prepared.AuthPlan == (identity.AuthPlan{}) { - authPlan = authPlanForPreference(string(prepared.IMSIdentity.AKAAppPreference)) - } + authPlan := runtimeAuthPlan(prepared) return &runtimecore.PreparedSessionStart{ Profile: profile.Profile{ IMSI: prepared.Profile.IMSI, MCC: prepared.Profile.MCC, MNC: prepared.Profile.MNC, @@ -301,6 +345,16 @@ func preparedForRuntimeCore(prepared *identity.PreparedSession) *runtimecore.Pre } } +func runtimeAuthPlan(prepared *identity.PreparedSession) profile.AuthPlan { + if prepared == nil { + return profile.AuthPlan{} + } + if prepared.AuthPlan != (identity.AuthPlan{}) { + return authPlanToInternal(prepared.AuthPlan).Normalize() + } + return authPlanForPreference(prepared.IMSIdentity.AKAAppPreference) +} + func authPlanForPreference(preference string) profile.AuthPlan { normalized := profile.NormalizeAKAApp(preference) plan := profile.NewAuthPlan(normalized, normalized) @@ -337,7 +391,7 @@ func newIMS(req StartRequest, tunnel Tunnel) (IMSLifecycle, error) { if err != nil { return nil, err } - return newServiceAdapter(svc), nil + return &imscoreLifecycleAdapter{svc: svc}, nil } // imscoreFromPrepared builds an imscore.Service from the prepared session. @@ -392,7 +446,7 @@ func imscoreFromPrepared(req StartRequest, tunnel Tunnel) (*imscore.Service, err Transport: registerTemplate.Transport, Expires: registerTemplate.Expires, TraceID: req.TraceID, - AKAProvider: req.SIM.AKAProvider(), + AKAProvider: req.SIM.runtimeSIMAdapter().EPDGSIMProvider(runtimeAuthPlan(req.Prepared)), IMSNetwork: imsNetwork, UserAgent: userAgent, CellularNetworkInfo: imscore.GenerateDefaultCellularNetworkInfo( diff --git a/third_party/vowifi-go/runtimehost/start_test.go b/third_party/vowifi-go/runtimehost/start_test.go index 589c7148..1cbf0885 100644 --- a/third_party/vowifi-go/runtimehost/start_test.go +++ b/third_party/vowifi-go/runtimehost/start_test.go @@ -11,6 +11,8 @@ import ( enginesim "github.com/iniwex5/vowifi-go/engine/sim" "github.com/iniwex5/vowifi-go/engine/swu" + "github.com/iniwex5/vowifi-go/internal/vowifi/access" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" "github.com/iniwex5/vowifi-go/runtimehost/identity" ) @@ -41,7 +43,9 @@ func (startAKAProvider) CalculateAKA(_, _ []byte) (enginesim.AKAResult, error) { type startSIMAdapter struct{} -func (startSIMAdapter) AKAProvider() enginesim.AKAProvider { return startAKAProvider{} } +func (startSIMAdapter) runtimeSIMAdapter() access.SIMAdapter { + return runtimecore.NewReaderSIMAdapter(startAKAProvider{}) +} type lifecycleTunnel struct { mu sync.Mutex @@ -60,7 +64,7 @@ type lifecycleTunnel struct { } type lifecycleIMS struct { - Service + CurrentService registerErr error deviceID string registered bool @@ -335,7 +339,9 @@ func TestStartShouldRunFalse(t *testing.T) { } func TestStartDefaultRoutesThroughRuntimeCorePreparation(t *testing.T) { - _, err := Start(context.Background(), StartRequest{ + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + _, err := Start(ctx, StartRequest{ DeviceID: "dev-1", Prepared: &identity.PreparedSession{ EPDGAddr: "epdg.example.com", @@ -343,8 +349,8 @@ func TestStartDefaultRoutesThroughRuntimeCorePreparation(t *testing.T) { SIM: startSIMAdapter{}, Dataplane: DataplanePolicy{Mode: swu.DataplaneModeUserspace}, }) - if err == nil || !strings.Contains(err.Error(), "runtimecore: prepared session has no IMSI") { - t.Fatalf("Start error = %v, want runtimecore preparation error", err) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Start error = %v, want bounded reconnect cancellation", err) } } @@ -376,8 +382,8 @@ func TestStartMarksIMSReadyOnlyAfterRegister(t *testing.T) { } // The real service adapter should report the device ID. st := svc.Status() - if st.State.DeviceID != "dev-1" { - t.Errorf("device = %q, want dev-1", st.State.DeviceID) + if st["device_id"] != "dev-1" { + t.Errorf("device = %v, want dev-1", st["device_id"]) } if !inst.State().IMSReady || !inst.State().SMSReady || inst.State().IMSState != "registered" { t.Errorf("IMS state = %+v", inst.State()) @@ -513,11 +519,11 @@ func TestStartContextCancellationStopsTunnel(t *testing.T) { t.Fatalf("Start: %v", err) } stopped := make(chan struct{}, 1) - inst.AddObserver(func(_ context.Context, event Event) { + inst.AddObserver(ObserverFunc(func(_ context.Context, event Event) { if event.State.SessionState == "stopped" { stopped <- struct{}{} } - }) + })) cancel() select { case <-stopped: diff --git a/third_party/vowifi-go/runtimehost/types.go b/third_party/vowifi-go/runtimehost/types.go index 9476566b..1a02eb7c 100644 --- a/third_party/vowifi-go/runtimehost/types.go +++ b/third_party/vowifi-go/runtimehost/types.go @@ -1,8 +1,4 @@ -// Package runtimehost is the IMS runtime host: it owns the VoWiFi session -// lifecycle, exposes SMS/USSD services and publishes runtime events. -// -// Reconstructed from the decompiled engine/runtimehost. The Instance is the -// central object the vohive host wires the modem, SIM and IMS service into. +// Package runtimehost owns the public VoWiFi runtime lifecycle. package runtimehost import ( @@ -14,138 +10,118 @@ import ( enginesim "github.com/iniwex5/vowifi-go/engine/sim" "github.com/iniwex5/vowifi-go/engine/swu" + "github.com/iniwex5/vowifi-go/internal/vowifi/access" + "github.com/iniwex5/vowifi-go/internal/vowifi/runtimecore" "github.com/iniwex5/vowifi-go/runtimehost/identity" "github.com/iniwex5/vowifi-go/runtimehost/messaging" ) -// ErrorClassReauthentication marks an expected runtime replacement boundary. const ErrorClassReauthentication = "reauth" -// State is the runtime state of the IMS host (session + IMS registration). +// State retains the exact v1.5.5 field prefix. Current projections follow it. type State struct { - // Session state (e.g. "idle", "connecting", "established", "error"). - SessionState string - // IMS registration state. - IMSState string - // Error text when the session is in an error state. - Error string - // Whether the data plane is up. - DataPlaneUp bool - // Whether the session is behind NAT. - NATDetected bool - // The negotiated ePDG address. - EPDGAddress string - // Network mode at startup. - NetworkMode string - // Runtime phase (e.g. PhaseSIMReady). - Phase string - // Last state update time. - UpdatedAt time.Time - // Last error class (e.g. "auth", "network"). - LastErrorClass string - // Registration status code (modem convention: 1 = registered). - RegStatus int - // Registration status text. - RegStatusText string - // Last error text. - LastError string - // Last failure reason. - LastReason string - // Device id. - DeviceID string - // Data plane mode. - DataplaneMode string - // Whether the SIM is ready. - SIMReady bool - // Whether the modem access is ready. - AccessReady bool - // Whether the tunnel is ready. - TunnelReady bool - // Whether IMS is ready. - IMSReady bool - // Whether SMS is ready. - SMSReady bool - // SMSReadyReason explains which real SMS prerequisite is missing. + Phase string + DeviceID string + DataplaneMode string + NetworkMode string + SIMReady bool + AccessReady bool + TunnelReady bool + IMSReady bool + SMSReady bool + RegStatus int + RegStatusText string + LastEvent string + LastReason string + LastRedirectEPDG string + LastErrorClass string + LastError string + UpdatedAt time.Time + + SessionState string + IMSState string + Error string + DataPlaneUp bool + NATDetected bool + EPDGAddress string SMSReadyReason string } -// Event is a runtime event published to observers. +// Event retains the recovered runtime event payload before additive fields. type Event struct { + Kind string + DeviceID string + TraceID string + Reason string + Attempt int + RetryDelay int64 + RedirectEPDG string + State State + Type string Detail string - State State Session *Instance } -// ObserverFunc receives runtime events. -type ObserverFunc func(ctx context.Context, ev Event) +type Observer interface { + OnRuntimeHostEvent(context.Context, Event) +} -// Notifier receives session notifications (e.g. SMS/USSD events). -type Notifier func(msg string) +type ObserverFunc func(context.Context, Event) +type Notifier func(string) +type SMSNotifier func(string, string, string, time.Time) -// SMSNotifier receives SMS delivery notifications. -type SMSNotifier func(deviceID, sender, content string, ts time.Time) +// Service is the original root service surface. +type Service = messaging.Service -// Service is the IMS service surface exposed by the runtime host. -type Service interface { - SendSMSWithOptions(ctx context.Context, to, text string, opts messaging.SendOptions) (messaging.SendOutcome, error) - SendSMSWithResult(ctx context.Context, to, text string) (messaging.SendOutcome, error) - GetSMSDeliveryStatus(ctx context.Context, ref string) (*messaging.DeliveryStatus, error) - SendUSSD(ctx context.Context, code string) (*messaging.USSDResult, error) - ContinueUSSD(ctx context.Context, sessionID, input string) (*messaging.USSDResult, error) - CancelUSSD(ctx context.Context, sessionID string) error +type SendOptions = messaging.SendOptions +type SendOutcome = messaging.SendOutcome +type DeliveryStatus = messaging.DeliveryStatus +type USSDResult = messaging.USSDResult + +// Status is retained for callers of the post-v1.5.5 lifecycle injection API. +type Status struct { + State State +} + +// CurrentService is the displaced lifecycle injection surface. +type CurrentService interface { + SendSMSWithOptions(context.Context, string, string, messaging.SendOptions) (messaging.SendOutcome, error) + SendSMSWithResult(context.Context, string, string) (messaging.SendOutcome, error) + GetSMSDeliveryStatus(context.Context, string) (*messaging.DeliveryStatus, error) + SendUSSD(context.Context, string) (*messaging.USSDResult, error) + ContinueUSSD(context.Context, string, string) (*messaging.USSDResult, error) + CancelUSSD(context.Context, string) error Status() Status StatusSnapshot() Status Stop() TriggerRegisterImmediate() error } -// SendOptions carries optional SMS delivery parameters. -type SendOptions = messaging.SendOptions - -// SendOutcome is the result of an SMS send. -type SendOutcome = messaging.SendOutcome - -// DeliveryStatus is the delivery status of an SMS. -type DeliveryStatus = messaging.DeliveryStatus - -// USSDResult is the result of a USSD operation. -type USSDResult = messaging.USSDResult - -// Status is a snapshot of the runtime host status. -type Status struct { - State State -} - -// Modem is the modem access surface the runtime host drives. +// Modem is the exact modem boundary used by the original runtime host. type Modem interface { - Capabilities() ModemCapabilities - IMSIdentityProvider() IMSIdentityProvider + CloseLogicalChannel(int) error + DeviceID() string + ExecuteATSilent(string, time.Duration) (string, error) GetNetworkMode() string - // GetRegStatus returns the registration status code and text. The code - // follows the vohive modem convention (1 = registered). GetRegStatus() (int, string) + IsHealthy() bool + IsSimInserted() bool + OpenLogicalChannel(string) (int, error) + QuerySIMInserted() (bool, error) + Stop() + TransmitAPDU(int, string) (string, error) } -// ModemCapabilities preserves the current name for identity capabilities. type ModemCapabilities = identity.AccessCapabilities - -// IMSIdentityProvider reads the IMS identity from the SIM. type IMSIdentityProvider = identity.IMSIdentityProvider -// Identity is an IMS identity (IMSI/IMPI/IMPU). -type Identity struct { - IMSI string - IMPI string - IMPU string -} - -// SIMAdapter is the SIM access surface. +// SIMAdapter deliberately has an unexported method, matching v1.5.5. Hosts +// obtain one through NewReaderSIMAdapter instead of implementing it directly. type SIMAdapter interface { - AKAProvider() enginesim.AKAProvider + runtimeSIMAdapter() access.SIMAdapter } -// Tunnel is the SWu session lifecycle owned by a runtime Instance. type Tunnel interface { Connect(context.Context) error Shutdown() @@ -153,16 +129,16 @@ type Tunnel interface { WaitDoneContext(context.Context) error InnerNetwork() swu.InnerNetworkConfig InnerPacketIO() swu.InnerPacketIO - UpdateAddresses(oldIP, newIP net.IP) error + UpdateAddresses(net.IP, net.IP) error } type tunnelFailureSource interface { TerminalError() error } -// IMSLifecycle is the registered IMS service owned by the runtime Instance. +// IMSLifecycle is additive and only used by explicitly injected current factories. type IMSLifecycle interface { - Service + CurrentService Register(context.Context) error } @@ -170,7 +146,6 @@ type registrationFailureSource interface { RegistrationErrors() <-chan error } -// SMSReadiness describes the independently verifiable IMS SMS prerequisites. type SMSReadiness struct { Registered bool ProfileReady bool @@ -186,14 +161,9 @@ type smsReadinessSource interface { SetOnSMSReadinessChanged(func(SMSReadiness)) } -// IMSFactory builds the IMS lifecycle after SWu has established. type IMSFactory func(StartRequest, Tunnel) (IMSLifecycle, error) - -// TunnelFactory builds an SWu tunnel from the prepared configuration. -// Tests and alternate hosts can inject the transport boundary explicitly. type TunnelFactory func(*swu.Config) (Tunnel, error) -// ProxyConfig configures the ePDG proxy path. type ProxyConfig struct { ID string Addr string @@ -202,112 +172,65 @@ type ProxyConfig struct { Enabled bool } -// SessionConfig configures the SWu session. type SessionConfig struct { + Ctx context.Context + DeviceID string + TraceID string + Prepared identity.PreparedSession DataplaneMode string + TUNName string + Proxy *ProxyConfig + DNSServer string } -// DataplanePolicy selects the data-plane implementation. type DataplanePolicy struct { - Mode string + Mode string + TUNName string +} + +type StartResult struct { + TraceID string } -// ErrAPDUBusy is returned when the SIM APDU channel is busy. var ErrAPDUBusy error = apduBusyError{} type apduBusyError struct{} func (apduBusyError) Error() string { return "runtimehost: APDU channel busy" } - func (apduBusyError) Unwrap() error { return enginesim.ErrAPDUBusy } -// errNoService is returned when an operation requires a service that has not -// been installed on the instance. var errNoService = errors.New("runtimehost: no service installed") +var errNoIdentityProvider = errors.New("runtimehost: no identity provider") -// PhaseSIMReady is the runtime phase after the SIM is ready. const PhaseSIMReady = "sim_ready" -// Instance is the IMS runtime host. +// Instance retains the v1.5.5 field sequence before additive fields. type Instance struct { - mu sync.RWMutex - state State - service Service + mu sync.RWMutex + state State + service messaging.Service + session *runtimecore.SessionResult + startedAt time.Time + cancel func() + observers []Observer + onNotify func(string) + onSMS func(string, string, string, time.Time) + tunnel Tunnel - cancel context.CancelFunc - observers []ObserverFunc - notifier Notifier - smsNotifier SMSNotifier voiceDetach func() error stopped bool } -// NewTraceID returns a fresh trace id. -func NewTraceID() string { - return newTraceID() -} - -// The adapter types below bridge the runtime host to the modem, SIM, identity -// and delivery-store surfaces. They are implemented in adapters.go. +func NewTraceID() string { return newTraceID() } type accessAdapter struct { - access IMSIdentityProvider -} - -// Capabilities reports the identity capabilities. -func (a *accessAdapter) Capabilities() ModemCapabilities { - return ModemCapabilities{} -} - -// IMSIdentityProvider returns the underlying identity provider. -func (a *accessAdapter) IMSIdentityProvider() IMSIdentityProvider { - if a == nil { - return nil - } - return a.access + host identity.AccessAdapter } type identityProviderAdapter struct { - provider IMSIdentityProvider + provider identity.IMSIdentityProvider } -// GetISIMIdentity reads the ISIM identity. -func (a *identityProviderAdapter) GetISIMIdentity() (Identity, error) { - if a == nil || a.provider == nil { - return Identity{}, errNoIdentityProvider - } - p, ok := a.provider.(interface { - GetISIMIdentity() (identity.Identity, error) - }) - if !ok { - return Identity{}, errNoIdentityProvider - } - ident, err := p.GetISIMIdentity() - if err != nil { - return Identity{}, err - } - return Identity{IMSI: ident.IMSI, IMPI: ident.IMPI}, nil -} - -// errNoIdentityProvider is returned when no identity provider is installed. -var errNoIdentityProvider = errors.New("runtimehost: no identity provider") - type modemAccessAdapter struct { modem Modem } - -// Capabilities returns the modem capabilities. -func (a modemAccessAdapter) Capabilities() ModemCapabilities { - if a.modem == nil { - return ModemCapabilities{} - } - return a.modem.Capabilities() -} - -// IMSIdentityProvider returns the modem's IMS identity provider. -func (a modemAccessAdapter) IMSIdentityProvider() IMSIdentityProvider { - if a.modem == nil { - return nil - } - return a.modem.IMSIdentityProvider() -}