static.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package static
  2. import (
  3. "context"
  4. "encoding/json"
  5. "strconv"
  6. "time"
  7. "go-common/app/interface/main/app-resource/conf"
  8. eggdao "go-common/app/interface/main/app-resource/dao/egg"
  9. "go-common/app/interface/main/app-resource/model"
  10. "go-common/app/interface/main/app-resource/model/static"
  11. "go-common/library/ecode"
  12. "go-common/library/log"
  13. farm "github.com/dgryski/go-farm"
  14. )
  15. const (
  16. _initVersion = "static_version"
  17. )
  18. var (
  19. _emptyStatics = []*static.Static{}
  20. )
  21. // Service static service.
  22. type Service struct {
  23. dao *eggdao.Dao
  24. tick time.Duration
  25. cache map[int8][]*static.Static
  26. staticPath string
  27. }
  28. // New new a static service.
  29. func New(c *conf.Config) (s *Service) {
  30. s = &Service{
  31. dao: eggdao.New(c),
  32. tick: time.Duration(c.Tick),
  33. cache: map[int8][]*static.Static{},
  34. staticPath: c.StaticJSONFile,
  35. }
  36. now := time.Now()
  37. s.loadCache(now)
  38. go s.loadCachepro()
  39. return
  40. }
  41. // Static return statics
  42. func (s *Service) Static(plat int8, build int, ver string, now time.Time) (res []*static.Static, version string, err error) {
  43. var (
  44. tmps = s.cache[plat]
  45. )
  46. for _, tmp := range tmps {
  47. if model.InvalidBuild(build, tmp.Build, tmp.Condition) {
  48. continue
  49. }
  50. res = append(res, tmp)
  51. }
  52. if len(res) == 0 {
  53. res = _emptyStatics
  54. }
  55. if version = s.hash(res); version == ver {
  56. err = ecode.NotModified
  57. res = nil
  58. }
  59. return
  60. }
  61. func (s *Service) hash(v []*static.Static) string {
  62. bs, err := json.Marshal(v)
  63. if err != nil {
  64. log.Error("json.Marshal error(%v)", err)
  65. return _initVersion
  66. }
  67. return strconv.FormatUint(farm.Hash64(bs), 10)
  68. }
  69. // loadCache update egg
  70. func (s *Service) loadCache(now time.Time) {
  71. tmp, err := s.dao.Egg(context.TODO(), now)
  72. if err != nil {
  73. log.Error("s.dao.Egg error(%v)", err)
  74. return
  75. }
  76. s.cache = tmp
  77. }
  78. func (s *Service) loadCachepro() {
  79. for {
  80. time.Sleep(s.tick)
  81. s.loadCache(time.Now())
  82. }
  83. }