status.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package status
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/opencode-ai/opencode/internal/pubsub"
  8. )
  9. type Level string
  10. const (
  11. LevelInfo Level = "info"
  12. LevelWarn Level = "warn"
  13. LevelError Level = "error"
  14. LevelDebug Level = "debug"
  15. )
  16. type StatusMessage struct {
  17. Level Level `json:"level"`
  18. Message string `json:"message"`
  19. Timestamp time.Time `json:"timestamp"`
  20. }
  21. const (
  22. EventStatusPublished pubsub.EventType = "status_published"
  23. )
  24. type Service interface {
  25. pubsub.Subscriber[StatusMessage]
  26. Info(message string)
  27. Warn(message string)
  28. Error(message string)
  29. Debug(message string)
  30. }
  31. type service struct {
  32. broker *pubsub.Broker[StatusMessage]
  33. mu sync.RWMutex
  34. }
  35. var globalStatusService *service
  36. func InitService() error {
  37. if globalStatusService != nil {
  38. return fmt.Errorf("status service already initialized")
  39. }
  40. broker := pubsub.NewBroker[StatusMessage]()
  41. globalStatusService = &service{
  42. broker: broker,
  43. }
  44. return nil
  45. }
  46. func GetService() Service {
  47. if globalStatusService == nil {
  48. panic("status service not initialized. Call status.InitService() at application startup.")
  49. }
  50. return globalStatusService
  51. }
  52. func (s *service) Info(message string) {
  53. s.publish(LevelInfo, message)
  54. }
  55. func (s *service) Warn(message string) {
  56. s.publish(LevelWarn, message)
  57. }
  58. func (s *service) Error(message string) {
  59. s.publish(LevelError, message)
  60. }
  61. func (s *service) Debug(message string) {
  62. s.publish(LevelDebug, message)
  63. }
  64. func (s *service) publish(level Level, messageText string) {
  65. statusMsg := StatusMessage{
  66. Level: level,
  67. Message: messageText,
  68. Timestamp: time.Now(),
  69. }
  70. s.broker.Publish(EventStatusPublished, statusMsg)
  71. }
  72. func (s *service) Subscribe(ctx context.Context) <-chan pubsub.Event[StatusMessage] {
  73. return s.broker.Subscribe(ctx)
  74. }
  75. func Info(message string) {
  76. GetService().Info(message)
  77. }
  78. func Warn(message string) {
  79. GetService().Warn(message)
  80. }
  81. func Error(message string) {
  82. GetService().Error(message)
  83. }
  84. func Debug(message string) {
  85. GetService().Debug(message)
  86. }
  87. func Subscribe(ctx context.Context) <-chan pubsub.Event[StatusMessage] {
  88. return GetService().Subscribe(ctx)
  89. }