bugfix on service discovery

This commit is contained in:
Pierre
2026-02-02 00:02:39 +01:00
parent 9a60f0e231
commit 38643eb129
9 changed files with 360 additions and 31 deletions
+32 -7
View File
@@ -21,15 +21,22 @@ type ServiceInfo struct {
BaseUrl string `json:"baseUrl"`
Status string `json:"status"`
LastHeartbeat string `json:"lastHeartbeat"`
Role string `json:"role,omitempty"` // "leader", "follower", or empty (for non-meta-core services)
}
// RoleProvider interface for getting the current role
type RoleProvider interface {
Role() string
}
// Service handles service registration and discovery
type Service struct {
config *config.Config
servicesDir string
serviceFile string
info *ServiceInfo
mu sync.RWMutex
config *config.Config
servicesDir string
serviceFile string
info *ServiceInfo
roleProvider RoleProvider
mu sync.RWMutex
stopChan chan struct{}
wg sync.WaitGroup
@@ -46,6 +53,11 @@ func NewService(cfg *config.Config) *Service {
}
}
// SetRoleProvider sets the role provider for this service
func (s *Service) SetRoleProvider(rp RoleProvider) {
s.roleProvider = rp
}
// Start begins service registration and heartbeat
func (s *Service) Start() error {
log.Printf("[Discovery] Starting service discovery for %s", s.config.ServiceName)
@@ -95,13 +107,20 @@ func (s *Service) buildServiceInfo() *ServiceInfo {
baseUrl = fmt.Sprintf("http://%s:%d", ip, s.config.APIPort)
}
return &ServiceInfo{
info := &ServiceInfo{
Name: s.config.ServiceName,
Hostname: hostname,
BaseUrl: baseUrl,
Status: "running",
LastHeartbeat: time.Now().UTC().Format(time.RFC3339),
}
// Add role if role provider is set (e.g., for meta-core)
if s.roleProvider != nil {
info.Role = s.roleProvider.Role()
}
return info
}
// register writes service info to file
@@ -145,7 +164,7 @@ func (s *Service) heartbeatLoop() {
}
}
// heartbeat updates the last heartbeat timestamp
// heartbeat updates the last heartbeat timestamp and role
func (s *Service) heartbeat() {
s.mu.Lock()
defer s.mu.Unlock()
@@ -155,6 +174,12 @@ func (s *Service) heartbeat() {
}
s.info.LastHeartbeat = time.Now().UTC().Format(time.RFC3339)
// Update role in case it changed (e.g., leader election)
if s.roleProvider != nil {
s.info.Role = s.roleProvider.Role()
}
if err := s.writeServiceInfo(s.info); err != nil {
log.Printf("[Discovery] Failed to update heartbeat: %v", err)
}