callback.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package service
  2. import (
  3. "context"
  4. "sort"
  5. "time"
  6. "go-common/app/admin/main/workflow/model"
  7. "go-common/app/admin/main/workflow/model/param"
  8. "go-common/library/log"
  9. "github.com/pkg/errors"
  10. )
  11. // AddOrUpCallback will add or update a callback
  12. func (s *Service) AddOrUpCallback(c context.Context, cbp *param.AddCallbackParam) (cbID int32, err error) {
  13. cb := &model.Callback{}
  14. if err = s.dao.ORM.Model(cb).
  15. Where(&model.Callback{Business: cbp.Business}).
  16. Assign(&model.Callback{
  17. Business: cbp.Business,
  18. URL: cbp.URL,
  19. IsSobot: cbp.IsSobot,
  20. State: cbp.State,
  21. ExternalAPI: cbp.ExternalAPI,
  22. SourceAPI: cbp.SourceAPI,
  23. }).
  24. FirstOrCreate(cb).Error; err != nil {
  25. log.Error("Failed to create a callback(%+v): %v", cb, err)
  26. return
  27. }
  28. cbID = cb.CbID
  29. // load callbacks from datebase in cache
  30. go s.loadCallbacks()
  31. return
  32. }
  33. // ListCallback will list all enabled callbacks
  34. func (s *Service) ListCallback(c context.Context) (cbList model.CallbackSlice, err error) {
  35. for _, cb := range s.callbackCache {
  36. cbList = append(cbList, cb)
  37. }
  38. sort.Slice(cbList, func(i, j int) bool {
  39. return cbList[i].Business > cbList[j].Business
  40. })
  41. return
  42. }
  43. // SendCallbackRetry will try to send callback with specified attempts
  44. func (s *Service) SendCallbackRetry(c context.Context, cb *model.Callback, payload *model.Payload) (err error) {
  45. attempts := 3
  46. for i := 0; i < attempts; i++ {
  47. err = s.dao.SendCallback(c, cb, payload)
  48. if err == nil {
  49. return
  50. }
  51. if i >= (attempts - 1) {
  52. break
  53. }
  54. time.Sleep(time.Second * 1)
  55. }
  56. return errors.Wrapf(err, "after %d attempts", attempts)
  57. }
  58. // SetExtAPI .
  59. func (s *Service) SetExtAPI(ctx context.Context, ea *param.BusAttrExtAPI) (err error) {
  60. if err = s.dao.ORM.Table("workflow_callback").Where("business = ?", ea.Bid).Update("external_api", ea.ExternalAPI).Error; err != nil {
  61. log.Error("Failed to set external_api field where bid = %d : %v", ea.Bid, err)
  62. }
  63. return
  64. }