You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

responsebuffer.go 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "runtime/debug"
  6. "time"
  7. "github.com/goshuirc/irc-go/ircmsg"
  8. "github.com/oragono/oragono/irc/caps"
  9. "github.com/oragono/oragono/irc/utils"
  10. )
  11. const (
  12. // https://ircv3.net/specs/extensions/labeled-response.html
  13. defaultBatchType = "draft/labeled-response"
  14. )
  15. // ResponseBuffer - put simply - buffers messages and then outputs them to a given client.
  16. //
  17. // Using a ResponseBuffer lets you really easily implement labeled-response, since the
  18. // buffer will silently create a batch if required and label the outgoing messages as
  19. // necessary (or leave it off and simply tag the outgoing message).
  20. type ResponseBuffer struct {
  21. Label string
  22. batchID string
  23. target *Client
  24. messages []ircmsg.IrcMessage
  25. finalized bool
  26. }
  27. // GetLabel returns the label from the given message.
  28. func GetLabel(msg ircmsg.IrcMessage) string {
  29. _, value := msg.GetTag(caps.LabelTagName)
  30. return value
  31. }
  32. // NewResponseBuffer returns a new ResponseBuffer.
  33. func NewResponseBuffer(target *Client) *ResponseBuffer {
  34. return &ResponseBuffer{
  35. target: target,
  36. }
  37. }
  38. func (rb *ResponseBuffer) AddMessage(msg ircmsg.IrcMessage) {
  39. if rb.finalized {
  40. rb.target.server.logger.Error("internal", "message added to finalized ResponseBuffer, undefined behavior")
  41. debug.PrintStack()
  42. // TODO(dan): send a NOTICE to the end user with a string representation of the message,
  43. // for debugging purposes
  44. return
  45. }
  46. rb.messages = append(rb.messages, msg)
  47. }
  48. // Add adds a standard new message to our queue.
  49. func (rb *ResponseBuffer) Add(tags map[string]string, prefix string, command string, params ...string) {
  50. rb.AddMessage(ircmsg.MakeMessage(tags, prefix, command, params...))
  51. }
  52. // AddFromClient adds a new message from a specific client to our queue.
  53. func (rb *ResponseBuffer) AddFromClient(msgid string, fromNickMask string, fromAccount string, tags map[string]string, command string, params ...string) {
  54. msg := ircmsg.MakeMessage(nil, fromNickMask, command, params...)
  55. msg.UpdateTags(tags)
  56. // attach account-tag
  57. if rb.target.capabilities.Has(caps.AccountTag) && fromAccount != "*" {
  58. msg.SetTag("account", fromAccount)
  59. }
  60. // attach message-id
  61. if len(msgid) > 0 && rb.target.capabilities.Has(caps.MessageTags) {
  62. msg.SetTag("draft/msgid", msgid)
  63. }
  64. rb.AddMessage(msg)
  65. }
  66. // AddSplitMessageFromClient adds a new split message from a specific client to our queue.
  67. func (rb *ResponseBuffer) AddSplitMessageFromClient(fromNickMask string, fromAccount string, tags map[string]string, command string, target string, message utils.SplitMessage) {
  68. if rb.target.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  69. rb.AddFromClient(message.Msgid, fromNickMask, fromAccount, tags, command, target, message.Message)
  70. } else {
  71. for _, messagePair := range message.Wrapped {
  72. rb.AddFromClient(messagePair.Msgid, fromNickMask, fromAccount, tags, command, target, messagePair.Message)
  73. }
  74. }
  75. }
  76. // InitializeBatch forcibly starts a batch of batch `batchType`.
  77. // Normally, Send/Flush will decide automatically whether to start a batch
  78. // of type draft/labeled-response. This allows changing the batch type
  79. // and forcing the creation of a possibly empty batch.
  80. func (rb *ResponseBuffer) InitializeBatch(batchType string, blocking bool) {
  81. rb.sendBatchStart(batchType, blocking)
  82. }
  83. func (rb *ResponseBuffer) sendBatchStart(batchType string, blocking bool) {
  84. if rb.batchID != "" {
  85. // batch already initialized
  86. return
  87. }
  88. // formerly this combined time.Now.UnixNano() in base 36 with an incrementing counter,
  89. // also in base 36. but let's just use a uuidv4-alike (26 base32 characters):
  90. rb.batchID = utils.GenerateSecretToken()
  91. message := ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", "+"+rb.batchID, batchType)
  92. if rb.Label != "" {
  93. message.SetTag(caps.LabelTagName, rb.Label)
  94. }
  95. rb.target.SendRawMessage(message, blocking)
  96. }
  97. func (rb *ResponseBuffer) sendBatchEnd(blocking bool) {
  98. if rb.batchID == "" {
  99. // we are not sending a batch, skip this
  100. return
  101. }
  102. message := ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", "-"+rb.batchID)
  103. rb.target.SendRawMessage(message, blocking)
  104. }
  105. // Send sends all messages in the buffer to the client.
  106. // Afterwards, the buffer is in an undefined state and MUST NOT be used further.
  107. // If `blocking` is true you MUST be sending to the client from its own goroutine.
  108. func (rb *ResponseBuffer) Send(blocking bool) error {
  109. return rb.flushInternal(true, blocking)
  110. }
  111. // Flush sends all messages in the buffer to the client.
  112. // Afterwards, the buffer can still be used. Client code MUST subsequently call Send()
  113. // to ensure that the final `BATCH -` message is sent.
  114. // If `blocking` is true you MUST be sending to the client from its own goroutine.
  115. func (rb *ResponseBuffer) Flush(blocking bool) error {
  116. return rb.flushInternal(false, blocking)
  117. }
  118. // flushInternal sends the contents of the buffer, either blocking or nonblocking
  119. // It sends the `BATCH +` message if the client supports it and it hasn't been sent already.
  120. // If `final` is true, it also sends `BATCH -` (if necessary).
  121. func (rb *ResponseBuffer) flushInternal(final bool, blocking bool) error {
  122. if rb.finalized {
  123. return nil
  124. }
  125. useLabel := rb.target.capabilities.Has(caps.LabeledResponse) && rb.Label != ""
  126. // use a batch if we have a label, and we either currently have 0 or 2+ messages,
  127. // or we are doing a Flush() and we have to assume that there will be more messages
  128. // in the future.
  129. useBatch := useLabel && (len(rb.messages) != 1 || !final)
  130. // if label but no batch, add label to first message
  131. if useLabel && !useBatch && len(rb.messages) == 1 && rb.batchID == "" {
  132. rb.messages[0].SetTag(caps.LabelTagName, rb.Label)
  133. } else if useBatch {
  134. rb.sendBatchStart(defaultBatchType, blocking)
  135. }
  136. // send each message out
  137. for _, message := range rb.messages {
  138. // attach server-time if needed
  139. if rb.target.capabilities.Has(caps.ServerTime) && !message.HasTag("time") {
  140. message.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  141. }
  142. // attach batch ID
  143. if rb.batchID != "" {
  144. message.SetTag("batch", rb.batchID)
  145. }
  146. // send message out
  147. rb.target.SendRawMessage(message, blocking)
  148. }
  149. // end batch if required
  150. if final {
  151. rb.sendBatchEnd(blocking)
  152. rb.finalized = true
  153. }
  154. // clear out any existing messages
  155. rb.messages = rb.messages[:0]
  156. return nil
  157. }
  158. // Notice sends the client the given notice from the server.
  159. func (rb *ResponseBuffer) Notice(text string) {
  160. rb.Add(nil, rb.target.server.name, "NOTICE", rb.target.nick, text)
  161. }