events.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package types
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. )
  9. // EventType defines the type of WebAPI event.
  10. type EventType string
  11. const (
  12. // Event types that can be subscribed to
  13. EventTypeBuddyList EventType = "buddylist"
  14. EventTypePresence EventType = "presence"
  15. EventTypeIM EventType = "im"
  16. EventTypeSentIM EventType = "sentIM"
  17. EventTypeTyping EventType = "typing"
  18. EventTypeStatus EventType = "status"
  19. EventTypeOfflineIM EventType = "offlineIM"
  20. EventTypeSessionEnded EventType = "sessionEnded"
  21. EventTypeRateLimit EventType = "rateLimit"
  22. EventTypePreference EventType = "preference"
  23. )
  24. // Event represents an event to be delivered to a web client.
  25. type Event struct {
  26. Type EventType `json:"type"`
  27. SeqNum uint64 `json:"seqNum"`
  28. Timestamp int64 `json:"timestamp"`
  29. Data interface{} `json:"eventData"`
  30. }
  31. // PresenceEvent represents a presence change event.
  32. type PresenceEvent struct {
  33. AimID string `json:"aimId"`
  34. State string `json:"state"` // "online", "offline", "away", "idle"
  35. StatusMsg string `json:"statusMsg,omitempty"`
  36. AwayMsg string `json:"awayMsg,omitempty"`
  37. IdleTime int `json:"idleTime,omitempty"` // Minutes idle
  38. OnlineTime int64 `json:"onlineTime,omitempty"` // Unix timestamp
  39. UserType string `json:"userType"` // "aim", "icq", "admin"
  40. }
  41. // IMEvent represents an instant message event.
  42. type IMEvent struct {
  43. Source UserInfo `json:"source"`
  44. Message string `json:"message"`
  45. MsgID string `json:"msgId,omitempty"`
  46. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  47. AutoResp bool `json:"autoresponse,omitempty"`
  48. }
  49. // SentIMEvent represents a sent instant message event.
  50. type SentIMEvent struct {
  51. Sender UserInfo `json:"sender"` // Sender user info
  52. Dest UserInfo `json:"dest"` // Destination user info
  53. Message string `json:"message"`
  54. MsgID string `json:"msgId,omitempty"`
  55. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  56. AutoResp bool `json:"autoResponse,omitempty"`
  57. }
  58. // UserInfo represents basic user information in events.
  59. type UserInfo struct {
  60. AimID string `json:"aimId"`
  61. DisplayID string `json:"displayId,omitempty"`
  62. UserType string `json:"userType,omitempty"`
  63. State string `json:"state,omitempty"`
  64. OnlineTime float64 `json:"onlineTime,omitempty"` // float64 for AMF3 encoding
  65. }
  66. // TypingEvent represents a typing notification event.
  67. type TypingEvent struct {
  68. From string `json:"from"`
  69. Typing bool `json:"typing"`
  70. }
  71. // BuddyListEvent represents a buddy list change event.
  72. type BuddyListEvent struct {
  73. Action string `json:"action"` // "add", "remove", "update"
  74. Buddy interface{} `json:"buddy"`
  75. Group string `json:"group,omitempty"`
  76. }
  77. // EventQueue manages a queue of events for a WebAPI session.
  78. type EventQueue struct {
  79. events []Event
  80. seqNum uint64
  81. maxSize int
  82. mu sync.RWMutex
  83. waitChan chan struct{}
  84. closed bool
  85. closedMu sync.RWMutex
  86. }
  87. // NewEventQueue creates a new event queue with the specified maximum size.
  88. func NewEventQueue(maxSize int) *EventQueue {
  89. return &EventQueue{
  90. events: make([]Event, 0),
  91. maxSize: maxSize,
  92. waitChan: make(chan struct{}, 1),
  93. }
  94. }
  95. // Push adds an event to the queue.
  96. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  97. q.closedMu.RLock()
  98. if q.closed {
  99. q.closedMu.RUnlock()
  100. return
  101. }
  102. q.closedMu.RUnlock()
  103. q.mu.Lock()
  104. defer q.mu.Unlock()
  105. // Increment sequence number atomically
  106. seqNum := atomic.AddUint64(&q.seqNum, 1)
  107. event := Event{
  108. Type: eventType,
  109. SeqNum: seqNum,
  110. Timestamp: time.Now().Unix(),
  111. Data: data,
  112. }
  113. // Add event to queue
  114. q.events = append(q.events, event)
  115. // If queue exceeds max size, remove oldest events
  116. if len(q.events) > q.maxSize {
  117. // Keep only the most recent maxSize events
  118. q.events = q.events[len(q.events)-q.maxSize:]
  119. }
  120. // Signal any waiting fetchers
  121. select {
  122. case q.waitChan <- struct{}{}:
  123. default:
  124. // Channel already has a signal
  125. }
  126. }
  127. // Fetch retrieves events from the queue, optionally waiting for new events.
  128. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  129. q.closedMu.RLock()
  130. if q.closed {
  131. q.closedMu.RUnlock()
  132. return nil, errors.New("event queue is closed")
  133. }
  134. q.closedMu.RUnlock()
  135. // First, check if we have any events newer than lastSeqNum
  136. q.mu.RLock()
  137. events := q.getEventsAfter(lastSeqNum)
  138. q.mu.RUnlock()
  139. if len(events) > 0 {
  140. return events, nil
  141. }
  142. // No events available, wait for new ones or timeout
  143. timeoutChan := time.After(timeout)
  144. for {
  145. select {
  146. case <-q.waitChan:
  147. // New events may be available
  148. q.mu.RLock()
  149. events = q.getEventsAfter(lastSeqNum)
  150. q.mu.RUnlock()
  151. if len(events) > 0 {
  152. return events, nil
  153. }
  154. // False alarm, keep waiting
  155. case <-timeoutChan:
  156. // Timeout reached, return empty array
  157. return []Event{}, nil
  158. case <-ctx.Done():
  159. // Context cancelled
  160. return nil, ctx.Err()
  161. }
  162. }
  163. }
  164. // getEventsAfter returns all events with sequence number greater than the specified value.
  165. // Must be called with at least a read lock held.
  166. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  167. var result []Event
  168. for _, event := range q.events {
  169. if event.SeqNum > seqNum {
  170. result = append(result, event)
  171. }
  172. }
  173. return result
  174. }
  175. // GetAllEvents returns all events in the queue (for debugging).
  176. func (q *EventQueue) GetAllEvents() []Event {
  177. q.mu.RLock()
  178. defer q.mu.RUnlock()
  179. result := make([]Event, len(q.events))
  180. copy(result, q.events)
  181. return result
  182. }
  183. // Clear removes all events from the queue.
  184. func (q *EventQueue) Clear() {
  185. q.mu.Lock()
  186. defer q.mu.Unlock()
  187. q.events = make([]Event, 0)
  188. }
  189. // Size returns the current number of events in the queue.
  190. func (q *EventQueue) Size() int {
  191. q.mu.RLock()
  192. defer q.mu.RUnlock()
  193. return len(q.events)
  194. }
  195. // Close closes the event queue, unblocking any waiting fetchers.
  196. func (q *EventQueue) Close() {
  197. q.closedMu.Lock()
  198. defer q.closedMu.Unlock()
  199. if q.closed {
  200. return
  201. }
  202. q.closed = true
  203. // Send multiple signals to unblock all potential waiters
  204. notifyWaiters:
  205. for i := 0; i < 10; i++ {
  206. select {
  207. case q.waitChan <- struct{}{}:
  208. default:
  209. break notifyWaiters
  210. }
  211. }
  212. }
  213. // IsClosed returns whether the queue is closed.
  214. func (q *EventQueue) IsClosed() bool {
  215. q.closedMu.RLock()
  216. defer q.closedMu.RUnlock()
  217. return q.closed
  218. }