session_manager.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package state
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "sync"
  8. "time"
  9. "github.com/mk6i/open-oscar-server/wire"
  10. )
  11. type sessionSlot struct {
  12. session *Session
  13. removed chan bool
  14. multiSession bool
  15. }
  16. type userLock struct {
  17. sync.Mutex
  18. refCount int
  19. }
  20. // InMemorySessionManager handles the lifecycle of a user session and provides
  21. // synchronized message relay between sessions in the session pool. An
  22. // InMemorySessionManager is safe for concurrent use by multiple goroutines.
  23. type InMemorySessionManager struct {
  24. store map[IdentScreenName]*sessionSlot
  25. mapMutex sync.RWMutex
  26. userLocks map[IdentScreenName]*userLock
  27. userLocksMutex sync.Mutex
  28. logger *slog.Logger
  29. maxConcurrentSessions int
  30. }
  31. const (
  32. // DefaultMaxConcurrentSessions is the default maximum number of concurrent
  33. // sessions allowed when multi-session is enabled.
  34. DefaultMaxConcurrentSessions = 5
  35. )
  36. // ErrMaxConcurrentSessionsReached is returned when attempting to add a new
  37. // session instance but the maximum number of concurrent sessions has been
  38. // reached.
  39. var ErrMaxConcurrentSessionsReached = errors.New("maximum number of concurrent sessions reached")
  40. // NewInMemorySessionManager creates a new instance of InMemorySessionManager.
  41. func NewInMemorySessionManager(logger *slog.Logger) *InMemorySessionManager {
  42. return &InMemorySessionManager{
  43. logger: logger,
  44. store: make(map[IdentScreenName]*sessionSlot),
  45. userLocks: make(map[IdentScreenName]*userLock),
  46. maxConcurrentSessions: DefaultMaxConcurrentSessions,
  47. }
  48. }
  49. func (s *InMemorySessionManager) lockUser(sn IdentScreenName) {
  50. s.userLocksMutex.Lock()
  51. lock, ok := s.userLocks[sn]
  52. if !ok {
  53. lock = &userLock{}
  54. s.userLocks[sn] = lock
  55. }
  56. lock.refCount++
  57. s.userLocksMutex.Unlock()
  58. lock.Lock()
  59. }
  60. func (s *InMemorySessionManager) unlockUser(sn IdentScreenName) {
  61. s.userLocksMutex.Lock()
  62. defer s.userLocksMutex.Unlock()
  63. lock, ok := s.userLocks[sn]
  64. if !ok {
  65. return
  66. }
  67. lock.Unlock()
  68. lock.refCount--
  69. if lock.refCount == 0 {
  70. delete(s.userLocks, sn)
  71. }
  72. }
  73. // RelayToAll relays a message to all sessions in the session pool.
  74. func (s *InMemorySessionManager) RelayToAll(ctx context.Context, msg wire.SNACMessage) {
  75. s.mapMutex.RLock()
  76. defer s.mapMutex.RUnlock()
  77. for _, rec := range s.store {
  78. s.maybeRelayMessage(ctx, msg, rec.session)
  79. }
  80. }
  81. // RelayToScreenName relays a message to a session with a matching screen name.
  82. func (s *InMemorySessionManager) RelayToScreenName(ctx context.Context, screenName IdentScreenName, msg wire.SNACMessage) {
  83. sess := s.RetrieveSession(screenName)
  84. if sess == nil {
  85. s.logger.WarnContext(ctx, "RelayToScreenName: session not found",
  86. "recipient", screenName,
  87. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  88. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
  89. return
  90. }
  91. s.logger.DebugContext(ctx, "RelayToScreenName: found session, relaying", "recipient", screenName,
  92. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  93. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup),
  94. "instances", len(sess.Instances()))
  95. s.maybeRelayMessage(ctx, msg, sess)
  96. }
  97. // RelayToScreenNames relays a message to sessions with matching screenNames.
  98. func (s *InMemorySessionManager) RelayToScreenNames(ctx context.Context, screenNames []IdentScreenName, msg wire.SNACMessage) {
  99. for _, sess := range s.retrieveByScreenNames(screenNames) {
  100. s.maybeRelayMessage(ctx, msg, sess)
  101. }
  102. }
  103. func (s *InMemorySessionManager) RelayToSelf(ctx context.Context, instance *SessionInstance, msg wire.SNACMessage) {
  104. switch instance.RelayMessageToInstance(msg) {
  105. case SessSendClosed:
  106. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", instance.IdentScreenName(), "message", msg)
  107. case SessQueueFull:
  108. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", instance.IdentScreenName(), "message", msg)
  109. instance.CloseInstance()
  110. }
  111. }
  112. func (s *InMemorySessionManager) RelayToOtherInstances(ctx context.Context, instance *SessionInstance, msg wire.SNACMessage) {
  113. for _, inst := range instance.Session().Instances() {
  114. if instance == inst || !inst.live() {
  115. continue
  116. }
  117. switch inst.RelayMessageToInstance(msg) {
  118. case SessSendClosed:
  119. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", instance.IdentScreenName(), "message", msg)
  120. case SessQueueFull:
  121. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", instance.IdentScreenName(), "message", msg)
  122. inst.CloseInstance()
  123. }
  124. }
  125. }
  126. func (s *InMemorySessionManager) RelayToScreenNameActiveOnly(ctx context.Context, screenName IdentScreenName, msg wire.SNACMessage) {
  127. sess := s.RetrieveSession(screenName)
  128. if sess == nil {
  129. s.logger.WarnContext(ctx, "RelayToScreenNameActiveOnly: session not found",
  130. "recipient", screenName,
  131. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  132. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
  133. return
  134. }
  135. s.logger.DebugContext(ctx, "RelayToScreenNameActiveOnly: found session, relaying", "recipient", screenName,
  136. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  137. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup),
  138. "instances", len(sess.Instances()),
  139. "inactive", sess.Inactive())
  140. s.maybeRelayMessageActiveOnly(ctx, msg, sess)
  141. }
  142. func (s *InMemorySessionManager) maybeRelayMessage(ctx context.Context, msg wire.SNACMessage, sess *Session) {
  143. for _, instance := range sess.Instances() {
  144. if !instance.live() {
  145. s.logger.DebugContext(ctx, "maybeRelayMessage: skipping non-live instance",
  146. "recipient", sess.IdentScreenName(),
  147. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  148. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup))
  149. continue
  150. }
  151. switch instance.RelayMessageToInstance(msg) {
  152. case SessSendClosed:
  153. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.IdentScreenName(), "message", msg)
  154. case SessQueueFull:
  155. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", sess.IdentScreenName(), "message", msg)
  156. instance.CloseInstance()
  157. default:
  158. s.logger.DebugContext(ctx, "maybeRelayMessage: relayed to instance",
  159. "recipient", sess.IdentScreenName(),
  160. "food_group", wire.FoodGroupName(msg.Frame.FoodGroup),
  161. "sub_group", wire.SubGroupName(msg.Frame.FoodGroup, msg.Frame.SubGroup),
  162. )
  163. }
  164. }
  165. }
  166. func (s *InMemorySessionManager) maybeRelayMessageActiveOnly(ctx context.Context, msg wire.SNACMessage, sess *Session) {
  167. for _, instance := range sess.Instances() {
  168. if !instance.active() {
  169. continue
  170. }
  171. switch instance.RelayMessageToInstance(msg) {
  172. case SessSendClosed:
  173. s.logger.WarnContext(ctx, "can't send notification because the user's session is closed", "recipient", sess.IdentScreenName(), "message", msg)
  174. case SessQueueFull:
  175. s.logger.WarnContext(ctx, "can't send notification because queue is full", "recipient", sess.IdentScreenName(), "message", msg)
  176. instance.CloseInstance()
  177. }
  178. }
  179. }
  180. func (s *InMemorySessionManager) AddSession(ctx context.Context, screenName DisplayScreenName, doMultiSess bool, cfg ...func(sess *Session)) (*SessionInstance, error) {
  181. s.lockUser(screenName.IdentScreenName())
  182. defer s.unlockUser(screenName.IdentScreenName())
  183. s.mapMutex.Lock()
  184. active := s.findRec(screenName.IdentScreenName())
  185. s.mapMutex.Unlock()
  186. // A closed session is a tombstone awaiting RemoveSession, the last act of
  187. // onSessCloseFn. Attaching to it strands the new instance without the
  188. // per-account goroutines its spent RunOnce would have started; evicting it
  189. // early lets the teardown's UnregisterBuddyList and RemoveUserFromAllChats
  190. // land after the fresh session registered. Wait it out.
  191. if active != nil && active.session.IsClosed() {
  192. select {
  193. case <-active.removed: // wait for RemoveSession to be called
  194. case <-ctx.Done():
  195. return nil, fmt.Errorf("waiting for closed session to be torn down: %w", ctx.Err())
  196. }
  197. active = nil
  198. }
  199. if active != nil {
  200. if doMultiSess {
  201. if !active.multiSession {
  202. active.session.CloseSession()
  203. return s.newSession(screenName, doMultiSess, cfg)
  204. }
  205. // Check if we've reached the maximum number of concurrent sessions
  206. if active.session.InstanceCount() >= s.maxConcurrentSessions {
  207. return nil, fmt.Errorf("%w: max instance(s) = %d", ErrMaxConcurrentSessionsReached, s.maxConcurrentSessions)
  208. }
  209. // AddInstance refuses a session that closed after the tombstone
  210. // check above — the account's last instance departed in the
  211. // interim. Wait that teardown out and build a fresh session, as
  212. // the tombstone path does.
  213. if instance := active.session.AddInstance(); instance != nil {
  214. return instance, nil
  215. }
  216. select {
  217. case <-active.removed: // wait for RemoveSession to be called
  218. case <-ctx.Done():
  219. return nil, fmt.Errorf("waiting for closed session to be torn down: %w", ctx.Err())
  220. }
  221. } else {
  222. // signal to callers that this session group has to go
  223. active.session.CloseSession()
  224. select {
  225. case <-active.removed: // wait for RemoveSession to be called
  226. case <-ctx.Done():
  227. return nil, fmt.Errorf("waiting for previous session to terminate: %w", ctx.Err())
  228. }
  229. }
  230. }
  231. return s.newSession(screenName, doMultiSess, cfg)
  232. }
  233. func (s *InMemorySessionManager) newSession(screenName DisplayScreenName, doMultiSess bool, cfg []func(sess *Session)) (*SessionInstance, error) {
  234. sess := NewSession()
  235. sess.SetIdentScreenName(screenName.IdentScreenName())
  236. sess.SetDisplayScreenName(screenName)
  237. for _, f := range cfg {
  238. f(sess)
  239. }
  240. // Create a new instance within the session group
  241. instance := sess.AddInstance()
  242. s.mapMutex.Lock()
  243. s.store[instance.IdentScreenName()] = &sessionSlot{
  244. session: sess,
  245. removed: make(chan bool),
  246. multiSession: doMultiSess,
  247. }
  248. s.mapMutex.Unlock()
  249. return instance, nil
  250. }
  251. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  252. for _, rec := range s.store {
  253. if identScreenName == rec.session.IdentScreenName() {
  254. return rec
  255. }
  256. }
  257. return nil
  258. }
  259. // RemoveSession takes a session out of the session pool.
  260. func (s *InMemorySessionManager) RemoveSession(session *Session) {
  261. s.mapMutex.Lock()
  262. defer s.mapMutex.Unlock()
  263. if rec, ok := s.store[session.IdentScreenName()]; ok && rec.session == session {
  264. delete(s.store, session.IdentScreenName())
  265. close(rec.removed)
  266. }
  267. }
  268. // RetrieveSession finds a session with a matching screen name. Returns nil if
  269. // session is not found or if there are no active instances with complete signon.
  270. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  271. s.mapMutex.RLock()
  272. defer s.mapMutex.RUnlock()
  273. if rec, ok := s.store[screenName]; ok {
  274. if rec.session.HasLiveInstances() {
  275. return rec.session
  276. }
  277. }
  278. return nil
  279. }
  280. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  281. s.mapMutex.RLock()
  282. defer s.mapMutex.RUnlock()
  283. var ret []*Session
  284. for _, sn := range screenNames {
  285. for _, rec := range s.store {
  286. if sn == rec.session.IdentScreenName() {
  287. ret = append(ret, rec.session)
  288. break
  289. }
  290. }
  291. }
  292. return ret
  293. }
  294. // Empty returns true if the session pool contains 0 sessions.
  295. func (s *InMemorySessionManager) Empty() bool {
  296. s.mapMutex.RLock()
  297. defer s.mapMutex.RUnlock()
  298. return len(s.store) == 0
  299. }
  300. // AllSessions returns all sessions in the session pool.
  301. func (s *InMemorySessionManager) AllSessions() []*Session {
  302. s.mapMutex.RLock()
  303. defer s.mapMutex.RUnlock()
  304. var sessions []*Session
  305. for _, rec := range s.store {
  306. if !rec.session.HasLiveInstances() {
  307. continue
  308. }
  309. sessions = append(sessions, rec.session)
  310. }
  311. return sessions
  312. }
  313. // NewInMemoryChatSessionManager creates a new instance of
  314. // InMemoryChatSessionManager.
  315. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  316. return &InMemoryChatSessionManager{
  317. store: make(map[string]*InMemorySessionManager),
  318. logger: logger,
  319. }
  320. }
  321. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  322. // stored in memory. It provides thread-safe operations to add, remove, and
  323. // manipulate sessions as well as relay messages to participants.
  324. type InMemoryChatSessionManager struct {
  325. logger *slog.Logger
  326. mapMutex sync.RWMutex
  327. store map[string]*InMemorySessionManager
  328. }
  329. // AddSession adds a user to a chat room. If screenName already exists, the old
  330. // session is replaced by a new one. Optional cfg callbacks let callers attach
  331. // setup (for example shutdown behavior) while the session is still being
  332. // created.
  333. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName, cfg ...func(sess *Session)) (*SessionInstance, error) {
  334. s.mapMutex.Lock()
  335. if _, ok := s.store[chatCookie]; !ok {
  336. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  337. }
  338. sessionManager := s.store[chatCookie]
  339. s.mapMutex.Unlock()
  340. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  341. defer cancel()
  342. sess, err := sessionManager.AddSession(ctx, screenName, false, cfg...)
  343. if err != nil {
  344. return nil, fmt.Errorf("AddSession: %w", err)
  345. }
  346. sess.Session().SetChatRoomCookie(chatCookie)
  347. s.mapMutex.Lock()
  348. defer s.mapMutex.Unlock()
  349. // at this point it's guaranteed that the prior chat session and corresponding
  350. // session manager (if the room count dropped to 0) were removed.
  351. //
  352. // - SessionManager.RemoveSession() was called because that unlocks
  353. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  354. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  355. // releasing mapMutex
  356. //
  357. // now restore the chat session manager, which may have been deleted by the
  358. // call to RemoveSession().
  359. if _, ok := s.store[chatCookie]; !ok {
  360. s.store[chatCookie] = sessionManager
  361. }
  362. return sess, nil
  363. }
  364. // RemoveSession removes a user session from a chat room. It panics if you
  365. // attempt to remove the session twice.
  366. func (s *InMemoryChatSessionManager) RemoveSession(sess *Session) {
  367. s.mapMutex.Lock()
  368. defer s.mapMutex.Unlock()
  369. sessionManager, ok := s.store[sess.ChatRoomCookie()]
  370. if !ok {
  371. panic("attempting to remove a session after its room has been deleted")
  372. }
  373. sessionManager.RemoveSession(sess)
  374. if sessionManager.Empty() {
  375. delete(s.store, sess.ChatRoomCookie())
  376. }
  377. }
  378. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  379. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  380. var cpy []*InMemorySessionManager
  381. // make a copy since CloseSession() may call back to InMemoryChatSessionManager
  382. // and deadlock with this call
  383. s.mapMutex.RLock()
  384. for _, sessionManager := range s.store {
  385. cpy = append(cpy, sessionManager)
  386. }
  387. s.mapMutex.RUnlock()
  388. for _, sessionManager := range cpy {
  389. userSess := sessionManager.RetrieveSession(user)
  390. if userSess != nil {
  391. userSess.CloseSession()
  392. }
  393. }
  394. }
  395. // AllSessions returns all chat room participants. Returns
  396. // ErrChatRoomNotFound if the room does not exist.
  397. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  398. s.mapMutex.RLock()
  399. defer s.mapMutex.RUnlock()
  400. sessionManager, ok := s.store[cookie]
  401. if !ok {
  402. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  403. return nil
  404. }
  405. return sessionManager.AllSessions()
  406. }
  407. // RelayToAllExcept sends a message to all chat room participants except for
  408. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  409. // if the room does not exist for cookie.
  410. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  411. s.mapMutex.RLock()
  412. defer s.mapMutex.RUnlock()
  413. sessionManager, ok := s.store[cookie]
  414. if !ok {
  415. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  416. return
  417. }
  418. for _, sess := range sessionManager.AllSessions() {
  419. if sess.IdentScreenName() == except {
  420. continue
  421. }
  422. sessionManager.maybeRelayMessage(ctx, msg, sess)
  423. }
  424. }
  425. // RelayToScreenName sends a message to a chat room user. Returns
  426. // ErrChatRoomNotFound if the room does not exist for cookie.
  427. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  428. s.mapMutex.RLock()
  429. defer s.mapMutex.RUnlock()
  430. sessionManager, ok := s.store[cookie]
  431. if !ok {
  432. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  433. return
  434. }
  435. sessionManager.RelayToScreenName(ctx, recipient, msg)
  436. }