gcx/backend/services/chain-indexer/cmd/server/main.go

79 lines
2.2 KiB
Go

package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/genex/chain-indexer/internal/indexer"
"github.com/genex/chain-indexer/internal/interface/http/handler"
"github.com/genex/chain-indexer/internal/interface/http/middleware"
)
func main() {
logger, _ := zap.NewProduction()
defer logger.Sync()
port := os.Getenv("PORT")
if port == "" {
port = "3009"
}
idx := indexer.NewIndexer(logger)
idx.Start()
r := gin.New()
r.Use(gin.Recovery())
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok", "service": "chain-indexer", "lastHeight": idx.GetLastHeight()})
})
r.GET("/health/ready", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ready"}) })
r.GET("/health/live", func(c *gin.Context) { c.JSON(200, gin.H{"status": "alive"}) })
api := r.Group("/api/v1/chain")
api.GET("/blocks", func(c *gin.Context) {
blocks := idx.GetRecentBlocks(20)
c.JSON(200, gin.H{"code": 0, "data": gin.H{"blocks": blocks, "lastHeight": idx.GetLastHeight()}})
})
api.GET("/status", func(c *gin.Context) {
c.JSON(200, gin.H{"code": 0, "data": gin.H{"lastHeight": idx.GetLastHeight(), "syncing": true}})
})
// Admin routes (require JWT + admin role)
adminChainHandler := handler.NewAdminChainHandler(idx)
admin := r.Group("/api/v1/admin/chain")
admin.Use(middleware.JWTAuth(), middleware.RequireAdmin())
{
admin.GET("/contracts", adminChainHandler.GetContracts)
admin.GET("/events", adminChainHandler.GetEvents)
admin.GET("/gas-monitor", adminChainHandler.GetGasMonitor)
admin.GET("/stats", adminChainHandler.GetChainStats)
}
server := &http.Server{Addr: ":" + port, Handler: r, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second}
go func() {
logger.Info("Chain Indexer starting", zap.String("port", port))
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal("Failed", zap.Error(err))
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
idx.Stop()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
server.Shutdown(ctx)
logger.Info("Chain Indexer stopped")
}