lifecycle.go 1.2 KB

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