session_manager.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. if active != nil {
  187. if doMultiSess {
  188. if !active.multiSession {
  189. active.session.CloseSession()
  190. return s.newSession(screenName, doMultiSess, cfg)
  191. }
  192. // Check if we've reached the maximum number of concurrent sessions
  193. if active.session.InstanceCount() >= s.maxConcurrentSessions {
  194. return nil, fmt.Errorf("%w: max instance(s) = %d", ErrMaxConcurrentSessionsReached, s.maxConcurrentSessions)
  195. }
  196. instance := active.session.AddInstance()
  197. return instance, nil
  198. } else {
  199. // signal to callers that this session group has to go
  200. active.session.CloseSession()
  201. select {
  202. case <-active.removed: // wait for RemoveSession to be called
  203. case <-ctx.Done():
  204. return nil, fmt.Errorf("waiting for previous session to terminate: %w", ctx.Err())
  205. }
  206. }
  207. }
  208. return s.newSession(screenName, doMultiSess, cfg)
  209. }
  210. func (s *InMemorySessionManager) newSession(screenName DisplayScreenName, doMultiSess bool, cfg []func(sess *Session)) (*SessionInstance, error) {
  211. sess := NewSession()
  212. sess.SetIdentScreenName(screenName.IdentScreenName())
  213. sess.SetDisplayScreenName(screenName)
  214. for _, f := range cfg {
  215. f(sess)
  216. }
  217. // Create a new instance within the session group
  218. instance := sess.AddInstance()
  219. s.mapMutex.Lock()
  220. s.store[instance.IdentScreenName()] = &sessionSlot{
  221. session: sess,
  222. removed: make(chan bool),
  223. multiSession: doMultiSess,
  224. }
  225. s.mapMutex.Unlock()
  226. return instance, nil
  227. }
  228. func (s *InMemorySessionManager) findRec(identScreenName IdentScreenName) *sessionSlot {
  229. for _, rec := range s.store {
  230. if identScreenName == rec.session.IdentScreenName() {
  231. return rec
  232. }
  233. }
  234. return nil
  235. }
  236. // RemoveSession takes a session out of the session pool.
  237. func (s *InMemorySessionManager) RemoveSession(session *Session) {
  238. s.mapMutex.Lock()
  239. defer s.mapMutex.Unlock()
  240. if rec, ok := s.store[session.IdentScreenName()]; ok && rec.session == session {
  241. delete(s.store, session.IdentScreenName())
  242. close(rec.removed)
  243. }
  244. }
  245. // RetrieveSession finds a session with a matching screen name. Returns nil if
  246. // session is not found or if there are no active instances with complete signon.
  247. func (s *InMemorySessionManager) RetrieveSession(screenName IdentScreenName) *Session {
  248. s.mapMutex.RLock()
  249. defer s.mapMutex.RUnlock()
  250. if rec, ok := s.store[screenName]; ok {
  251. if rec.session.HasLiveInstances() {
  252. return rec.session
  253. }
  254. }
  255. return nil
  256. }
  257. func (s *InMemorySessionManager) retrieveByScreenNames(screenNames []IdentScreenName) []*Session {
  258. s.mapMutex.RLock()
  259. defer s.mapMutex.RUnlock()
  260. var ret []*Session
  261. for _, sn := range screenNames {
  262. for _, rec := range s.store {
  263. if sn == rec.session.IdentScreenName() {
  264. ret = append(ret, rec.session)
  265. break
  266. }
  267. }
  268. }
  269. return ret
  270. }
  271. // Empty returns true if the session pool contains 0 sessions.
  272. func (s *InMemorySessionManager) Empty() bool {
  273. s.mapMutex.RLock()
  274. defer s.mapMutex.RUnlock()
  275. return len(s.store) == 0
  276. }
  277. // AllSessions returns all sessions in the session pool.
  278. func (s *InMemorySessionManager) AllSessions() []*Session {
  279. s.mapMutex.RLock()
  280. defer s.mapMutex.RUnlock()
  281. var sessions []*Session
  282. for _, rec := range s.store {
  283. if !rec.session.HasLiveInstances() {
  284. continue
  285. }
  286. sessions = append(sessions, rec.session)
  287. }
  288. return sessions
  289. }
  290. // NewInMemoryChatSessionManager creates a new instance of
  291. // InMemoryChatSessionManager.
  292. func NewInMemoryChatSessionManager(logger *slog.Logger) *InMemoryChatSessionManager {
  293. return &InMemoryChatSessionManager{
  294. store: make(map[string]*InMemorySessionManager),
  295. logger: logger,
  296. }
  297. }
  298. // InMemoryChatSessionManager manages chat sessions for multiple chat rooms
  299. // stored in memory. It provides thread-safe operations to add, remove, and
  300. // manipulate sessions as well as relay messages to participants.
  301. type InMemoryChatSessionManager struct {
  302. logger *slog.Logger
  303. mapMutex sync.RWMutex
  304. store map[string]*InMemorySessionManager
  305. }
  306. // AddSession adds a user to a chat room. If screenName already exists, the old
  307. // session is replaced by a new one. Optional cfg callbacks let callers attach
  308. // setup (for example shutdown behavior) while the session is still being
  309. // created.
  310. func (s *InMemoryChatSessionManager) AddSession(ctx context.Context, chatCookie string, screenName DisplayScreenName, cfg ...func(sess *Session)) (*SessionInstance, error) {
  311. s.mapMutex.Lock()
  312. if _, ok := s.store[chatCookie]; !ok {
  313. s.store[chatCookie] = NewInMemorySessionManager(s.logger)
  314. }
  315. sessionManager := s.store[chatCookie]
  316. s.mapMutex.Unlock()
  317. ctx, cancel := context.WithTimeout(ctx, time.Second*5)
  318. defer cancel()
  319. sess, err := sessionManager.AddSession(ctx, screenName, false, cfg...)
  320. if err != nil {
  321. return nil, fmt.Errorf("AddSession: %w", err)
  322. }
  323. sess.Session().SetChatRoomCookie(chatCookie)
  324. s.mapMutex.Lock()
  325. defer s.mapMutex.Unlock()
  326. // at this point it's guaranteed that the prior chat session and corresponding
  327. // session manager (if the room count dropped to 0) were removed.
  328. //
  329. // - SessionManager.RemoveSession() was called because that unlocks
  330. // SessionManager.AddSession(), which unblocks ChatSessionManager.AddSession()
  331. // - ChatSessionManager.RemoveSession() must call room deletion routine before
  332. // releasing mapMutex
  333. //
  334. // now restore the chat session manager, which may have been deleted by the
  335. // call to RemoveSession().
  336. if _, ok := s.store[chatCookie]; !ok {
  337. s.store[chatCookie] = sessionManager
  338. }
  339. return sess, nil
  340. }
  341. // RemoveSession removes a user session from a chat room. It panics if you
  342. // attempt to remove the session twice.
  343. func (s *InMemoryChatSessionManager) RemoveSession(sess *Session) {
  344. s.mapMutex.Lock()
  345. defer s.mapMutex.Unlock()
  346. sessionManager, ok := s.store[sess.ChatRoomCookie()]
  347. if !ok {
  348. panic("attempting to remove a session after its room has been deleted")
  349. }
  350. sessionManager.RemoveSession(sess)
  351. if sessionManager.Empty() {
  352. delete(s.store, sess.ChatRoomCookie())
  353. }
  354. }
  355. // RemoveUserFromAllChats removes a user's session from all chat rooms.
  356. func (s *InMemoryChatSessionManager) RemoveUserFromAllChats(user IdentScreenName) {
  357. var cpy []*InMemorySessionManager
  358. // make a copy since CloseSession() may call back to InMemoryChatSessionManager
  359. // and deadlock with this call
  360. s.mapMutex.RLock()
  361. for _, sessionManager := range s.store {
  362. cpy = append(cpy, sessionManager)
  363. }
  364. s.mapMutex.RUnlock()
  365. for _, sessionManager := range cpy {
  366. userSess := sessionManager.RetrieveSession(user)
  367. if userSess != nil {
  368. userSess.CloseSession()
  369. }
  370. }
  371. }
  372. // AllSessions returns all chat room participants. Returns
  373. // ErrChatRoomNotFound if the room does not exist.
  374. func (s *InMemoryChatSessionManager) AllSessions(cookie string) []*Session {
  375. s.mapMutex.RLock()
  376. defer s.mapMutex.RUnlock()
  377. sessionManager, ok := s.store[cookie]
  378. if !ok {
  379. s.logger.Debug("trying to get sessions for non-existent room", "cookie", cookie)
  380. return nil
  381. }
  382. return sessionManager.AllSessions()
  383. }
  384. // RelayToAllExcept sends a message to all chat room participants except for
  385. // the participant with a particular screen name. Returns ErrChatRoomNotFound
  386. // if the room does not exist for cookie.
  387. func (s *InMemoryChatSessionManager) RelayToAllExcept(ctx context.Context, cookie string, except IdentScreenName, msg wire.SNACMessage) {
  388. s.mapMutex.RLock()
  389. defer s.mapMutex.RUnlock()
  390. sessionManager, ok := s.store[cookie]
  391. if !ok {
  392. s.logger.Error("trying to relay message to all for non-existent room", "cookie", cookie)
  393. return
  394. }
  395. for _, sess := range sessionManager.AllSessions() {
  396. if sess.IdentScreenName() == except {
  397. continue
  398. }
  399. sessionManager.maybeRelayMessage(ctx, msg, sess)
  400. }
  401. }
  402. // RelayToScreenName sends a message to a chat room user. Returns
  403. // ErrChatRoomNotFound if the room does not exist for cookie.
  404. func (s *InMemoryChatSessionManager) RelayToScreenName(ctx context.Context, cookie string, recipient IdentScreenName, msg wire.SNACMessage) {
  405. s.mapMutex.RLock()
  406. defer s.mapMutex.RUnlock()
  407. sessionManager, ok := s.store[cookie]
  408. if !ok {
  409. s.logger.Error("trying to relay message to screen name for non-existent room", "cookie", cookie)
  410. return
  411. }
  412. sessionManager.RelayToScreenName(ctx, recipient, msg)
  413. }