events.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package types
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. )
  8. // EventType defines the type of WebAPI event.
  9. type EventType string
  10. const (
  11. EventTypeBuddyList EventType = "buddylist"
  12. EventTypeConversation EventType = "conversation"
  13. EventTypeIM EventType = "im"
  14. EventTypeOfflineIM EventType = "offlineIM"
  15. EventTypePreference EventType = "preference"
  16. EventTypePresence EventType = "presence"
  17. EventTypeRateLimit EventType = "rateLimit"
  18. EventTypeSentIM EventType = "sentIM"
  19. EventTypeSessionEnded EventType = "sessionEnded"
  20. EventTypeStatus EventType = "status"
  21. EventTypeTyping EventType = "typing"
  22. EventTypePermitDeny EventType = "permitDeny"
  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. // Friendly repeats the viewer's alias for the user. The client's merge deletes any
  33. // alias it already holds, so a presence update that omits it silently renames the
  34. // buddy back to their screen name. See UserInfo.
  35. type PresenceEvent struct {
  36. AimID string `json:"aimId"`
  37. Friendly string `json:"friendly,omitempty"`
  38. State string `json:"state"` // "online", "offline", "away", "idle"
  39. StatusMsg string `json:"statusMsg,omitempty"`
  40. AwayMsg string `json:"awayMsg,omitempty"`
  41. IdleTime int `json:"idleTime,omitempty"` // Minutes idle
  42. OnlineTime int64 `json:"onlineTime,omitempty"` // Unix timestamp
  43. UserType string `json:"userType"` // "aim", "icq", "admin"
  44. BuddyIcon string `json:"buddyIcon,omitempty"` // Absolute icon URL; empty preserves the client's current icon, the placeholder URL clears it
  45. }
  46. // IMEvent represents an instant message event.
  47. type IMEvent struct {
  48. Source UserInfo `json:"source"`
  49. Message string `json:"message"`
  50. MsgID string `json:"msgId,omitempty"`
  51. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  52. AutoResp bool `json:"autoresponse,omitempty"`
  53. }
  54. // SentIMEvent represents a sent instant message event.
  55. type SentIMEvent struct {
  56. Sender UserInfo `json:"sender"` // Sender user info
  57. Dest UserInfo `json:"dest"` // Destination user info
  58. Message string `json:"message"`
  59. MsgID string `json:"msgId,omitempty"`
  60. Timestamp float64 `json:"timestamp"` // float64 for AMF3 encoding
  61. AutoResp bool `json:"autoResponse,omitempty"`
  62. }
  63. // UserInfo represents basic user information in events.
  64. // AimID is the normalized screen name the client keys users by. DisplayID is the
  65. // screen name as its owner formatted it. Friendly is the viewer's private alias for
  66. // that user, and takes precedence over DisplayID when the client renders a name.
  67. //
  68. // The client merges every user map it receives onto the single user object it holds
  69. // per aimId, and that merge deletes friendly before applying the map. An alias
  70. // therefore has to be repeated on every user map, or it is lost.
  71. type UserInfo struct {
  72. AimID string `json:"aimId"`
  73. DisplayID string `json:"displayId,omitempty"`
  74. Friendly string `json:"friendly,omitempty"`
  75. UserType string `json:"userType,omitempty"`
  76. State string `json:"state,omitempty"`
  77. OnlineTime float64 `json:"onlineTime,omitempty"` // float64 for AMF3 encoding
  78. }
  79. // TypingEvent represents a typing notification event.
  80. type TypingEvent struct {
  81. AimID string `json:"aimId"`
  82. TypingStatus string `json:"typingStatus"`
  83. }
  84. // EventQueue manages a queue of events for a WebAPI session.
  85. type EventQueue struct {
  86. events []Event
  87. seqNum uint64
  88. maxSize int
  89. mu sync.RWMutex
  90. waitChan chan struct{}
  91. closeChan chan struct{}
  92. closeOnce sync.Once
  93. }
  94. // isClosed reports whether Close has been called.
  95. func (q *EventQueue) isClosed() bool {
  96. select {
  97. case <-q.closeChan:
  98. return true
  99. default:
  100. return false
  101. }
  102. }
  103. // NewEventQueue creates a new event queue with the specified maximum size.
  104. func NewEventQueue(maxSize int) *EventQueue {
  105. return &EventQueue{
  106. events: make([]Event, 0),
  107. maxSize: maxSize,
  108. waitChan: make(chan struct{}, 1),
  109. closeChan: make(chan struct{}),
  110. }
  111. }
  112. // Push adds an event to the queue.
  113. func (q *EventQueue) Push(eventType EventType, data interface{}) {
  114. if q.isClosed() {
  115. return
  116. }
  117. q.mu.Lock()
  118. defer q.mu.Unlock()
  119. // Increment sequence number atomically
  120. seqNum := atomic.AddUint64(&q.seqNum, 1)
  121. event := Event{
  122. Type: eventType,
  123. SeqNum: seqNum,
  124. Timestamp: time.Now().Unix(),
  125. Data: data,
  126. }
  127. // Add event to queue
  128. q.events = append(q.events, event)
  129. // If queue exceeds max size, remove oldest events
  130. if len(q.events) > q.maxSize {
  131. // Keep only the most recent maxSize events
  132. q.events = q.events[len(q.events)-q.maxSize:]
  133. }
  134. // Signal any waiting fetchers
  135. select {
  136. case q.waitChan <- struct{}{}:
  137. default:
  138. // Channel already has a signal
  139. }
  140. }
  141. // Fetch retrieves events from the queue, optionally waiting for new events.
  142. func (q *EventQueue) Fetch(ctx context.Context, lastSeqNum uint64, timeout time.Duration) ([]Event, error) {
  143. if q.isClosed() {
  144. return []Event{}, nil
  145. }
  146. // First, check if we have any events newer than lastSeqNum
  147. q.mu.RLock()
  148. events := q.getEventsAfter(lastSeqNum)
  149. q.mu.RUnlock()
  150. if len(events) > 0 {
  151. return events, nil
  152. }
  153. // No events available, wait for new ones or timeout
  154. timeoutChan := time.After(timeout)
  155. for {
  156. select {
  157. case <-q.closeChan:
  158. return []Event{}, nil
  159. case <-q.waitChan:
  160. // New events may be available
  161. q.mu.RLock()
  162. events = q.getEventsAfter(lastSeqNum)
  163. q.mu.RUnlock()
  164. if len(events) > 0 {
  165. return events, nil
  166. }
  167. // False alarm, keep waiting
  168. case <-timeoutChan:
  169. // Timeout reached, return empty array
  170. return []Event{}, nil
  171. case <-ctx.Done():
  172. // Context cancelled
  173. return nil, ctx.Err()
  174. }
  175. }
  176. }
  177. // getEventsAfter returns all events with sequence number greater than the specified value.
  178. // Must be called with at least a read lock held.
  179. func (q *EventQueue) getEventsAfter(seqNum uint64) []Event {
  180. var result []Event
  181. for _, event := range q.events {
  182. if event.SeqNum > seqNum {
  183. result = append(result, event)
  184. }
  185. }
  186. return result
  187. }
  188. // GetAllEvents returns all events in the queue (for debugging).
  189. func (q *EventQueue) GetAllEvents() []Event {
  190. q.mu.RLock()
  191. defer q.mu.RUnlock()
  192. result := make([]Event, len(q.events))
  193. copy(result, q.events)
  194. return result
  195. }
  196. // Close closes the event queue, unblocking any waiting fetchers. Safe to call
  197. // more than once.
  198. func (q *EventQueue) Close() {
  199. q.closeOnce.Do(func() {
  200. close(q.closeChan)
  201. })
  202. }