service.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "sync"
  8. "time"
  9. artrpc "go-common/app/interface/openplatform/article/rpc/client"
  10. "go-common/app/job/main/reply/conf"
  11. "go-common/app/job/main/reply/dao/message"
  12. "go-common/app/job/main/reply/dao/notice"
  13. "go-common/app/job/main/reply/dao/reply"
  14. "go-common/app/job/main/reply/dao/search"
  15. "go-common/app/job/main/reply/dao/spam"
  16. "go-common/app/job/main/reply/dao/stat"
  17. model "go-common/app/job/main/reply/model/reply"
  18. accrpc "go-common/app/service/main/account/api"
  19. arcrpc "go-common/app/service/main/archive/api/gorpc"
  20. assrpc "go-common/app/service/main/assist/rpc/client"
  21. eprpc "go-common/app/service/openplatform/pgc-season/api/grpc/episode/v1"
  22. es "go-common/library/database/elastic"
  23. "go-common/library/log"
  24. xhttp "go-common/library/net/http/blademaster"
  25. "go-common/library/net/rpc/warden"
  26. "go-common/library/queue/databus"
  27. "go-common/library/sync/pipeline/fanout"
  28. )
  29. const (
  30. _chLen = 2048
  31. )
  32. var (
  33. _rpChs []chan *databus.Message
  34. _likeChs []chan *databus.Message
  35. )
  36. // action the message struct of kafka
  37. type consumerMsg struct {
  38. Action string `json:"action"`
  39. Data json.RawMessage `json:"data"`
  40. }
  41. type searchFlush struct {
  42. OldState int8
  43. Reply *model.Reply
  44. Report *model.Report
  45. }
  46. func (s *searchFlush) Key() (key string) {
  47. if s.Report != nil {
  48. return fmt.Sprintf("%d%d", s.Report.RpID, s.Report.ID)
  49. }
  50. return fmt.Sprintf("%d", s.Reply.RpID)
  51. }
  52. // Service is reply-job service
  53. type Service struct {
  54. c *conf.Config
  55. waiter *sync.WaitGroup
  56. dataConsumer *databus.Databus
  57. likeConsumer *databus.Databus
  58. searchChan chan *searchFlush
  59. // rpc client
  60. accSrv accrpc.AccountClient
  61. arcSrv *arcrpc.Service2
  62. articleSrv *artrpc.Service
  63. assistSrv *assrpc.Service
  64. bangumiSrv eprpc.EpisodeClient
  65. // depend
  66. messageDao *message.Dao
  67. // notice
  68. noticeDao *notice.Dao
  69. // stat
  70. statDao *stat.Dao
  71. // reply
  72. dao *reply.Dao
  73. // spam
  74. spam *spam.Cache
  75. // search
  76. searchDao *search.Dao
  77. batchNumber int
  78. es *es.Elastic
  79. notify *fanout.Fanout
  80. typeMapping map[int32]string
  81. aliasMapping map[string]int32
  82. marker *fanout.Fanout
  83. }
  84. // New return new service
  85. func New(c *conf.Config) (s *Service) {
  86. if c.Job.BatchNumber <= 0 {
  87. c.Job.BatchNumber = 2000
  88. }
  89. searchHTTPClient = xhttp.NewClient(c.HTTPClient)
  90. wardenClient := warden.DefaultClient()
  91. cc, err := wardenClient.Dial(context.Background(), "discovery://default/season.service")
  92. if err != nil {
  93. panic(err)
  94. }
  95. bangumiClient := eprpc.NewEpisodeClient(cc)
  96. s = &Service{
  97. c: c,
  98. bangumiSrv: bangumiClient,
  99. waiter: new(sync.WaitGroup),
  100. searchChan: make(chan *searchFlush, 1024),
  101. dataConsumer: databus.New(c.Databus.Consumer),
  102. likeConsumer: databus.New(c.Databus.Like),
  103. //rpc
  104. arcSrv: arcrpc.New2(c.RPCClient2.Archive),
  105. articleSrv: artrpc.New(c.RPCClient2.Article),
  106. assistSrv: assrpc.New(c.RPCClient2.Assist),
  107. messageDao: message.NewMessageDao(c),
  108. searchDao: search.New(c),
  109. noticeDao: notice.New(c),
  110. // stat
  111. statDao: stat.New(c),
  112. // init reply dao
  113. dao: reply.New(c),
  114. // init spam cache
  115. batchNumber: c.Job.BatchNumber,
  116. spam: spam.NewCache(c.Redis.Config),
  117. notify: fanout.New("cache", fanout.Worker(1), fanout.Buffer(2048)),
  118. typeMapping: make(map[int32]string),
  119. aliasMapping: make(map[string]int32),
  120. es: es.NewElastic(c.Es),
  121. marker: fanout.New("marker", fanout.Worker(1), fanout.Buffer(1024)),
  122. }
  123. accSvc, err := accrpc.NewClient(c.AccountClient)
  124. if err != nil {
  125. panic(err)
  126. }
  127. s.accSrv = accSvc
  128. time.Sleep(time.Second)
  129. _rpChs = make([]chan *databus.Message, c.Job.Proc)
  130. _likeChs = make([]chan *databus.Message, c.Job.Proc)
  131. for i := 0; i < c.Job.Proc; i++ {
  132. _rpChs[i] = make(chan *databus.Message, _chLen)
  133. _likeChs[i] = make(chan *databus.Message, _chLen)
  134. s.waiter.Add(1)
  135. go s.consumeproc(i)
  136. s.waiter.Add(1)
  137. go s.consumelikeproc(i)
  138. }
  139. s.waiter.Add(1)
  140. go s.likeConsume()
  141. s.waiter.Add(1)
  142. go s.dataConsume()
  143. go s.searchproc()
  144. go s.mappingproc()
  145. return
  146. }
  147. func (s *Service) addSearchUp(c context.Context, oldState int8, rp *model.Reply, rpt *model.Report) {
  148. select {
  149. case s.searchChan <- &searchFlush{OldState: oldState, Reply: rp, Report: rpt}:
  150. default:
  151. log.Error("addSearchUp chan full, type:%d oid:%d rpID:%d", rp.Type, rp.Oid, rp.RpID)
  152. }
  153. }
  154. func (s *Service) searchproc() {
  155. var (
  156. m *searchFlush
  157. merge = make(map[string]*searchFlush)
  158. num = s.c.Job.SearchNum
  159. ticker = time.NewTicker(time.Duration(s.c.Job.SearchFlush))
  160. )
  161. for {
  162. select {
  163. case m = <-s.searchChan:
  164. merge[m.Key()] = m
  165. if len(merge) < num {
  166. continue
  167. }
  168. case <-ticker.C:
  169. }
  170. if len(merge) > 0 {
  171. s.callSearchUp(context.Background(), merge)
  172. merge = make(map[string]*searchFlush)
  173. }
  174. }
  175. }
  176. func (s *Service) likeConsume() {
  177. defer func() {
  178. s.waiter.Done()
  179. for i := 0; i < s.c.Job.Proc; i++ {
  180. close(_rpChs[i])
  181. }
  182. }()
  183. msgs := s.likeConsumer.Messages()
  184. for {
  185. msg, ok := <-msgs
  186. if !ok {
  187. log.Warn("[service.dataConsume|reply] dataConsumer has been closed.")
  188. return
  189. }
  190. if msg.Topic != s.c.Databus.Like.Topic {
  191. continue
  192. }
  193. rpid, err := strconv.ParseInt(string(msg.Key), 10, 64)
  194. if err != nil {
  195. continue
  196. }
  197. _likeChs[rpid%int64(s.c.Job.Proc)] <- msg
  198. }
  199. }
  200. func (s *Service) dataConsume() {
  201. defer func() {
  202. s.waiter.Done()
  203. for i := 0; i < s.c.Job.Proc; i++ {
  204. close(_rpChs[i])
  205. }
  206. }()
  207. msgs := s.dataConsumer.Messages()
  208. for {
  209. msg, ok := <-msgs
  210. if !ok {
  211. log.Warn("[service.dataConsume|reply] dataConsumer has been closed.")
  212. return
  213. }
  214. if msg.Topic != s.c.Databus.Consumer.Topic {
  215. continue
  216. }
  217. oid, err := strconv.ParseInt(string(msg.Key), 10, 64)
  218. if err != nil {
  219. continue
  220. }
  221. _rpChs[oid%int64(s.c.Job.Proc)] <- msg
  222. }
  223. }
  224. // StatMsg stat msg.
  225. type StatMsg struct {
  226. Type string `json:"type,omitempty"`
  227. ID int64 `json:"id,omitempty"`
  228. Count int `json:"count,omitempty"`
  229. Oid int64 `json:"origin_id,omitempty"`
  230. DislikeCount int `json:"dislike_count,omitempty"`
  231. Timestamp int64 `json:"timestamp,omitempty"`
  232. Mid int64 `json:"mid,omitempty"`
  233. }
  234. func (s *Service) consumelikeproc(i int) {
  235. defer s.waiter.Done()
  236. for {
  237. msg, ok := <-_likeChs[i]
  238. if !ok {
  239. log.Info("consumeproc exit")
  240. return
  241. }
  242. cmsg := &StatMsg{}
  243. if err := json.Unmarshal(msg.Value, cmsg); err != nil {
  244. log.Error("json.Unmarshal() error(%v)", err)
  245. continue
  246. }
  247. if cmsg.Type != "reply" {
  248. continue
  249. }
  250. s.setLike(context.Background(), cmsg)
  251. msg.Commit()
  252. log.Info("consumer topic:%s, partitionId:%d, offset:%d, Key:%s, Value:%s", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value)
  253. }
  254. }
  255. func (s *Service) consumeproc(i int) {
  256. defer s.waiter.Done()
  257. for {
  258. msg, ok := <-_rpChs[i]
  259. if !ok {
  260. log.Info("consumeproc exit")
  261. return
  262. }
  263. cmsg := &consumerMsg{}
  264. if err := json.Unmarshal(msg.Value, cmsg); err != nil {
  265. log.Error("json.Unmarshal() error(%v)", err)
  266. continue
  267. }
  268. switch cmsg.Action {
  269. case "add":
  270. s.actionAdd(context.Background(), cmsg)
  271. case "add_top":
  272. s.addTopCache(context.Background(), cmsg)
  273. case "rpt":
  274. s.actionRpt(context.Background(), cmsg)
  275. case "act":
  276. //s.actionAct(context.Background(), cmsg)
  277. s.recAct(context.Background(), cmsg)
  278. case "re_idx":
  279. s.actionRecoverIndex(context.Background(), cmsg)
  280. case "idx_floor":
  281. s.acionRecoverFloorIdx(context.Background(), cmsg)
  282. case "re_rt_idx":
  283. s.actionRecoverRootIndex(context.Background(), cmsg)
  284. case "idx_dialog":
  285. s.actionRecoverDialog(context.Background(), cmsg)
  286. case "fix_dialog":
  287. s.actionRecoverFixDialog(context.Background(), cmsg)
  288. case "re_act":
  289. // s.actionRecoverAction(context.Background(),cmsg)
  290. case "up":
  291. s.actionUp(context.Background(), cmsg)
  292. case "admin":
  293. s.actionAdmin(context.Background(), cmsg)
  294. case "spam":
  295. s.addRecReply(context.Background(), cmsg)
  296. s.addDailyReply(context.Background(), cmsg)
  297. case "folder":
  298. s.folderHanlder(context.Background(), cmsg)
  299. default:
  300. log.Error("invalid action %s, cmsg is %v", cmsg.Action, cmsg)
  301. }
  302. msg.Commit()
  303. log.Info("consumer topic:%s, partitionId:%d, offset:%d, Key:%s, Value:%s", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value)
  304. }
  305. }
  306. // TypeToAlias map type to alias
  307. func (s *Service) TypeToAlias(t int32) (alias string, exists bool) {
  308. alias, exists = s.typeMapping[t]
  309. return
  310. }
  311. // AliasToType map alias to type
  312. func (s *Service) AliasToType(alias string) (t int32, exists bool) {
  313. t, exists = s.aliasMapping[alias]
  314. return
  315. }
  316. func (s *Service) mappingproc() {
  317. for {
  318. if business, err := s.ListBusiness(context.Background()); err != nil {
  319. log.Error("s.ListBusiness error(%v)", err)
  320. } else {
  321. for _, b := range business {
  322. s.typeMapping[b.Type] = b.Alias
  323. s.aliasMapping[b.Alias] = b.Type
  324. }
  325. }
  326. time.Sleep(time.Duration(time.Minute * 5))
  327. }
  328. }
  329. // Close close service
  330. func (s *Service) Close() error {
  331. return s.dataConsumer.Close()
  332. }
  333. // Wait wait all chan close
  334. func (s *Service) Wait() {
  335. s.waiter.Wait()
  336. }
  337. // Ping check service health
  338. func (s *Service) Ping(c context.Context) (err error) {
  339. return s.dao.Ping(c)
  340. }