bingomanager.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package bingomanager
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "errors"
  6. "log"
  7. "math/rand"
  8. "time"
  9. gamelangBingopb "git.alfi.li/gamelang/protobuf/gamelang-bingo"
  10. "github.com/golang/protobuf/proto"
  11. "github.com/segmentio/kafka-go"
  12. )
  13. type BingoManager struct {
  14. bingos map[string]*gamelangBingopb.Bingo
  15. kafkaBroker []string
  16. kafkaR *kafka.Reader
  17. kafkaW *kafka.Writer
  18. }
  19. func NewBingoManager(kafkaBroker []string) *BingoManager {
  20. bm := BingoManager{kafkaBroker: kafkaBroker}
  21. bm.bingos = map[string]*gamelangBingopb.Bingo{}
  22. if len(kafkaBroker) > 0 {
  23. bm.kafkaBroker = kafkaBroker
  24. bm.InitKafka()
  25. }
  26. return &bm
  27. }
  28. // Create adds an entry into the user database
  29. func (bm *BingoManager) Create(inputBingo gamelangBingopb.Bingo) (gamelangBingopb.Bingo, error) {
  30. if _, exists := bm.bingos[inputBingo.GetName()]; exists {
  31. log.Println("bingo already exists", inputBingo.GetName())
  32. return gamelangBingopb.Bingo{}, errors.New("bingo already exists")
  33. }
  34. if bm.kafkaW != nil {
  35. newBingo := gamelangBingopb.Bingo{Id: inputBingo.GetId(), Name: inputBingo.GetName(), Textlist: inputBingo.GetTextlist(), Options: inputBingo.GetOptions()}
  36. newBingoBin, _ := proto.Marshal(&newBingo)
  37. if err := bm.kafkaW.WriteMessages(context.Background(), kafka.Message{Key: []byte("bingo:create"), Value: newBingoBin}); err != nil {
  38. log.Println("ERROR: cannot write to kafka\n", err.Error())
  39. return gamelangBingopb.Bingo{}, err
  40. }
  41. return newBingo, nil
  42. } else {
  43. bingo := gamelangBingopb.Bingo{Id: inputBingo.GetId(), Name: inputBingo.GetName(), Textlist: inputBingo.GetTextlist(), Options: inputBingo.GetOptions()}
  44. bm.bingos[inputBingo.Name] = &bingo
  45. return bingo, nil
  46. }
  47. }
  48. // Remove removes an entry from the user database
  49. func (bm *BingoManager) Remove(name string) error {
  50. if bm.kafkaW != nil {
  51. delBingo := bm.bingos[name]
  52. delBingoBin, _ := proto.Marshal(delBingo)
  53. if err := bm.kafkaW.WriteMessages(context.Background(), kafka.Message{Key: []byte("bingo:delete"), Value: delBingoBin}); err != nil {
  54. log.Fatal(err)
  55. } else {
  56. // print common key info
  57. log.Print("Delete is done")
  58. }
  59. } else {
  60. delete(bm.bingos, name)
  61. }
  62. return nil
  63. }
  64. func (bm *BingoManager) Get(name string) (gamelangBingopb.Bingo, error) {
  65. bingo, ok := bm.bingos[name]
  66. if !ok {
  67. return gamelangBingopb.Bingo{}, errors.New("Bingo not found")
  68. }
  69. return *bingo, nil
  70. }
  71. // List returns a list of all Users
  72. func (bm *BingoManager) List() []gamelangBingopb.Bingo {
  73. list := []gamelangBingopb.Bingo{}
  74. for _, bingoP := range bm.bingos {
  75. bingo := *bingoP
  76. list = append(list, bingo)
  77. }
  78. return list
  79. }
  80. // CheckField marks a field a marked
  81. // gets the name and the first field [0][0] from inputBingo
  82. func (bm *BingoManager) CheckField(inputBingo *gamelangBingopb.Bingo) error {
  83. bingo, ok := bm.bingos[inputBingo.GetName()]
  84. if !ok {
  85. return errors.New("cannot find bingo")
  86. }
  87. if bm.kafkaW != nil {
  88. inputBingoBin, _ := proto.Marshal(inputBingo)
  89. if err := bm.kafkaW.WriteMessages(context.Background(), kafka.Message{Key: []byte("bingo:check"), Value: inputBingoBin}); err != nil {
  90. log.Fatal(err)
  91. return err
  92. } else {
  93. // print common key info
  94. log.Print("check is done")
  95. return nil
  96. }
  97. } else {
  98. matrix := inputBingo.GetFields()
  99. for x, row := range matrix.GetRows() {
  100. for y, field := range row.Fields {
  101. if field != nil {
  102. bingo.Fields.Rows[x].Fields[y].Checked = true
  103. return nil
  104. }
  105. }
  106. }
  107. return errors.New("no field found")
  108. }
  109. }
  110. // ReceiveMessages handles kafka messages
  111. func (bm *BingoManager) ReceiveMessages(msg kafka.Message) {
  112. log.Println("bm receive: new msg", msg.Offset, string(msg.Key))
  113. switch string(msg.Key) {
  114. // uc - user create event
  115. case "bingo:create":
  116. newBingo := &gamelangBingopb.Bingo{}
  117. proto.Unmarshal(msg.Value, newBingo)
  118. bm.bingos[newBingo.Name] = newBingo
  119. log.Println("bm receive: bingo \"", newBingo.Name, "\" has been created")
  120. // ur - user remove event
  121. case "bingo:remove":
  122. delBingo := &gamelangBingopb.Bingo{}
  123. proto.Unmarshal(msg.Value, delBingo)
  124. name := delBingo.Name
  125. delete(bm.bingos, name)
  126. log.Println("bm receive: bingo \"", delBingo.Name, "\" has been deleted")
  127. case "bingo:check":
  128. checkBingo := &gamelangBingopb.Bingo{}
  129. err := proto.Unmarshal(msg.Value, checkBingo)
  130. bingo, ok := bm.bingos[checkBingo.GetName()]
  131. if !ok {
  132. log.Println("cannot find bingo")
  133. return
  134. }
  135. if err != nil {
  136. log.Println("cannot unmarshall bingo")
  137. return
  138. }
  139. matrix := checkBingo.GetFields()
  140. for x, row := range matrix.GetRows() {
  141. for y, field := range row.Fields {
  142. if field != nil {
  143. bingo.Fields.Rows[x].Fields[y].Checked = true
  144. return
  145. }
  146. }
  147. }
  148. log.Println("bm receive: field checked on \"", checkBingo.Name)
  149. default:
  150. log.Println("unknown type ", string(msg.Key))
  151. }
  152. }
  153. // InitKafka initializes the kafka reader and writer and starts the watch thread
  154. func (bm *BingoManager) InitKafka() error {
  155. bm.kafkaR = kafka.NewReader(kafka.ReaderConfig{
  156. Brokers: bm.kafkaBroker,
  157. Topic: "bingomanager",
  158. Partition: 0,
  159. MinBytes: 10e3, // 10KB
  160. MaxBytes: 10e6, // 10MB
  161. })
  162. bm.kafkaW = kafka.NewWriter(kafka.WriterConfig{
  163. Brokers: bm.kafkaBroker,
  164. Topic: "bingomanager",
  165. Balancer: &kafka.LeastBytes{},
  166. })
  167. go bm.pollKafka()
  168. return nil
  169. }
  170. func (bm *BingoManager) pollKafka() error {
  171. for {
  172. m, err := bm.kafkaR.ReadMessage(context.Background())
  173. if err != nil {
  174. log.Print(err)
  175. time.Sleep(time.Second)
  176. continue
  177. }
  178. bm.ReceiveMessages(m)
  179. }
  180. }
  181. func randomHex(n int) (string, error) {
  182. bytes := make([]byte, n)
  183. if _, err := rand.Read(bytes); err != nil {
  184. return "", err
  185. }
  186. return hex.EncodeToString(bytes), nil
  187. }