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 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 // label if this is a labeled response batch
  22. batchID string // ID of the labeled response batch, if one has been initiated
  23. batchType string // type of the labeled response batch (possibly `history` or `chathistory`)
  24. // stack of batch IDs of nested batches, which are handled separately
  25. // from the underlying labeled-response batch. starting a new nested batch
  26. // unconditionally enqueues its batch start message; subsequent messages
  27. // are tagged with the nested batch ID, until nested batch end.
  28. // (the nested batch start itself may have no batch tag, or the batch tag of the
  29. // underlying labeled-response batch, or the batch tag of the next outermost
  30. // nested batch.)
  31. nestedBatches []string
  32. messages []ircmsg.IrcMessage
  33. finalized bool
  34. target *Client
  35. session *Session
  36. }
  37. // GetLabel returns the label from the given message.
  38. func GetLabel(msg ircmsg.IrcMessage) string {
  39. _, value := msg.GetTag(caps.LabelTagName)
  40. return value
  41. }
  42. // NewResponseBuffer returns a new ResponseBuffer.
  43. func NewResponseBuffer(session *Session) *ResponseBuffer {
  44. return &ResponseBuffer{
  45. session: session,
  46. target: session.client,
  47. batchType: defaultBatchType,
  48. }
  49. }
  50. func (rb *ResponseBuffer) AddMessage(msg ircmsg.IrcMessage) {
  51. if rb.finalized {
  52. rb.target.server.logger.Error("internal", "message added to finalized ResponseBuffer, undefined behavior")
  53. debug.PrintStack()
  54. // TODO(dan): send a NOTICE to the end user with a string representation of the message,
  55. // for debugging purposes
  56. return
  57. }
  58. if 0 < len(rb.nestedBatches) {
  59. msg.SetTag("batch", rb.nestedBatches[len(rb.nestedBatches)-1])
  60. }
  61. rb.messages = append(rb.messages, msg)
  62. }
  63. // Add adds a standard new message to our queue.
  64. func (rb *ResponseBuffer) Add(tags map[string]string, prefix string, command string, params ...string) {
  65. rb.AddMessage(ircmsg.MakeMessage(tags, prefix, command, params...))
  66. }
  67. // AddFromClient adds a new message from a specific client to our queue.
  68. func (rb *ResponseBuffer) AddFromClient(time time.Time, msgid string, fromNickMask string, fromAccount string, tags map[string]string, command string, params ...string) {
  69. msg := ircmsg.MakeMessage(nil, fromNickMask, command, params...)
  70. if rb.session.capabilities.Has(caps.MessageTags) {
  71. msg.UpdateTags(tags)
  72. }
  73. // attach account-tag
  74. if rb.session.capabilities.Has(caps.AccountTag) && fromAccount != "*" {
  75. msg.SetTag("account", fromAccount)
  76. }
  77. // attach message-id
  78. if len(msgid) > 0 && rb.session.capabilities.Has(caps.MessageTags) {
  79. msg.SetTag("msgid", msgid)
  80. }
  81. // attach server-time
  82. rb.session.setTimeTag(&msg, time)
  83. rb.AddMessage(msg)
  84. }
  85. // AddSplitMessageFromClient adds a new split message from a specific client to our queue.
  86. func (rb *ResponseBuffer) AddSplitMessageFromClient(fromNickMask string, fromAccount string, tags map[string]string, command string, target string, message utils.SplitMessage) {
  87. if rb.session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  88. rb.AddFromClient(message.Time, message.Msgid, fromNickMask, fromAccount, tags, command, target, message.Message)
  89. } else {
  90. for _, messagePair := range message.Wrapped {
  91. rb.AddFromClient(message.Time, messagePair.Msgid, fromNickMask, fromAccount, tags, command, target, messagePair.Message)
  92. }
  93. }
  94. }
  95. // ForceBatchStart forcibly starts a batch of batch `batchType`.
  96. // Normally, Send/Flush will decide automatically whether to start a batch
  97. // of type draft/labeled-response. This allows changing the batch type
  98. // and forcing the creation of a possibly empty batch.
  99. func (rb *ResponseBuffer) ForceBatchStart(batchType string, blocking bool) {
  100. rb.batchType = batchType
  101. rb.sendBatchStart(blocking)
  102. }
  103. func (rb *ResponseBuffer) sendBatchStart(blocking bool) {
  104. if rb.batchID != "" {
  105. // batch already initialized
  106. return
  107. }
  108. rb.batchID = utils.GenerateSecretToken()
  109. message := ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", "+"+rb.batchID, rb.batchType)
  110. if rb.Label != "" {
  111. message.SetTag(caps.LabelTagName, rb.Label)
  112. }
  113. rb.session.SendRawMessage(message, blocking)
  114. }
  115. func (rb *ResponseBuffer) sendBatchEnd(blocking bool) {
  116. if rb.batchID == "" {
  117. // we are not sending a batch, skip this
  118. return
  119. }
  120. message := ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", "-"+rb.batchID)
  121. rb.session.SendRawMessage(message, blocking)
  122. }
  123. // Starts a nested batch (see the ResponseBuffer struct definition for a description of
  124. // how this works)
  125. func (rb *ResponseBuffer) StartNestedBatch(batchType string, params ...string) (batchID string) {
  126. batchID = utils.GenerateSecretToken()
  127. msgParams := make([]string, len(params)+2)
  128. msgParams[0] = "+" + batchID
  129. msgParams[1] = batchType
  130. copy(msgParams[2:], params)
  131. rb.AddMessage(ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", msgParams...))
  132. rb.nestedBatches = append(rb.nestedBatches, batchID)
  133. return
  134. }
  135. // Ends a nested batch
  136. func (rb *ResponseBuffer) EndNestedBatch(batchID string) {
  137. if batchID == "" {
  138. return
  139. }
  140. if 0 == len(rb.nestedBatches) || rb.nestedBatches[len(rb.nestedBatches)-1] != batchID {
  141. rb.target.server.logger.Error("internal", "inconsistent batch nesting detected")
  142. debug.PrintStack()
  143. return
  144. }
  145. rb.nestedBatches = rb.nestedBatches[0 : len(rb.nestedBatches)-1]
  146. rb.AddMessage(ircmsg.MakeMessage(nil, rb.target.server.name, "BATCH", "-"+batchID))
  147. }
  148. // Convenience to start a nested batch for history lines, at the highest level
  149. // supported by the client (`history`, `chathistory`, or no batch, in descending order).
  150. func (rb *ResponseBuffer) StartNestedHistoryBatch(params ...string) (batchID string) {
  151. var batchType string
  152. if rb.session.capabilities.Has(caps.EventPlayback) {
  153. batchType = "history"
  154. } else if rb.session.capabilities.Has(caps.Batch) {
  155. batchType = "chathistory"
  156. }
  157. if batchType != "" {
  158. batchID = rb.StartNestedBatch(batchType, params...)
  159. }
  160. return
  161. }
  162. // Send sends all messages in the buffer to the client.
  163. // Afterwards, the buffer is in an undefined state and MUST NOT be used further.
  164. // If `blocking` is true you MUST be sending to the client from its own goroutine.
  165. func (rb *ResponseBuffer) Send(blocking bool) error {
  166. return rb.flushInternal(true, blocking)
  167. }
  168. // Flush sends all messages in the buffer to the client.
  169. // Afterwards, the buffer can still be used. Client code MUST subsequently call Send()
  170. // to ensure that the final `BATCH -` message is sent.
  171. // If `blocking` is true you MUST be sending to the client from its own goroutine.
  172. func (rb *ResponseBuffer) Flush(blocking bool) error {
  173. return rb.flushInternal(false, blocking)
  174. }
  175. // flushInternal sends the contents of the buffer, either blocking or nonblocking
  176. // It sends the `BATCH +` message if the client supports it and it hasn't been sent already.
  177. // If `final` is true, it also sends `BATCH -` (if necessary).
  178. func (rb *ResponseBuffer) flushInternal(final bool, blocking bool) error {
  179. if rb.finalized {
  180. return nil
  181. }
  182. useLabel := rb.session.capabilities.Has(caps.LabeledResponse) && rb.Label != ""
  183. // use a batch if we have a label, and we either currently have 2+ messages,
  184. // or we are doing a Flush() and we have to assume that there will be more messages
  185. // in the future.
  186. startBatch := useLabel && (1 < len(rb.messages) || !final)
  187. if startBatch {
  188. rb.sendBatchStart(blocking)
  189. } else if useLabel && len(rb.messages) == 0 && rb.batchID == "" && final {
  190. // ACK message
  191. message := ircmsg.MakeMessage(nil, rb.session.client.server.name, "ACK")
  192. message.SetTag(caps.LabelTagName, rb.Label)
  193. rb.session.setTimeTag(&message, time.Time{})
  194. rb.session.SendRawMessage(message, blocking)
  195. } else if useLabel && len(rb.messages) == 1 && rb.batchID == "" && final {
  196. // single labeled message
  197. rb.messages[0].SetTag(caps.LabelTagName, rb.Label)
  198. }
  199. // send each message out
  200. for _, message := range rb.messages {
  201. // attach server-time if needed
  202. rb.session.setTimeTag(&message, time.Time{})
  203. // attach batch ID, unless this message was part of a nested batch and is
  204. // already tagged
  205. if rb.batchID != "" && !message.HasTag("batch") {
  206. message.SetTag("batch", rb.batchID)
  207. }
  208. // send message out
  209. rb.session.SendRawMessage(message, blocking)
  210. }
  211. // end batch if required
  212. if final {
  213. rb.sendBatchEnd(blocking)
  214. rb.finalized = true
  215. }
  216. // clear out any existing messages
  217. rb.messages = rb.messages[:0]
  218. return nil
  219. }
  220. // Notice sends the client the given notice from the server.
  221. func (rb *ResponseBuffer) Notice(text string) {
  222. rb.Add(nil, rb.target.server.name, "NOTICE", rb.target.nick, text)
  223. }