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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. "time"
  8. )
  9. type ItemType uint
  10. const (
  11. uninitializedItem ItemType = iota
  12. Privmsg
  13. Notice
  14. Join
  15. Part
  16. Kick
  17. Quit
  18. Mode
  19. Tagmsg
  20. Nick
  21. )
  22. const (
  23. initialAutoSize = 32
  24. )
  25. // a Tagmsg that consists entirely of transient tags is not stored
  26. var transientTags = map[string]bool{
  27. "+draft/typing": true,
  28. "+typing": true, // future-proofing
  29. }
  30. // Item represents an event (e.g., a PRIVMSG or a JOIN) and its associated data
  31. type Item struct {
  32. Type ItemType
  33. Nick string
  34. // this is the uncasefolded account name, if there's no account it should be set to "*"
  35. AccountName string
  36. // for non-privmsg items, we may stuff some other data in here
  37. Message utils.SplitMessage
  38. Tags map[string]string
  39. Params [1]string
  40. CfCorrespondent string
  41. }
  42. // HasMsgid tests whether a message has the message id `msgid`.
  43. func (item *Item) HasMsgid(msgid string) bool {
  44. return item.Message.Msgid == msgid
  45. }
  46. func (item *Item) IsStorable() bool {
  47. switch item.Type {
  48. case Tagmsg:
  49. for name := range item.Tags {
  50. if !transientTags[name] {
  51. return true
  52. }
  53. }
  54. return false // all tags were blacklisted
  55. case Privmsg, Notice:
  56. // don't store CTCP other than ACTION
  57. return !item.Message.IsRestrictedCTCPMessage()
  58. default:
  59. return true
  60. }
  61. }
  62. type Predicate func(item *Item) (matches bool)
  63. func Reverse(results []Item) {
  64. for i, j := 0, len(results)-1; i < j; i, j = i+1, j-1 {
  65. results[i], results[j] = results[j], results[i]
  66. }
  67. }
  68. // Buffer is a ring buffer holding message/event history for a channel or user
  69. type Buffer struct {
  70. sync.RWMutex
  71. // ring buffer, see irc/whowas.go for conventions
  72. buffer []Item
  73. start int
  74. end int
  75. maximumSize int
  76. window time.Duration
  77. lastDiscarded time.Time
  78. nowFunc func() time.Time
  79. }
  80. func NewHistoryBuffer(size int, window time.Duration) (result *Buffer) {
  81. result = new(Buffer)
  82. result.Initialize(size, window)
  83. return
  84. }
  85. func (hist *Buffer) Initialize(size int, window time.Duration) {
  86. hist.buffer = make([]Item, hist.initialSize(size, window))
  87. hist.start = -1
  88. hist.end = -1
  89. hist.window = window
  90. hist.maximumSize = size
  91. hist.nowFunc = time.Now
  92. }
  93. // compute the initial size for the buffer, taking into account autoresize
  94. func (hist *Buffer) initialSize(size int, window time.Duration) (result int) {
  95. result = size
  96. if window != 0 {
  97. result = initialAutoSize
  98. if size < result {
  99. result = size // min(initialAutoSize, size)
  100. }
  101. }
  102. return
  103. }
  104. // Add adds a history item to the buffer
  105. func (list *Buffer) Add(item Item) {
  106. if item.Message.Time.IsZero() {
  107. item.Message.Time = time.Now().UTC()
  108. }
  109. list.Lock()
  110. defer list.Unlock()
  111. if len(list.buffer) == 0 {
  112. return
  113. }
  114. list.maybeExpand()
  115. var pos int
  116. if list.start == -1 { // empty
  117. pos = 0
  118. list.start = 0
  119. list.end = 1 % len(list.buffer)
  120. } else if list.start != list.end { // partially full
  121. pos = list.end
  122. list.end = (list.end + 1) % len(list.buffer)
  123. } else if list.start == list.end { // full
  124. pos = list.end
  125. list.end = (list.end + 1) % len(list.buffer)
  126. list.start = list.end // advance start as well, overwriting first entry
  127. // record the timestamp of the overwritten item
  128. if list.lastDiscarded.Before(list.buffer[pos].Message.Time) {
  129. list.lastDiscarded = list.buffer[pos].Message.Time
  130. }
  131. }
  132. list.buffer[pos] = item
  133. }
  134. func (list *Buffer) lookup(msgid string) (result Item, found bool) {
  135. predicate := func(item *Item) bool {
  136. return item.HasMsgid(msgid)
  137. }
  138. results := list.matchInternal(predicate, false, 1)
  139. if len(results) != 0 {
  140. return results[0], true
  141. }
  142. return
  143. }
  144. // Between returns all history items with a time `after` <= time <= `before`,
  145. // with an indication of whether the results are complete or are missing items
  146. // because some of that period was discarded. A zero value of `before` is considered
  147. // higher than all other times.
  148. func (list *Buffer) betweenHelper(start, end Selector, cutoff time.Time, pred Predicate, limit int) (results []Item, complete bool, err error) {
  149. var ascending bool
  150. defer func() {
  151. if !ascending {
  152. Reverse(results)
  153. }
  154. }()
  155. list.RLock()
  156. defer list.RUnlock()
  157. if len(list.buffer) == 0 {
  158. return
  159. }
  160. after := start.Time
  161. if start.Msgid != "" {
  162. item, found := list.lookup(start.Msgid)
  163. if !found {
  164. return
  165. }
  166. after = item.Message.Time
  167. }
  168. before := end.Time
  169. if end.Msgid != "" {
  170. item, found := list.lookup(end.Msgid)
  171. if !found {
  172. return
  173. }
  174. before = item.Message.Time
  175. }
  176. after, before, ascending = MinMaxAsc(after, before, cutoff)
  177. complete = after.Equal(list.lastDiscarded) || after.After(list.lastDiscarded)
  178. satisfies := func(item *Item) bool {
  179. return (after.IsZero() || item.Message.Time.After(after)) &&
  180. (before.IsZero() || item.Message.Time.Before(before)) &&
  181. (pred == nil || pred(item))
  182. }
  183. return list.matchInternal(satisfies, ascending, limit), complete, nil
  184. }
  185. // implements history.Sequence, emulating a single history buffer (for a channel,
  186. // a single user's DMs, or a DM conversation)
  187. type bufferSequence struct {
  188. list *Buffer
  189. pred Predicate
  190. cutoff time.Time
  191. }
  192. func (list *Buffer) MakeSequence(correspondent string, cutoff time.Time) Sequence {
  193. var pred Predicate
  194. if correspondent != "" {
  195. pred = func(item *Item) bool {
  196. return item.CfCorrespondent == correspondent
  197. }
  198. }
  199. return &bufferSequence{
  200. list: list,
  201. pred: pred,
  202. cutoff: cutoff,
  203. }
  204. }
  205. func (seq *bufferSequence) Between(start, end Selector, limit int) (results []Item, complete bool, err error) {
  206. return seq.list.betweenHelper(start, end, seq.cutoff, seq.pred, limit)
  207. }
  208. func (seq *bufferSequence) Around(start Selector, limit int) (results []Item, err error) {
  209. return GenericAround(seq, start, limit)
  210. }
  211. // you must be holding the read lock to call this
  212. func (list *Buffer) matchInternal(predicate Predicate, ascending bool, limit int) (results []Item) {
  213. if list.start == -1 || len(list.buffer) == 0 {
  214. return
  215. }
  216. var pos, stop int
  217. if ascending {
  218. pos = list.start
  219. stop = list.prev(list.end)
  220. } else {
  221. pos = list.prev(list.end)
  222. stop = list.start
  223. }
  224. for {
  225. if predicate(&list.buffer[pos]) {
  226. results = append(results, list.buffer[pos])
  227. }
  228. if pos == stop || (limit != 0 && len(results) == limit) {
  229. break
  230. }
  231. if ascending {
  232. pos = list.next(pos)
  233. } else {
  234. pos = list.prev(pos)
  235. }
  236. }
  237. return
  238. }
  239. // latest returns the items most recently added, up to `limit`. If `limit` is 0,
  240. // it returns all items.
  241. func (list *Buffer) latest(limit int) (results []Item) {
  242. results, _, _ = list.betweenHelper(Selector{}, Selector{}, time.Time{}, nil, limit)
  243. return
  244. }
  245. // LastDiscarded returns the latest time of any entry that was evicted
  246. // from the ring buffer.
  247. func (list *Buffer) LastDiscarded() time.Time {
  248. list.RLock()
  249. defer list.RUnlock()
  250. return list.lastDiscarded
  251. }
  252. func (list *Buffer) prev(index int) int {
  253. switch index {
  254. case 0:
  255. return len(list.buffer) - 1
  256. default:
  257. return index - 1
  258. }
  259. }
  260. func (list *Buffer) next(index int) int {
  261. switch index {
  262. case len(list.buffer) - 1:
  263. return 0
  264. default:
  265. return index + 1
  266. }
  267. }
  268. // return n such that v <= n and n == 2**i for some i
  269. func roundUpToPowerOfTwo(v int) int {
  270. // http://graphics.stanford.edu/~seander/bithacks.html
  271. v -= 1
  272. v |= v >> 1
  273. v |= v >> 2
  274. v |= v >> 4
  275. v |= v >> 8
  276. v |= v >> 16
  277. return v + 1
  278. }
  279. func (list *Buffer) maybeExpand() {
  280. if list.window == 0 {
  281. return // autoresize is disabled
  282. }
  283. length := list.length()
  284. if length < len(list.buffer) {
  285. return // we have spare capacity already
  286. }
  287. if len(list.buffer) == list.maximumSize {
  288. return // cannot expand any further
  289. }
  290. wouldDiscard := list.buffer[list.start].Message.Time
  291. if list.window < list.nowFunc().Sub(wouldDiscard) {
  292. return // oldest element is old enough to overwrite
  293. }
  294. newSize := roundUpToPowerOfTwo(length + 1)
  295. if list.maximumSize < newSize {
  296. newSize = list.maximumSize
  297. }
  298. list.resize(newSize)
  299. }
  300. // Resize shrinks or expands the buffer
  301. func (list *Buffer) Resize(maximumSize int, window time.Duration) {
  302. list.Lock()
  303. defer list.Unlock()
  304. if list.maximumSize == maximumSize && list.window == window {
  305. return // no-op
  306. }
  307. list.maximumSize = maximumSize
  308. list.window = window
  309. // three cases where we need to preemptively resize:
  310. // (1) we are not autoresizing
  311. // (2) the buffer is currently larger than maximumSize and needs to be shrunk
  312. // (3) the buffer is currently smaller than the recommended initial size
  313. // (including the case where it is currently disabled and needs to be enabled)
  314. // TODO make it possible to shrink the buffer so that it only contains `window`
  315. if window == 0 || maximumSize < len(list.buffer) {
  316. list.resize(maximumSize)
  317. } else {
  318. initialSize := list.initialSize(maximumSize, window)
  319. if len(list.buffer) < initialSize {
  320. list.resize(initialSize)
  321. }
  322. }
  323. }
  324. func (list *Buffer) resize(size int) {
  325. newbuffer := make([]Item, size)
  326. if list.start == -1 {
  327. // indices are already correct and nothing needs to be copied
  328. } else if size == 0 {
  329. // this is now the empty list
  330. list.start = -1
  331. list.end = -1
  332. } else {
  333. currentLength := list.length()
  334. start := list.start
  335. end := list.end
  336. // if we're truncating, keep the latest entries, not the earliest
  337. if size < currentLength {
  338. start = list.end - size
  339. if start < 0 {
  340. start += len(list.buffer)
  341. }
  342. // update lastDiscarded for discarded entries
  343. for i := list.start; i != start; i = (i + 1) % len(list.buffer) {
  344. if list.lastDiscarded.Before(list.buffer[i].Message.Time) {
  345. list.lastDiscarded = list.buffer[i].Message.Time
  346. }
  347. }
  348. }
  349. if start < end {
  350. copied := copy(newbuffer, list.buffer[start:end])
  351. list.start = 0
  352. list.end = copied % size
  353. } else {
  354. lenInitial := len(list.buffer) - start
  355. copied := copy(newbuffer, list.buffer[start:])
  356. copied += copy(newbuffer[lenInitial:], list.buffer[:end])
  357. list.start = 0
  358. list.end = copied % size
  359. }
  360. }
  361. list.buffer = newbuffer
  362. }
  363. func (hist *Buffer) length() int {
  364. if hist.start == -1 {
  365. return 0
  366. } else if hist.start < hist.end {
  367. return hist.end - hist.start
  368. } else {
  369. return len(hist.buffer) - (hist.start - hist.end)
  370. }
  371. }