Files
kalzu-value-store/server/lifecycle.go
ryyst a5ea869b28 refactor: extract core server package with handlers, routes, and lifecycle
Created server package with:
- server.go: Server struct and core methods
- handlers.go: HTTP handlers for health, KV operations, cluster management
- routes.go: HTTP route setup
- lifecycle.go: Server startup/shutdown logic

This moves ~400 lines of server-related code from main.go to dedicated
server package for better organization.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-20 11:02:44 +03:00

94 lines
2.0 KiB
Go

package server
import (
"context"
"fmt"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
// Start the server and initialize all services
func (s *Server) Start() error {
router := s.setupRoutes()
addr := fmt.Sprintf("%s:%d", s.config.BindAddress, s.config.Port)
s.httpServer = &http.Server{
Addr: addr,
Handler: router,
}
s.logger.WithFields(logrus.Fields{
"node_id": s.config.NodeID,
"address": addr,
}).Info("Starting KVS server")
// Start gossip and sync routines
s.startBackgroundTasks()
// Try to join cluster if seed nodes are configured and clustering is enabled
if s.config.ClusteringEnabled && len(s.config.SeedNodes) > 0 {
go s.bootstrap()
}
return s.httpServer.ListenAndServe()
}
// Stop the server gracefully
func (s *Server) Stop() error {
s.logger.Info("Shutting down KVS server")
// Stop cluster services
s.gossipService.Stop()
s.syncService.Stop()
// Close storage services
if s.storageService != nil {
s.storageService.Close()
}
s.cancel()
s.wg.Wait()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := s.httpServer.Shutdown(ctx); err != nil {
s.logger.WithError(err).Error("HTTP server shutdown error")
}
if err := s.db.Close(); err != nil {
s.logger.WithError(err).Error("BadgerDB close error")
}
return nil
}
// startBackgroundTasks initializes and starts cluster services
func (s *Server) startBackgroundTasks() {
// Start cluster services
s.gossipService.Start()
s.syncService.Start()
}
// bootstrap joins cluster using seed nodes via bootstrap service
func (s *Server) bootstrap() {
if len(s.config.SeedNodes) == 0 {
s.logger.Info("No seed nodes configured, running as standalone")
return
}
s.logger.Info("Starting bootstrap process")
s.setMode("syncing")
// Use bootstrap service to join cluster
if err := s.bootstrapService.JoinCluster(); err != nil {
s.logger.WithError(err).Error("Failed to join cluster")
s.setMode("normal")
return
}
s.setMode("normal")
s.logger.Info("Successfully joined cluster")
}