manager.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // Package runtime owns the long-lived VoWiFi orchestrators used by the
  2. // service. It keeps HTTP requests short while preserving every evidence-backed
  3. // state transition through the supplied state callback.
  4. package runtime
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "log/slog"
  10. "sync"
  11. "time"
  12. "vocat/internal/vowifi"
  13. )
  14. var (
  15. ErrNotRegistered = errors.New("vowifi runtime: device is not registered")
  16. ErrOperationInProgress = errors.New("vowifi runtime: an operation is already in progress")
  17. ErrClosed = errors.New("vowifi runtime: manager is closed")
  18. )
  19. const (
  20. defaultOperationTimeout = 2 * time.Minute
  21. defaultRetryInitial = 2 * time.Second
  22. defaultRetryMaximum = 30 * time.Second
  23. )
  24. type StateHandler func(context.Context, vowifi.State) error
  25. type OrchestratorFactory func(context.Context, string) (*vowifi.Orchestrator, error)
  26. type Options struct {
  27. Logger *slog.Logger
  28. OperationTimeout time.Duration
  29. RetryInitial time.Duration
  30. RetryMaximum time.Duration
  31. OnState StateHandler
  32. Factory OrchestratorFactory
  33. }
  34. type Manager struct {
  35. ctx context.Context
  36. cancel context.CancelFunc
  37. logger *slog.Logger
  38. operationTimeout time.Duration
  39. retryInitial time.Duration
  40. retryMaximum time.Duration
  41. onState StateHandler
  42. factory OrchestratorFactory
  43. mu sync.Mutex
  44. closed bool
  45. entries map[string]*entry
  46. wg sync.WaitGroup
  47. }
  48. type entry struct {
  49. orchestrator *vowifi.Orchestrator
  50. busy bool
  51. reconnectPending bool
  52. disablePending bool
  53. desiredEnabled bool
  54. autoRetryPending bool
  55. retryFailures uint
  56. operationCancel context.CancelFunc
  57. stopWatch func()
  58. }
  59. func New(options Options) *Manager {
  60. if options.Logger == nil {
  61. options.Logger = slog.Default()
  62. }
  63. if options.OperationTimeout <= 0 {
  64. options.OperationTimeout = defaultOperationTimeout
  65. }
  66. if options.RetryInitial <= 0 {
  67. options.RetryInitial = defaultRetryInitial
  68. }
  69. if options.RetryMaximum <= 0 {
  70. options.RetryMaximum = defaultRetryMaximum
  71. }
  72. if options.RetryMaximum < options.RetryInitial {
  73. options.RetryMaximum = options.RetryInitial
  74. }
  75. ctx, cancel := context.WithCancel(context.Background())
  76. return &Manager{
  77. ctx: ctx,
  78. cancel: cancel,
  79. logger: options.Logger,
  80. operationTimeout: options.OperationTimeout,
  81. retryInitial: options.RetryInitial,
  82. retryMaximum: options.RetryMaximum,
  83. onState: options.OnState,
  84. factory: options.Factory,
  85. entries: make(map[string]*entry),
  86. }
  87. }
  88. // Ensure registers a runtime for deviceID on demand. This keeps device
  89. // configuration and runtime lifecycle in sync when a modem is added after the
  90. // service has already started.
  91. func (manager *Manager) Ensure(ctx context.Context, deviceID string) error {
  92. if ctx == nil {
  93. ctx = context.Background()
  94. }
  95. manager.mu.Lock()
  96. if manager.closed {
  97. manager.mu.Unlock()
  98. return ErrClosed
  99. }
  100. if _, exists := manager.entries[deviceID]; exists {
  101. manager.mu.Unlock()
  102. return nil
  103. }
  104. if manager.factory == nil {
  105. manager.mu.Unlock()
  106. return ErrNotRegistered
  107. }
  108. // The factory is called while holding the manager lock so concurrent status
  109. // and enable requests cannot create duplicate runtimes for the same device.
  110. orchestrator, err := manager.factory(ctx, deviceID)
  111. if err != nil {
  112. manager.mu.Unlock()
  113. return err
  114. }
  115. if orchestrator == nil {
  116. manager.mu.Unlock()
  117. return errors.New("vowifi runtime: factory returned a nil orchestrator")
  118. }
  119. state := orchestrator.State()
  120. if state.DeviceID != deviceID {
  121. manager.mu.Unlock()
  122. _ = orchestrator.Close(context.Background())
  123. return fmt.Errorf(
  124. "vowifi runtime: factory returned device %q for %q",
  125. state.DeviceID,
  126. deviceID,
  127. )
  128. }
  129. states, stopWatch := orchestrator.Subscribe(8)
  130. manager.entries[deviceID] = &entry{
  131. orchestrator: orchestrator,
  132. stopWatch: stopWatch,
  133. }
  134. manager.wg.Add(1)
  135. manager.mu.Unlock()
  136. go manager.watch(deviceID, states)
  137. return nil
  138. }
  139. func (manager *Manager) Register(orchestrator *vowifi.Orchestrator) error {
  140. if orchestrator == nil {
  141. return errors.New("vowifi runtime: orchestrator is nil")
  142. }
  143. state := orchestrator.State()
  144. if state.DeviceID == "" {
  145. return errors.New("vowifi runtime: orchestrator device ID is empty")
  146. }
  147. manager.mu.Lock()
  148. if manager.closed {
  149. manager.mu.Unlock()
  150. return ErrClosed
  151. }
  152. if _, exists := manager.entries[state.DeviceID]; exists {
  153. manager.mu.Unlock()
  154. return fmt.Errorf("vowifi runtime: device %q is already registered", state.DeviceID)
  155. }
  156. states, stopWatch := orchestrator.Subscribe(8)
  157. item := &entry{
  158. orchestrator: orchestrator,
  159. stopWatch: stopWatch,
  160. }
  161. manager.entries[state.DeviceID] = item
  162. manager.wg.Add(1)
  163. manager.mu.Unlock()
  164. go manager.watch(state.DeviceID, states)
  165. return nil
  166. }
  167. func (manager *Manager) State(deviceID string) (vowifi.State, error) {
  168. manager.mu.Lock()
  169. item := manager.entries[deviceID]
  170. closed := manager.closed
  171. manager.mu.Unlock()
  172. if item == nil {
  173. if closed {
  174. return vowifi.State{}, ErrClosed
  175. }
  176. if err := manager.Ensure(manager.ctx, deviceID); err != nil {
  177. return vowifi.State{}, err
  178. }
  179. manager.mu.Lock()
  180. item = manager.entries[deviceID]
  181. manager.mu.Unlock()
  182. }
  183. return item.orchestrator.State(), nil
  184. }
  185. // RequestEnabled queues an enable or disable transaction and returns
  186. // immediately. Callers observe progress through State; provider errors are
  187. // persisted in the orchestrator state instead of being lost with an HTTP
  188. // request context.
  189. func (manager *Manager) RequestEnabled(deviceID string, enabled bool) (vowifi.State, error) {
  190. if err := manager.Ensure(manager.ctx, deviceID); err != nil {
  191. return vowifi.State{}, err
  192. }
  193. manager.mu.Lock()
  194. item := manager.entries[deviceID]
  195. item.desiredEnabled = enabled
  196. if !enabled && item.busy {
  197. item.disablePending = true
  198. cancel := item.operationCancel
  199. state := item.orchestrator.State()
  200. manager.mu.Unlock()
  201. if cancel != nil {
  202. cancel()
  203. }
  204. return state, nil
  205. }
  206. manager.mu.Unlock()
  207. return manager.startOperation(deviceID, false, func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  208. if enabled {
  209. _, err := orchestrator.Enable(ctx)
  210. return err
  211. }
  212. _, err := orchestrator.Disable(ctx)
  213. return err
  214. })
  215. }
  216. func (manager *Manager) RequestReconnect(deviceID string) (vowifi.State, error) {
  217. if err := manager.Ensure(manager.ctx, deviceID); err != nil {
  218. return vowifi.State{}, err
  219. }
  220. manager.mu.Lock()
  221. if item := manager.entries[deviceID]; item != nil {
  222. item.desiredEnabled = true
  223. }
  224. manager.mu.Unlock()
  225. return manager.startOperation(deviceID, true, func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  226. _, err := orchestrator.Reconnect(ctx)
  227. return err
  228. })
  229. }
  230. func (manager *Manager) SendSMS(
  231. ctx context.Context,
  232. deviceID string,
  233. request vowifi.SMSSubmitRequest,
  234. ) (vowifi.SMSSubmitResult, error) {
  235. if err := manager.Ensure(ctx, deviceID); err != nil {
  236. return vowifi.SMSSubmitResult{}, err
  237. }
  238. manager.mu.Lock()
  239. if manager.closed {
  240. manager.mu.Unlock()
  241. return vowifi.SMSSubmitResult{}, ErrClosed
  242. }
  243. item := manager.entries[deviceID]
  244. manager.mu.Unlock()
  245. if item == nil {
  246. return vowifi.SMSSubmitResult{}, ErrNotRegistered
  247. }
  248. return item.orchestrator.SendSMS(ctx, request)
  249. }
  250. func (manager *Manager) startOperation(
  251. deviceID string,
  252. coalesceReconnect bool,
  253. operation func(context.Context, *vowifi.Orchestrator) error,
  254. ) (vowifi.State, error) {
  255. manager.mu.Lock()
  256. if manager.closed {
  257. manager.mu.Unlock()
  258. return vowifi.State{}, ErrClosed
  259. }
  260. item := manager.entries[deviceID]
  261. if item == nil {
  262. manager.mu.Unlock()
  263. return vowifi.State{}, ErrNotRegistered
  264. }
  265. if item.busy {
  266. state := item.orchestrator.State()
  267. if coalesceReconnect {
  268. // Route changes and repeated reconnect clicks only need the latest
  269. // result. Keep one pending reconnect behind the active lifecycle
  270. // operation instead of rejecting the request or running two modem/
  271. // tunnel transactions concurrently.
  272. item.reconnectPending = true
  273. manager.mu.Unlock()
  274. return state, nil
  275. }
  276. manager.mu.Unlock()
  277. return state, ErrOperationInProgress
  278. }
  279. item.busy = true
  280. manager.wg.Add(1)
  281. manager.mu.Unlock()
  282. go manager.runOperations(deviceID, item, operation)
  283. return item.orchestrator.State(), nil
  284. }
  285. func (manager *Manager) runOperations(
  286. deviceID string,
  287. item *entry,
  288. operation func(context.Context, *vowifi.Orchestrator) error,
  289. ) {
  290. defer manager.wg.Done()
  291. for {
  292. ctx, cancel := context.WithTimeout(manager.ctx, manager.operationTimeout)
  293. manager.mu.Lock()
  294. if item.disablePending {
  295. item.disablePending = false
  296. item.reconnectPending = false
  297. operation = func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  298. _, err := orchestrator.Disable(ctx)
  299. return err
  300. }
  301. }
  302. item.operationCancel = cancel
  303. manager.mu.Unlock()
  304. err := operation(ctx, item.orchestrator)
  305. cancel()
  306. if err != nil &&
  307. !errors.Is(err, context.Canceled) &&
  308. !errors.Is(err, vowifi.ErrAlreadyEnabled) {
  309. manager.logger.Warn(
  310. "VoWiFi operation failed",
  311. "device_id", deviceID,
  312. "error", err,
  313. )
  314. }
  315. state := item.orchestrator.State()
  316. manager.mu.Lock()
  317. item.operationCancel = nil
  318. if manager.closed {
  319. item.busy = false
  320. manager.mu.Unlock()
  321. return
  322. }
  323. if item.disablePending {
  324. item.disablePending = false
  325. item.reconnectPending = false
  326. manager.mu.Unlock()
  327. operation = func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  328. _, err := orchestrator.Disable(ctx)
  329. return err
  330. }
  331. continue
  332. }
  333. if item.reconnectPending {
  334. item.reconnectPending = false
  335. manager.mu.Unlock()
  336. // Read the route only when this runs. If the user bound, unbound,
  337. // then rebound while busy, this reconnect uses the final persisted
  338. // binding instead of replaying stale intermediate routes.
  339. operation = func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  340. _, err := orchestrator.Reconnect(ctx)
  341. return err
  342. }
  343. continue
  344. }
  345. item.busy = false
  346. shouldRetry := item.desiredEnabled && state.Phase == vowifi.PhaseFailed
  347. if !shouldRetry && state.Phase != vowifi.PhaseFailed {
  348. item.retryFailures = 0
  349. }
  350. manager.mu.Unlock()
  351. if shouldRetry {
  352. manager.scheduleAutoRetry(deviceID, item)
  353. }
  354. return
  355. }
  356. }
  357. func (manager *Manager) scheduleAutoRetry(deviceID string, item *entry) {
  358. manager.mu.Lock()
  359. if manager.closed || item.busy || item.autoRetryPending || !item.desiredEnabled {
  360. manager.mu.Unlock()
  361. return
  362. }
  363. delay := manager.retryInitial
  364. for attempt := uint(0); attempt < item.retryFailures && delay < manager.retryMaximum; attempt++ {
  365. if delay > manager.retryMaximum/2 {
  366. delay = manager.retryMaximum
  367. break
  368. }
  369. delay *= 2
  370. }
  371. if delay > manager.retryMaximum {
  372. delay = manager.retryMaximum
  373. }
  374. item.retryFailures++
  375. item.autoRetryPending = true
  376. manager.wg.Add(1)
  377. manager.mu.Unlock()
  378. manager.logger.Info(
  379. "VoWiFi automatic retry scheduled",
  380. "device_id", deviceID,
  381. "retry_in", delay,
  382. )
  383. go func() {
  384. defer manager.wg.Done()
  385. timer := time.NewTimer(delay)
  386. defer timer.Stop()
  387. select {
  388. case <-manager.ctx.Done():
  389. return
  390. case <-timer.C:
  391. }
  392. manager.mu.Lock()
  393. item.autoRetryPending = false
  394. if manager.closed || manager.entries[deviceID] != item || !item.desiredEnabled {
  395. manager.mu.Unlock()
  396. return
  397. }
  398. state := item.orchestrator.State()
  399. if state.Phase != vowifi.PhaseFailed {
  400. if state.Phase != vowifi.PhaseStopping {
  401. item.retryFailures = 0
  402. }
  403. manager.mu.Unlock()
  404. return
  405. }
  406. if item.busy {
  407. manager.mu.Unlock()
  408. return
  409. }
  410. item.busy = true
  411. manager.wg.Add(1)
  412. manager.mu.Unlock()
  413. go manager.runOperations(deviceID, item, func(ctx context.Context, orchestrator *vowifi.Orchestrator) error {
  414. _, err := orchestrator.Retry(ctx)
  415. return err
  416. })
  417. }()
  418. }
  419. func (manager *Manager) watch(deviceID string, states <-chan vowifi.State) {
  420. defer manager.wg.Done()
  421. for {
  422. select {
  423. case <-manager.ctx.Done():
  424. return
  425. case state, ok := <-states:
  426. if !ok {
  427. return
  428. }
  429. if state.Phase == vowifi.PhaseFailed {
  430. manager.mu.Lock()
  431. item := manager.entries[deviceID]
  432. manager.mu.Unlock()
  433. if item != nil {
  434. manager.scheduleAutoRetry(deviceID, item)
  435. }
  436. } else if state.Phase == vowifi.PhaseSMSReady || !state.Enabled {
  437. manager.mu.Lock()
  438. if item := manager.entries[deviceID]; item != nil {
  439. item.retryFailures = 0
  440. }
  441. manager.mu.Unlock()
  442. }
  443. if manager.onState == nil {
  444. continue
  445. }
  446. ctx, cancel := context.WithTimeout(manager.ctx, 5*time.Second)
  447. err := manager.onState(ctx, state)
  448. cancel()
  449. if err != nil && !errors.Is(err, context.Canceled) {
  450. manager.logger.Error(
  451. "persist VoWiFi state",
  452. "device_id", deviceID,
  453. "phase", state.Phase,
  454. "error", err,
  455. )
  456. }
  457. }
  458. }
  459. }
  460. func (manager *Manager) Close(ctx context.Context) error {
  461. if ctx == nil {
  462. ctx = context.Background()
  463. }
  464. manager.mu.Lock()
  465. if manager.closed {
  466. manager.mu.Unlock()
  467. return nil
  468. }
  469. manager.closed = true
  470. manager.cancel()
  471. items := make([]*entry, 0, len(manager.entries))
  472. for _, item := range manager.entries {
  473. items = append(items, item)
  474. }
  475. manager.mu.Unlock()
  476. var closeErrors []error
  477. for _, item := range items {
  478. if item.stopWatch != nil {
  479. item.stopWatch()
  480. }
  481. if err := item.orchestrator.Close(ctx); err != nil {
  482. closeErrors = append(closeErrors, err)
  483. }
  484. }
  485. done := make(chan struct{})
  486. go func() {
  487. manager.wg.Wait()
  488. close(done)
  489. }()
  490. select {
  491. case <-ctx.Done():
  492. closeErrors = append(closeErrors, ctx.Err())
  493. case <-done:
  494. }
  495. return errors.Join(closeErrors...)
  496. }