request_tracker.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package oscarclient
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/mk6i/open-oscar-server/wire"
  6. )
  7. // requestTTL is how long a sent SNAC waits for a reply before it is no
  8. // longer tracked. Requests the server drops, such as rate-limited ones, never
  9. // get a reply.
  10. const requestTTL = 60 * time.Second
  11. // RequestTracker tracks the SNACs a client sends to the OSCAR server by
  12. // request ID, so that a reply can be matched to the request that produced it.
  13. type RequestTracker struct {
  14. mu sync.Mutex
  15. lastID uint32
  16. entries map[uint32]pendingRequest
  17. timeNow func() time.Time
  18. }
  19. // pendingRequest is a SNAC request awaiting a reply.
  20. type pendingRequest struct {
  21. // frame is the request's SNAC frame.
  22. frame wire.SNACFrame
  23. // data holds whatever the reply handler needs to know about the request.
  24. data any
  25. sentAt time.Time
  26. }
  27. // NewRequestTracker creates a RequestTracker with no pending requests.
  28. func NewRequestTracker() *RequestTracker {
  29. return &RequestTracker{
  30. entries: make(map[uint32]pendingRequest),
  31. timeNow: time.Now,
  32. }
  33. }
  34. // Track records the request frame along with data under the next request ID,
  35. // and returns frame with that request ID set. Entries older than requestTTL
  36. // are swept out.
  37. func (c *RequestTracker) Track(frame wire.SNACFrame, data any) wire.SNACFrame {
  38. c.mu.Lock()
  39. defer c.mu.Unlock()
  40. now := c.timeNow()
  41. for id, entry := range c.entries {
  42. if now.Sub(entry.sentAt) > requestTTL {
  43. delete(c.entries, id)
  44. }
  45. }
  46. c.lastID++
  47. if c.lastID >= wire.ReqIDFromServer {
  48. c.lastID = 1
  49. }
  50. frame.RequestID = c.lastID
  51. c.entries[frame.RequestID] = pendingRequest{
  52. frame: frame,
  53. data: data,
  54. sentAt: now,
  55. }
  56. return frame
  57. }
  58. // Take removes the request that reply answers and returns the frame and data
  59. // it was tracked with. The request ID alone identifies the request: the OSCAR
  60. // server sends a client only its own request IDs, 0, or wire.ReqIDFromServer,
  61. // and Track hands out neither of the latter two.
  62. func (c *RequestTracker) Take(reply wire.SNACFrame) (frame wire.SNACFrame, data any, ok bool) {
  63. c.mu.Lock()
  64. defer c.mu.Unlock()
  65. entry, ok := c.entries[reply.RequestID]
  66. if !ok {
  67. return wire.SNACFrame{}, nil, false
  68. }
  69. delete(c.entries, reply.RequestID)
  70. return entry.frame, entry.data, true
  71. }
  72. // Remove drops the request with the given ID.
  73. func (c *RequestTracker) Remove(requestID uint32) {
  74. c.mu.Lock()
  75. defer c.mu.Unlock()
  76. delete(c.entries, requestID)
  77. }