lifecycle.go 1.2 KB

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