archive.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "go-common/app/interface/main/push-archive/dao"
  9. "go-common/app/interface/main/push-archive/model"
  10. accmdl "go-common/app/service/main/account/model"
  11. "go-common/library/log"
  12. )
  13. const (
  14. _insertAct = "insert"
  15. _updateAct = "update"
  16. _deleteAct = "delete"
  17. _archiveTable = "archive"
  18. _pushRetryTimes = 3
  19. _pushPartSize = 500000 // 每次请求最多推50w mid
  20. _hbaseBatch = 100
  21. )
  22. func (s *Service) consumeArchiveproc() {
  23. defer s.wg.Done()
  24. var (
  25. err error
  26. msgs = s.archiveSub.Messages()
  27. )
  28. for {
  29. msg, ok := <-msgs
  30. if !ok {
  31. log.Warn("s.ArchiveSub has been closed.")
  32. return
  33. }
  34. msg.Commit()
  35. s.arcMo++
  36. log.Info("consume archive key(%s) offset(%d) message(%s)", msg.Key, msg.Offset, msg.Value)
  37. m := new(model.Message)
  38. if err = json.Unmarshal(msg.Value, &m); err != nil {
  39. log.Error("json.Unmarshal(%v) error(%v)", string(msg.Value), err)
  40. continue
  41. }
  42. if m.Table != _archiveTable {
  43. continue
  44. }
  45. n := new(model.Archive)
  46. if err = json.Unmarshal(m.New, n); err != nil {
  47. log.Error("json.Unmarshal(%s) error(%v)", m.New, err)
  48. continue
  49. }
  50. // 稿件过审
  51. switch m.Action {
  52. case _insertAct:
  53. if !n.IsNormal() {
  54. log.Info("archive (%d) upper(%d) is not normal when insert, no need to push", n.ID, n.Mid)
  55. continue
  56. }
  57. case _updateAct:
  58. o := new(model.Archive)
  59. if err = json.Unmarshal(m.Old, o); err != nil {
  60. log.Error("json.Unmarshal(%s) error(%v)", m.Old, err)
  61. continue
  62. }
  63. if !n.IsNormal() || o.State == n.State || o.PubTime == n.PubTime {
  64. log.Info("archive (%d) upper(%d) is not normal when update, no need to push", n.ID, n.Mid)
  65. continue
  66. }
  67. default:
  68. continue
  69. }
  70. dao.PromInfo("archive_push")
  71. // 在指定周期内,up主只推送一次
  72. if s.limit(n.Mid) {
  73. log.Info("upper's push limit upper(%d) aid(%d)", n.Mid, n.ID)
  74. continue
  75. }
  76. log.Info("noticeFans start, mid(%d) aid(%d)", n.Mid, n.ID)
  77. err = s.noticeFans(n) // notice fans
  78. log.Info("noticeFans end, mid(%d) aid(%d) error(%v)", n.Mid, n.ID, err)
  79. }
  80. }
  81. // isForbidTime 当前时间是否被禁止推送消息
  82. func (s *Service) isForbidTime() (forbid bool, err error) {
  83. var forbidStart, forbidEnd time.Time
  84. now := time.Now()
  85. for _, f := range s.ForbidTimes {
  86. forbidStart, err = s.getTodayTime(f.PushForbidStartTime)
  87. if err != nil {
  88. log.Error("isForbidTime getTodayTime(%s) error(%v)", f.PushForbidStartTime, err)
  89. return
  90. }
  91. forbidEnd, err = s.getTodayTime(f.PushForbidEndTime)
  92. if err != nil {
  93. log.Error("isForbidTime getTodayTime(%s) error(%v)", f.PushForbidEndTime, err)
  94. return
  95. }
  96. if now.After(forbidStart) && now.Before(forbidEnd) {
  97. forbid = true
  98. break
  99. }
  100. }
  101. return
  102. }
  103. func (s *Service) noticeFans(arc *model.Archive) (err error) {
  104. isPGC := s.isPGC(arc)
  105. mids, counter, err := s.fans(arc.Mid, arc.ID, isPGC)
  106. if err != nil {
  107. return
  108. }
  109. log.Info("noticeFans get fans mid(%d) aid(%d) fans number(%d)", arc.Mid, arc.ID, counter)
  110. arc.Author = s.name(arc.Mid)
  111. for gKey, list := range mids {
  112. g := s.dao.FanGroups[gKey]
  113. params := model.NewBatchParam(map[string]interface{}{
  114. "relationType": g.RelationType,
  115. "archive": arc,
  116. "group": s.getGroupParam(g),
  117. "msgTemplate": g.MsgTemplate,
  118. }, model.PushParamHandler)
  119. dao.Batch(&list, _pushPartSize, _pushRetryTimes, params, s.dao.NoticeFans)
  120. }
  121. return
  122. }
  123. func (s *Service) fans(upper int64, aid int64, isPGC bool) (mids map[string][]int64, counter int, err error) {
  124. mids = make(map[string][]int64)
  125. // 从 HBase 获取upper粉丝数据
  126. fans, err := s.dao.Fans(context.TODO(), upper, isPGC)
  127. ln := len(fans)
  128. if err != nil {
  129. log.Error("fans from hbase upper(%d) error(%v)", upper, err)
  130. return
  131. }
  132. log.Info("filter fans -- get all fans of upper(%d), fans num(%d)", upper, ln)
  133. if ln == 0 {
  134. return
  135. }
  136. dao.PromInfoAdd("archive_fans", int64(ln))
  137. // 筛选粉丝,分配到对应的实验组
  138. hitFans := s.group(upper, fans)
  139. hour := time.Now().Hour()
  140. for gKey, hits := range hitFans {
  141. log.Info("before filter by active time, upper(%d) group(%s) fans(%d)", upper, gKey, len(hits))
  142. if len(hits) <= 0 {
  143. continue
  144. }
  145. g := s.dao.FanGroups[gKey]
  146. var activeFans, excluded []int64
  147. if g.RelationType == model.RelationAttention {
  148. activeFans, excluded = s.dao.FansByActiveTime(hour, &hits)
  149. noLimitFans := s.noPushLimitFans(upper, gKey, &activeFans)
  150. for _, mid := range activeFans {
  151. if !s.filterUserSetting(mid, g.RelationType) {
  152. excluded = append(excluded, mid)
  153. log.Info("filter fans: excluded by usersettings, fan(%d), relationtype(%d), upper(%d) table(%s)", mid, g.RelationType, upper, g.HBaseTable)
  154. continue
  155. }
  156. if !s.pushLimit(mid, upper, g, &noLimitFans) {
  157. excluded = append(excluded, mid)
  158. continue
  159. }
  160. mids[gKey] = append(mids[gKey], mid)
  161. dao.PromInfo(fmt.Sprintf("%s__send", g.Name))
  162. log.Info("filter fans: included by pushlimit: upper(%d)'s fan(%d) group.name(%s)", upper, mid, g.Name)
  163. }
  164. } else {
  165. mids[gKey] = hits
  166. }
  167. counter += len(mids[gKey])
  168. log.Info("upper(%d) aid(%d) group(%s) fans(%d)", upper, aid, gKey, len(mids[gKey]))
  169. // 统计数据落表
  170. s.formStatisticsProc(aid, g.Name, mids[gKey], &excluded)
  171. }
  172. return
  173. }
  174. // group 粉丝分组: 分组优先级(优先级 & 分组的可用性)-->分组规则(默认default,hbase过滤走hbase)
  175. func (s *Service) group(upper int64, fans map[int64]int) (list map[string][]int64) {
  176. list = make(map[string][]int64)
  177. // 将粉丝分为 特殊关注 和 普通关注 两类
  178. attentions, specials := s.dao.FansByProportion(upper, fans)
  179. log.Info("group count upper(%d) attentions(%d) specials(%d)", upper, len(attentions), len(specials))
  180. // 禁止推送时间判断, 免打扰用户(针对普通关注)
  181. isForbid, err := s.isForbidTime()
  182. if err != nil {
  183. log.Error("isForbidTime upper(%d) error(%v)", upper, err)
  184. }
  185. // 按顺序筛选出每个分组的数据
  186. for _, gkey := range s.dao.GroupOrder {
  187. g := s.dao.FanGroups[gkey]
  188. if g.RelationType == model.RelationAttention && isForbid {
  189. log.Info("forbid by time upper(%d) group(%+v)", upper, g)
  190. continue
  191. }
  192. // 优先处理abtest的流量
  193. if g.Hitby == model.GroupDataTypeAbtest {
  194. switch g.RelationType {
  195. case model.RelationAttention:
  196. var pool, exists, ex []int64
  197. pool, attentions = s.fansByAbtest(g, attentions)
  198. for _, gk := range s.dao.GroupOrder {
  199. gg := s.dao.FanGroups[gk]
  200. if gg.RelationType != model.RelationAttention ||
  201. gg.Hitby != model.GroupDataTypeHBase ||
  202. gg.Name == "ai:pushlist_follow_recent" {
  203. continue
  204. }
  205. ex, pool = s.dao.FansByHBase(upper, gk, &pool)
  206. exists = append(exists, ex...)
  207. }
  208. list[gkey] = s.filterByBlacklist(upper, exists)
  209. case model.RelationSpecial:
  210. list[gkey], specials = s.fansByAbtest(g, specials)
  211. }
  212. continue
  213. }
  214. if g.Hitby == model.GroupDataTypeAbComparison {
  215. // 对照组保持原来逻辑
  216. switch g.RelationType {
  217. case model.RelationAttention:
  218. var pool, exists []int64
  219. pool, attentions = s.fansByAbtest(g, attentions)
  220. for _, gk := range s.dao.GroupOrder {
  221. gg := s.dao.FanGroups[gk]
  222. if gg.RelationType != model.RelationAttention || gg.Hitby != model.GroupDataTypeHBase {
  223. continue
  224. }
  225. exists, pool = s.dao.FansByHBase(upper, gk, &pool)
  226. list[gkey] = append(list[gkey], exists...)
  227. }
  228. case model.RelationSpecial:
  229. list[gkey], specials = s.fansByAbtest(g, specials)
  230. }
  231. continue
  232. }
  233. switch {
  234. case g.RelationType == model.RelationAttention && g.Hitby == model.GroupDataTypeDefault:
  235. list[gkey] = attentions
  236. attentions = []int64{}
  237. case g.RelationType == model.RelationSpecial && g.Hitby == model.GroupDataTypeDefault:
  238. list[gkey] = specials
  239. specials = []int64{}
  240. case g.RelationType == model.RelationAttention && g.Hitby == model.GroupDataTypeHBase:
  241. list[gkey], attentions = s.dao.FansByHBase(upper, gkey, &attentions)
  242. case g.RelationType == model.RelationSpecial && g.Hitby == model.GroupDataTypeHBase:
  243. list[gkey], specials = s.dao.FansByHBase(upper, gkey, &specials)
  244. default:
  245. log.Error("group failed for grouporder(%s) & group.relationtype(%d) & hitby(%s)", gkey, g.RelationType, g.Hitby)
  246. }
  247. }
  248. return
  249. }
  250. func (s *Service) filterByBlacklist(upper int64, fans []int64) (result []int64) {
  251. for {
  252. var mids []int64
  253. l := len(fans)
  254. if l == 0 {
  255. return
  256. }
  257. if l <= _hbaseBatch {
  258. mids = fans[:]
  259. fans = []int64{}
  260. } else {
  261. mids = fans[:_hbaseBatch]
  262. fans = fans[_hbaseBatch:]
  263. }
  264. exists, notExists := s.dao.ExistsInBlacklist(context.Background(), upper, mids)
  265. result = append(result, notExists...) // 不在黑名单中的用户直接可推
  266. exists, notExists = s.dao.ExistsInWhitelist(context.Background(), upper, exists)
  267. result = append(result, exists...) // 存在黑名单中但是后来被恢复到白名单中的用户可推
  268. for _, mid := range notExists {
  269. // 只出现在黑名单中的用户不推
  270. log.Warn("filter by blacklist, mid(%d)", mid)
  271. }
  272. }
  273. }
  274. // getGroupParam g.name被_分隔后的第1个/2个值(比如:ai:pushlist_offline_up的是offline, special的就是special)
  275. func (s *Service) getGroupParam(g *dao.FanGroup) string {
  276. p := strings.Split(g.Name, "_")
  277. if len(p) == 1 {
  278. return p[0]
  279. }
  280. if g.RelationType == model.RelationSpecial {
  281. return "s_" + p[1]
  282. }
  283. return p[1]
  284. }
  285. // filterUserSetting 普通关注up主的粉丝中,推送开启配置为全部推送的人很少,因此,只要其开启了特殊关注/全部关注/没有设置的就发送;特殊关注等同
  286. func (s *Service) filterUserSetting(mid int64, relationType int) bool {
  287. if relationType == model.RelationSpecial && s.userSettings[mid] != nil && s.userSettings[mid].Type == model.PushTypeForbid {
  288. return false
  289. }
  290. if relationType == model.RelationAttention && s.userSettings[mid] != nil && s.userSettings[mid].Type == model.PushTypeForbid {
  291. return false
  292. }
  293. return true
  294. }
  295. func (s *Service) name(mid int64) (name string) {
  296. arg := &accmdl.ArgMid{Mid: mid}
  297. info, err := s.accRPC.Info3(context.TODO(), arg)
  298. if err != nil {
  299. dao.PromError("archive:获取作者信息")
  300. log.Error("s.accRPC.Info3(%+v) error(%v)", arg, err)
  301. return
  302. }
  303. name = info.Name
  304. return
  305. }
  306. func (s *Service) isPGC(arc *model.Archive) bool {
  307. return (arc.Attribute >> model.AttrBitIsPGC & 1) == 1
  308. }
  309. // Test for test
  310. // TODO delete, for test
  311. func (s *Service) Test(arc *model.Archive) {
  312. if arc.ID == 0 || arc.Mid == 0 {
  313. return
  314. }
  315. go s.noticeFans(arc)
  316. } // TODO delete, for test