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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. // Copyright (c) 2018 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package history
  4. import (
  5. "github.com/ergochat/ergo/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. Topic
  22. Invite
  23. )
  24. const (
  25. initialAutoSize = 32
  26. )
  27. // Item represents an event (e.g., a PRIVMSG or a JOIN) and its associated data
  28. type Item struct {
  29. Type ItemType
  30. Nick string
  31. // this is the uncasefolded account name, if there's no account it should be set to "*"
  32. AccountName string
  33. // for non-privmsg items, we may stuff some other data in here
  34. Message utils.SplitMessage
  35. Tags map[string]string
  36. Params [1]string
  37. // for a DM, this is the casefolded nickname of the other party (whether this is
  38. // an incoming or outgoing message). this lets us emulate the "query buffer" functionality
  39. // required by CHATHISTORY:
  40. CfCorrespondent string `json:"CfCorrespondent,omitempty"`
  41. IsBot bool `json:"IsBot,omitempty"`
  42. }
  43. // HasMsgid tests whether a message has the message id `msgid`.
  44. func (item *Item) HasMsgid(msgid string) bool {
  45. return item.Message.Msgid == msgid
  46. }
  47. type Predicate func(item *Item) (matches bool)
  48. func Reverse(results []Item) {
  49. for i, j := 0, len(results)-1; i < j; i, j = i+1, j-1 {
  50. results[i], results[j] = results[j], results[i]
  51. }
  52. }
  53. // Buffer is a ring buffer holding message/event history for a channel or user
  54. type Buffer struct {
  55. sync.RWMutex
  56. // ring buffer, see irc/whowas.go for conventions
  57. buffer []Item
  58. start int
  59. end int
  60. maximumSize int
  61. window time.Duration
  62. lastDiscarded time.Time
  63. nowFunc func() time.Time
  64. }
  65. func NewHistoryBuffer(size int, window time.Duration) (result *Buffer) {
  66. result = new(Buffer)
  67. result.Initialize(size, window)
  68. return
  69. }
  70. func (hist *Buffer) Initialize(size int, window time.Duration) {
  71. hist.buffer = make([]Item, hist.initialSize(size, window))
  72. hist.start = -1
  73. hist.end = -1
  74. hist.window = window
  75. hist.maximumSize = size
  76. hist.nowFunc = time.Now
  77. }
  78. // compute the initial size for the buffer, taking into account autoresize
  79. func (hist *Buffer) initialSize(size int, window time.Duration) (result int) {
  80. result = size
  81. if window != 0 {
  82. result = initialAutoSize
  83. if size < result {
  84. result = size // min(initialAutoSize, size)
  85. }
  86. }
  87. return
  88. }
  89. // Add adds a history item to the buffer
  90. func (list *Buffer) Add(item Item) {
  91. if item.Message.Time.IsZero() {
  92. item.Message.Time = time.Now().UTC()
  93. }
  94. list.Lock()
  95. defer list.Unlock()
  96. if len(list.buffer) == 0 {
  97. return
  98. }
  99. list.maybeExpand()
  100. var pos int
  101. if list.start == -1 { // empty
  102. pos = 0
  103. list.start = 0
  104. list.end = 1 % len(list.buffer)
  105. } else if list.start != list.end { // partially full
  106. pos = list.end
  107. list.end = (list.end + 1) % len(list.buffer)
  108. } else if list.start == list.end { // full
  109. pos = list.end
  110. list.end = (list.end + 1) % len(list.buffer)
  111. list.start = list.end // advance start as well, overwriting first entry
  112. // record the timestamp of the overwritten item
  113. if list.lastDiscarded.Before(list.buffer[pos].Message.Time) {
  114. list.lastDiscarded = list.buffer[pos].Message.Time
  115. }
  116. }
  117. list.buffer[pos] = item
  118. }
  119. func (list *Buffer) lookup(msgid string) (result Item, found bool) {
  120. predicate := func(item *Item) bool {
  121. return item.HasMsgid(msgid)
  122. }
  123. results := list.matchInternal(predicate, false, 1)
  124. if len(results) != 0 {
  125. return results[0], true
  126. }
  127. return
  128. }
  129. // Between returns all history items with a time `after` <= time <= `before`,
  130. // with an indication of whether the results are complete or are missing items
  131. // because some of that period was discarded. A zero value of `before` is considered
  132. // higher than all other times.
  133. func (list *Buffer) betweenHelper(start, end Selector, cutoff time.Time, pred Predicate, limit int) (results []Item, complete bool, err error) {
  134. var ascending bool
  135. defer func() {
  136. if !ascending {
  137. Reverse(results)
  138. }
  139. }()
  140. list.RLock()
  141. defer list.RUnlock()
  142. if len(list.buffer) == 0 {
  143. return
  144. }
  145. after := start.Time
  146. if start.Msgid != "" {
  147. item, found := list.lookup(start.Msgid)
  148. if !found {
  149. return
  150. }
  151. after = item.Message.Time
  152. }
  153. before := end.Time
  154. if end.Msgid != "" {
  155. item, found := list.lookup(end.Msgid)
  156. if !found {
  157. return
  158. }
  159. before = item.Message.Time
  160. }
  161. after, before, ascending = MinMaxAsc(after, before, cutoff)
  162. complete = after.Equal(list.lastDiscarded) || after.After(list.lastDiscarded)
  163. satisfies := func(item *Item) bool {
  164. return (after.IsZero() || item.Message.Time.After(after)) &&
  165. (before.IsZero() || item.Message.Time.Before(before)) &&
  166. (pred == nil || pred(item))
  167. }
  168. return list.matchInternal(satisfies, ascending, limit), complete, nil
  169. }
  170. // returns all correspondents, in reverse time order
  171. func (list *Buffer) allCorrespondents() (results []TargetListing) {
  172. seen := make(utils.StringSet)
  173. list.RLock()
  174. defer list.RUnlock()
  175. if list.start == -1 || len(list.buffer) == 0 {
  176. return
  177. }
  178. // XXX traverse in reverse order, so we get the latest timestamp
  179. // of any message sent to/from the correspondent
  180. pos := list.prev(list.end)
  181. stop := list.start
  182. for {
  183. if !seen.Has(list.buffer[pos].CfCorrespondent) {
  184. seen.Add(list.buffer[pos].CfCorrespondent)
  185. results = append(results, TargetListing{
  186. CfName: list.buffer[pos].CfCorrespondent,
  187. Time: list.buffer[pos].Message.Time,
  188. })
  189. }
  190. if pos == stop {
  191. break
  192. }
  193. pos = list.prev(pos)
  194. }
  195. return
  196. }
  197. // list DM correspondents, as one input to CHATHISTORY TARGETS
  198. func (list *Buffer) listCorrespondents(start, end Selector, cutoff time.Time, limit int) (results []TargetListing, err error) {
  199. after := start.Time
  200. before := end.Time
  201. after, before, ascending := MinMaxAsc(after, before, cutoff)
  202. correspondents := list.allCorrespondents()
  203. if len(correspondents) == 0 {
  204. return
  205. }
  206. // XXX allCorrespondents returns results in reverse order,
  207. // so if we're ascending, we actually go backwards
  208. var i int
  209. if ascending {
  210. i = len(correspondents) - 1
  211. } else {
  212. i = 0
  213. }
  214. for 0 <= i && i < len(correspondents) && (limit == 0 || len(results) < limit) {
  215. if (after.IsZero() || correspondents[i].Time.After(after)) &&
  216. (before.IsZero() || correspondents[i].Time.Before(before)) {
  217. results = append(results, correspondents[i])
  218. }
  219. if ascending {
  220. i--
  221. } else {
  222. i++
  223. }
  224. }
  225. if !ascending {
  226. ReverseCorrespondents(results)
  227. }
  228. return
  229. }
  230. // implements history.Sequence, emulating a single history buffer (for a channel,
  231. // a single user's DMs, or a DM conversation)
  232. type bufferSequence struct {
  233. list *Buffer
  234. pred Predicate
  235. cutoff time.Time
  236. }
  237. func (list *Buffer) MakeSequence(correspondent string, cutoff time.Time) Sequence {
  238. var pred Predicate
  239. if correspondent != "" {
  240. pred = func(item *Item) bool {
  241. return item.CfCorrespondent == correspondent
  242. }
  243. }
  244. return &bufferSequence{
  245. list: list,
  246. pred: pred,
  247. cutoff: cutoff,
  248. }
  249. }
  250. func (seq *bufferSequence) Between(start, end Selector, limit int) (results []Item, err error) {
  251. results, _, err = seq.list.betweenHelper(start, end, seq.cutoff, seq.pred, limit)
  252. return
  253. }
  254. func (seq *bufferSequence) Around(start Selector, limit int) (results []Item, err error) {
  255. return GenericAround(seq, start, limit)
  256. }
  257. func (seq *bufferSequence) ListCorrespondents(start, end Selector, limit int) (results []TargetListing, err error) {
  258. return seq.list.listCorrespondents(start, end, seq.cutoff, limit)
  259. }
  260. func (seq *bufferSequence) Cutoff() time.Time {
  261. return seq.cutoff
  262. }
  263. func (seq *bufferSequence) Ephemeral() bool {
  264. return true
  265. }
  266. // you must be holding the read lock to call this
  267. func (list *Buffer) matchInternal(predicate Predicate, ascending bool, limit int) (results []Item) {
  268. if list.start == -1 || len(list.buffer) == 0 {
  269. return
  270. }
  271. var pos, stop int
  272. if ascending {
  273. pos = list.start
  274. stop = list.prev(list.end)
  275. } else {
  276. pos = list.prev(list.end)
  277. stop = list.start
  278. }
  279. for {
  280. if predicate(&list.buffer[pos]) {
  281. results = append(results, list.buffer[pos])
  282. }
  283. if pos == stop || (limit != 0 && len(results) == limit) {
  284. break
  285. }
  286. if ascending {
  287. pos = list.next(pos)
  288. } else {
  289. pos = list.prev(pos)
  290. }
  291. }
  292. return
  293. }
  294. // Delete deletes messages matching some predicate.
  295. func (list *Buffer) Delete(predicate Predicate) (count int) {
  296. list.Lock()
  297. defer list.Unlock()
  298. if list.start == -1 || len(list.buffer) == 0 {
  299. return
  300. }
  301. pos := list.start
  302. stop := list.prev(list.end)
  303. for {
  304. if predicate(&list.buffer[pos]) {
  305. list.buffer[pos] = Item{}
  306. count++
  307. }
  308. if pos == stop {
  309. break
  310. }
  311. pos = list.next(pos)
  312. }
  313. return
  314. }
  315. // latest returns the items most recently added, up to `limit`. If `limit` is 0,
  316. // it returns all items.
  317. func (list *Buffer) latest(limit int) (results []Item) {
  318. results, _, _ = list.betweenHelper(Selector{}, Selector{}, time.Time{}, nil, limit)
  319. return
  320. }
  321. // LastDiscarded returns the latest time of any entry that was evicted
  322. // from the ring buffer.
  323. func (list *Buffer) LastDiscarded() time.Time {
  324. list.RLock()
  325. defer list.RUnlock()
  326. return list.lastDiscarded
  327. }
  328. func (list *Buffer) prev(index int) int {
  329. switch index {
  330. case 0:
  331. return len(list.buffer) - 1
  332. default:
  333. return index - 1
  334. }
  335. }
  336. func (list *Buffer) next(index int) int {
  337. switch index {
  338. case len(list.buffer) - 1:
  339. return 0
  340. default:
  341. return index + 1
  342. }
  343. }
  344. func (list *Buffer) maybeExpand() {
  345. if list.window == 0 {
  346. return // autoresize is disabled
  347. }
  348. length := list.length()
  349. if length < len(list.buffer) {
  350. return // we have spare capacity already
  351. }
  352. if len(list.buffer) == list.maximumSize {
  353. return // cannot expand any further
  354. }
  355. wouldDiscard := list.buffer[list.start].Message.Time
  356. if list.window < list.nowFunc().Sub(wouldDiscard) {
  357. return // oldest element is old enough to overwrite
  358. }
  359. newSize := utils.RoundUpToPowerOfTwo(length + 1)
  360. if list.maximumSize < newSize {
  361. newSize = list.maximumSize
  362. }
  363. list.resize(newSize)
  364. }
  365. // Resize shrinks or expands the buffer
  366. func (list *Buffer) Resize(maximumSize int, window time.Duration) {
  367. list.Lock()
  368. defer list.Unlock()
  369. if list.maximumSize == maximumSize && list.window == window {
  370. return // no-op
  371. }
  372. list.maximumSize = maximumSize
  373. list.window = window
  374. // three cases where we need to preemptively resize:
  375. // (1) we are not autoresizing
  376. // (2) the buffer is currently larger than maximumSize and needs to be shrunk
  377. // (3) the buffer is currently smaller than the recommended initial size
  378. // (including the case where it is currently disabled and needs to be enabled)
  379. // TODO make it possible to shrink the buffer so that it only contains `window`
  380. if window == 0 || maximumSize < len(list.buffer) {
  381. list.resize(maximumSize)
  382. } else {
  383. initialSize := list.initialSize(maximumSize, window)
  384. if len(list.buffer) < initialSize {
  385. list.resize(initialSize)
  386. }
  387. }
  388. }
  389. func (list *Buffer) resize(size int) {
  390. newbuffer := make([]Item, size)
  391. if list.start == -1 {
  392. // indices are already correct and nothing needs to be copied
  393. } else if size == 0 {
  394. // this is now the empty list
  395. list.start = -1
  396. list.end = -1
  397. } else {
  398. currentLength := list.length()
  399. start := list.start
  400. end := list.end
  401. // if we're truncating, keep the latest entries, not the earliest
  402. if size < currentLength {
  403. start = list.end - size
  404. if start < 0 {
  405. start += len(list.buffer)
  406. }
  407. // update lastDiscarded for discarded entries
  408. for i := list.start; i != start; i = (i + 1) % len(list.buffer) {
  409. if list.lastDiscarded.Before(list.buffer[i].Message.Time) {
  410. list.lastDiscarded = list.buffer[i].Message.Time
  411. }
  412. }
  413. }
  414. if start < end {
  415. copied := copy(newbuffer, list.buffer[start:end])
  416. list.start = 0
  417. list.end = copied % size
  418. } else {
  419. lenInitial := len(list.buffer) - start
  420. copied := copy(newbuffer, list.buffer[start:])
  421. copied += copy(newbuffer[lenInitial:], list.buffer[:end])
  422. list.start = 0
  423. list.end = copied % size
  424. }
  425. }
  426. list.buffer = newbuffer
  427. }
  428. func (hist *Buffer) length() int {
  429. if hist.start == -1 {
  430. return 0
  431. } else if hist.start < hist.end {
  432. return hist.end - hist.start
  433. } else {
  434. return len(hist.buffer) - (hist.start - hist.end)
  435. }
  436. }