saga.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package saga
  2. import (
  3. "git.sxidc.com/service-supports/dapr_api/state"
  4. "sync"
  5. "time"
  6. )
  7. var sagaInstance *Saga
  8. var sagaInstanceMutex sync.Mutex
  9. type Saga struct {
  10. stateAPI *state.API
  11. stateStoreName string
  12. name string
  13. orchestrators []*Orchestrator
  14. }
  15. func Init(stateAPI *state.API, stateStoreName string, sagaName string) {
  16. sagaInstanceMutex.Lock()
  17. defer sagaInstanceMutex.Unlock()
  18. if sagaInstance != nil {
  19. return
  20. }
  21. sagaInstance = new(Saga)
  22. sagaInstance.stateAPI = stateAPI
  23. sagaInstance.stateStoreName = stateStoreName
  24. sagaInstance.name = sagaName
  25. sagaInstance.orchestrators = make([]*Orchestrator, 0)
  26. }
  27. func Destroy() {
  28. sagaInstanceMutex.Lock()
  29. defer sagaInstanceMutex.Unlock()
  30. if sagaInstance == nil {
  31. return
  32. }
  33. for _, orchestrator := range sagaInstance.orchestrators {
  34. orchestrator.stop()
  35. }
  36. sagaInstance.orchestrators = nil
  37. sagaInstance.name = ""
  38. sagaInstance.stateStoreName = ""
  39. sagaInstance.stateAPI = nil
  40. sagaInstance = nil
  41. }
  42. func GetInstance() *Saga {
  43. return sagaInstance
  44. }
  45. func (s *Saga) BuildOrchestrator(orchestratorName string, rollbackRetryPeriodSec time.Duration) *Orchestrator {
  46. sagaInstanceMutex.Lock()
  47. defer sagaInstanceMutex.Unlock()
  48. orchestrator := &Orchestrator{
  49. stateAPI: s.stateAPI,
  50. stateStoreName: s.stateStoreName,
  51. sagaName: s.name,
  52. name: orchestratorName,
  53. rollbackRetryPeriodSec: rollbackRetryPeriodSec,
  54. }
  55. sagaInstance.orchestrators = append(sagaInstance.orchestrators, orchestrator)
  56. return orchestrator
  57. }
  58. func (s *Saga) GetOrchestratorNeedRollback() ([]OrchestratorState, error) {
  59. return getSagaOrchestratorStates(s.stateAPI, s.stateStoreName, s.name)
  60. }