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

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