actor-follow-score-cache.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { ACTOR_FOLLOW_SCORE } from '../../initializers/constants'
  2. import { logger } from '../../helpers/logger'
  3. // Cache follows scores, instead of writing them too often in database
  4. // Keep data in memory, we don't really need Redis here as we don't really care to loose some scores
  5. class ActorFollowScoreCache {
  6. private static instance: ActorFollowScoreCache
  7. private pendingFollowsScore: { [ url: string ]: number } = {}
  8. private pendingBadServer = new Set<number>()
  9. private pendingGoodServer = new Set<number>()
  10. private constructor () {}
  11. static get Instance () {
  12. return this.instance || (this.instance = new this())
  13. }
  14. updateActorFollowsScore (goodInboxes: string[], badInboxes: string[]) {
  15. if (goodInboxes.length === 0 && badInboxes.length === 0) return
  16. logger.info('Updating %d good actor follows and %d bad actor follows scores in cache.', goodInboxes.length, badInboxes.length)
  17. for (const goodInbox of goodInboxes) {
  18. if (this.pendingFollowsScore[goodInbox] === undefined) this.pendingFollowsScore[goodInbox] = 0
  19. this.pendingFollowsScore[goodInbox] += ACTOR_FOLLOW_SCORE.BONUS
  20. }
  21. for (const badInbox of badInboxes) {
  22. if (this.pendingFollowsScore[badInbox] === undefined) this.pendingFollowsScore[badInbox] = 0
  23. this.pendingFollowsScore[badInbox] += ACTOR_FOLLOW_SCORE.PENALTY
  24. }
  25. }
  26. addBadServerId (serverId: number) {
  27. this.pendingBadServer.add(serverId)
  28. }
  29. getBadFollowingServerIds () {
  30. return Array.from(this.pendingBadServer)
  31. }
  32. clearBadFollowingServerIds () {
  33. this.pendingBadServer = new Set<number>()
  34. }
  35. addGoodServerId (serverId: number) {
  36. this.pendingGoodServer.add(serverId)
  37. }
  38. getGoodFollowingServerIds () {
  39. return Array.from(this.pendingGoodServer)
  40. }
  41. clearGoodFollowingServerIds () {
  42. this.pendingGoodServer = new Set<number>()
  43. }
  44. getPendingFollowsScore () {
  45. return this.pendingFollowsScore
  46. }
  47. clearPendingFollowsScore () {
  48. this.pendingFollowsScore = {}
  49. }
  50. }
  51. export {
  52. ActorFollowScoreCache
  53. }