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.

history.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package history
  4. import (
  5. "github.com/oragono/oragono/irc/utils"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. )
  10. type ItemType uint
  11. const (
  12. uninitializedItem ItemType = iota
  13. Privmsg
  14. Notice
  15. Join
  16. Part
  17. Kick
  18. Quit
  19. Mode
  20. )
  21. // Item represents an event (e.g., a PRIVMSG or a JOIN) and its associated data
  22. type Item struct {
  23. Type ItemType
  24. Time time.Time
  25. Nick string
  26. // this is the uncasefolded account name, if there's no account it should be set to "*"
  27. AccountName string
  28. Message utils.SplitMessage
  29. // for non-privmsg items, we may stuff some other data in here
  30. Msgid string
  31. }
  32. // HasMsgid tests whether a message has the message id `msgid`.
  33. func (item *Item) HasMsgid(msgid string) bool {
  34. // XXX we stuff other data in the Msgid field sometimes,
  35. // don't match it by accident
  36. return (item.Type == Privmsg || item.Type == Notice) && item.Msgid == msgid
  37. }
  38. type Predicate func(item Item) (matches bool)
  39. // Buffer is a ring buffer holding message/event history for a channel or user
  40. type Buffer struct {
  41. sync.RWMutex
  42. // ring buffer, see irc/whowas.go for conventions
  43. buffer []Item
  44. start int
  45. end int
  46. lastDiscarded time.Time
  47. enabled uint32
  48. }
  49. func NewHistoryBuffer(size int) (result *Buffer) {
  50. result = new(Buffer)
  51. result.Initialize(size)
  52. return
  53. }
  54. func (hist *Buffer) Initialize(size int) {
  55. hist.buffer = make([]Item, size)
  56. hist.start = -1
  57. hist.end = -1
  58. hist.setEnabled(size)
  59. }
  60. func (hist *Buffer) setEnabled(size int) {
  61. var enabled uint32
  62. if size != 0 {
  63. enabled = 1
  64. }
  65. atomic.StoreUint32(&hist.enabled, enabled)
  66. }
  67. // Enabled returns whether the buffer is currently storing messages
  68. // (a disabled buffer blackholes everything it sees)
  69. func (list *Buffer) Enabled() bool {
  70. return atomic.LoadUint32(&list.enabled) != 0
  71. }
  72. // Add adds a history item to the buffer
  73. func (list *Buffer) Add(item Item) {
  74. // fast path without a lock acquisition for when we are not storing history
  75. if !list.Enabled() {
  76. return
  77. }
  78. if item.Time.IsZero() {
  79. item.Time = time.Now().UTC()
  80. }
  81. list.Lock()
  82. defer list.Unlock()
  83. var pos int
  84. if list.start == -1 { // empty
  85. pos = 0
  86. list.start = 0
  87. list.end = 1 % len(list.buffer)
  88. } else if list.start != list.end { // partially full
  89. pos = list.end
  90. list.end = (list.end + 1) % len(list.buffer)
  91. } else if list.start == list.end { // full
  92. pos = list.end
  93. list.end = (list.end + 1) % len(list.buffer)
  94. list.start = list.end // advance start as well, overwriting first entry
  95. // record the timestamp of the overwritten item
  96. if list.lastDiscarded.Before(list.buffer[pos].Time) {
  97. list.lastDiscarded = list.buffer[pos].Time
  98. }
  99. }
  100. list.buffer[pos] = item
  101. }
  102. // Reverse reverses an []Item, in-place.
  103. func Reverse(results []Item) {
  104. for i, j := 0, len(results)-1; i < j; i, j = i+1, j-1 {
  105. results[i], results[j] = results[j], results[i]
  106. }
  107. }
  108. // Between returns all history items with a time `after` <= time <= `before`,
  109. // with an indication of whether the results are complete or are missing items
  110. // because some of that period was discarded. A zero value of `before` is considered
  111. // higher than all other times.
  112. func (list *Buffer) Between(after, before time.Time, ascending bool, limit int) (results []Item, complete bool) {
  113. if !list.Enabled() {
  114. return
  115. }
  116. list.RLock()
  117. defer list.RUnlock()
  118. complete = after.Equal(list.lastDiscarded) || after.After(list.lastDiscarded)
  119. satisfies := func(item Item) bool {
  120. return (after.IsZero() || item.Time.After(after)) && (before.IsZero() || item.Time.Before(before))
  121. }
  122. return list.matchInternal(satisfies, ascending, limit), complete
  123. }
  124. // Match returns all history items such that `predicate` returns true for them.
  125. // Items are considered in reverse insertion order if `ascending` is false, or
  126. // in insertion order if `ascending` is true, up to a total of `limit` matches
  127. // if `limit` > 0 (unlimited otherwise).
  128. // `predicate` MAY be a closure that maintains its own state across invocations;
  129. // it MUST NOT acquire any locks or otherwise do anything weird.
  130. // Results are always returned in insertion order.
  131. func (list *Buffer) Match(predicate Predicate, ascending bool, limit int) (results []Item) {
  132. if !list.Enabled() {
  133. return
  134. }
  135. list.RLock()
  136. defer list.RUnlock()
  137. return list.matchInternal(predicate, ascending, limit)
  138. }
  139. // you must be holding the read lock to call this
  140. func (list *Buffer) matchInternal(predicate Predicate, ascending bool, limit int) (results []Item) {
  141. if list.start == -1 {
  142. return
  143. }
  144. var pos, stop int
  145. if ascending {
  146. pos = list.start
  147. stop = list.prev(list.end)
  148. } else {
  149. pos = list.prev(list.end)
  150. stop = list.start
  151. }
  152. for {
  153. if predicate(list.buffer[pos]) {
  154. results = append(results, list.buffer[pos])
  155. }
  156. if pos == stop || (limit != 0 && len(results) == limit) {
  157. break
  158. }
  159. if ascending {
  160. pos = list.next(pos)
  161. } else {
  162. pos = list.prev(pos)
  163. }
  164. }
  165. // TODO sort by time instead?
  166. if !ascending {
  167. Reverse(results)
  168. }
  169. return
  170. }
  171. // Latest returns the items most recently added, up to `limit`. If `limit` is 0,
  172. // it returns all items.
  173. func (list *Buffer) Latest(limit int) (results []Item) {
  174. matchAll := func(item Item) bool { return true }
  175. return list.Match(matchAll, false, limit)
  176. }
  177. // LastDiscarded returns the latest time of any entry that was evicted
  178. // from the ring buffer.
  179. func (list *Buffer) LastDiscarded() time.Time {
  180. list.RLock()
  181. defer list.RUnlock()
  182. return list.lastDiscarded
  183. }
  184. func (list *Buffer) prev(index int) int {
  185. switch index {
  186. case 0:
  187. return len(list.buffer) - 1
  188. default:
  189. return index - 1
  190. }
  191. }
  192. func (list *Buffer) next(index int) int {
  193. switch index {
  194. case len(list.buffer) - 1:
  195. return 0
  196. default:
  197. return index + 1
  198. }
  199. }
  200. // Resize shrinks or expands the buffer
  201. func (list *Buffer) Resize(size int) {
  202. newbuffer := make([]Item, size)
  203. list.Lock()
  204. defer list.Unlock()
  205. list.setEnabled(size)
  206. if list.start == -1 {
  207. // indices are already correct and nothing needs to be copied
  208. } else if size == 0 {
  209. // this is now the empty list
  210. list.start = -1
  211. list.end = -1
  212. } else {
  213. currentLength := list.length()
  214. start := list.start
  215. end := list.end
  216. // if we're truncating, keep the latest entries, not the earliest
  217. if size < currentLength {
  218. start = list.end - size
  219. if start < 0 {
  220. start += len(list.buffer)
  221. }
  222. // update lastDiscarded for discarded entries
  223. for i := list.start; i != start; i = (i + 1) % len(list.buffer) {
  224. if list.lastDiscarded.Before(list.buffer[i].Time) {
  225. list.lastDiscarded = list.buffer[i].Time
  226. }
  227. }
  228. }
  229. if start < end {
  230. copied := copy(newbuffer, list.buffer[start:end])
  231. list.start = 0
  232. list.end = copied % size
  233. } else {
  234. lenInitial := len(list.buffer) - start
  235. copied := copy(newbuffer, list.buffer[start:])
  236. copied += copy(newbuffer[lenInitial:], list.buffer[:end])
  237. list.start = 0
  238. list.end = copied % size
  239. }
  240. }
  241. list.buffer = newbuffer
  242. }
  243. func (hist *Buffer) length() int {
  244. if hist.start == -1 {
  245. return 0
  246. } else if hist.start < hist.end {
  247. return hist.end - hist.start
  248. } else {
  249. return len(hist.buffer) - (hist.start - hist.end)
  250. }
  251. }