You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
1.7 KiB

  1. package lucifer3
  2. import (
  3. "fmt"
  4. "sync/atomic"
  5. )
  6. type Service interface {
  7. Active() bool
  8. ServiceID() ServiceID
  9. Handle(bus *EventBus, event Event, sender ServiceID)
  10. }
  11. type ServiceID struct {
  12. Kind ServiceKind
  13. ID int64
  14. Name string
  15. }
  16. func (s *ServiceID) String() string {
  17. if s == nil {
  18. return "BROADCAST"
  19. }
  20. if s.Kind == SKNotService {
  21. return "EXTERNAL"
  22. }
  23. if s.Name != "" {
  24. return s.Name
  25. } else {
  26. return fmt.Sprintf("%s[%d]", s.Kind.String(), s.ID)
  27. }
  28. }
  29. type ServiceCommon struct {
  30. serviceID ServiceID
  31. inactive uint32
  32. }
  33. func (s *ServiceCommon) Active() bool {
  34. return atomic.LoadUint32(&s.inactive) == 0
  35. }
  36. func (s *ServiceCommon) markInactive() {
  37. atomic.StoreUint32(&s.inactive, 1)
  38. }
  39. func (s *ServiceCommon) ServiceID() ServiceID {
  40. return s.serviceID
  41. }
  42. type ServiceKind int
  43. func (s ServiceKind) String() string {
  44. switch s {
  45. case SKSingleton:
  46. return "Singleton"
  47. case SKStorage:
  48. return "Storage"
  49. case SKDeviceHub:
  50. return "DeviceHub"
  51. case SKEffect:
  52. return "Effect"
  53. case SKCallback:
  54. return "Callback"
  55. case SKNotService:
  56. return "NotService"
  57. default:
  58. return "???"
  59. }
  60. }
  61. const (
  62. SKNotService ServiceKind = iota
  63. SKSingleton
  64. SKStorage
  65. SKDeviceHub
  66. SKEffect
  67. SKCallback
  68. )
  69. type callbackService struct {
  70. ServiceCommon
  71. cb func(event Event, sender ServiceID) bool
  72. }
  73. func (c *callbackService) Handle(_ *EventBus, event Event, sender ServiceID) {
  74. if !c.cb(event, sender) {
  75. c.markInactive()
  76. }
  77. }
  78. var nextCallback int64 = 0
  79. func newCallbackService(cb func(event Event, sender ServiceID) bool) Service {
  80. return &callbackService{
  81. ServiceCommon: ServiceCommon{
  82. serviceID: ServiceID{
  83. Kind: SKCallback,
  84. ID: atomic.AddInt64(&nextCallback, 1),
  85. },
  86. inactive: 0,
  87. },
  88. cb: cb,
  89. }
  90. }