lifecycle.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package adapter
  2. import E "github.com/sagernet/sing/common/exceptions"
  3. type StartStage uint8
  4. const (
  5. StartStateInitialize StartStage = iota
  6. StartStateStart
  7. StartStatePostStart
  8. StartStateStarted
  9. )
  10. var ListStartStages = []StartStage{
  11. StartStateInitialize,
  12. StartStateStart,
  13. StartStatePostStart,
  14. StartStateStarted,
  15. }
  16. func (s StartStage) String() string {
  17. switch s {
  18. case StartStateInitialize:
  19. return "initialize"
  20. case StartStateStart:
  21. return "start"
  22. case StartStatePostStart:
  23. return "post-start"
  24. case StartStateStarted:
  25. return "finish-start"
  26. default:
  27. panic("unknown stage")
  28. }
  29. }
  30. type Lifecycle interface {
  31. Start(stage StartStage) error
  32. Close() error
  33. }
  34. type LifecycleService interface {
  35. Name() string
  36. Lifecycle
  37. }
  38. func Start(stage StartStage, services ...Lifecycle) error {
  39. for _, service := range services {
  40. err := service.Start(stage)
  41. if err != nil {
  42. return err
  43. }
  44. }
  45. return nil
  46. }
  47. func StartNamed(stage StartStage, services []LifecycleService) error {
  48. for _, service := range services {
  49. err := service.Start(stage)
  50. if err != nil {
  51. return E.Cause(err, stage.String(), " ", service.Name())
  52. }
  53. }
  54. return nil
  55. }