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

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