Skip to content

Commit

Permalink
refactor: use pkg/service
Browse files Browse the repository at this point in the history
refactor(validator): use pkg/service
refactor(advancer): use pkg/service
refactor(evm-reader): use pkg/service
  • Loading branch information
mpolitzer committed Dec 3, 2024
1 parent 92aa2dc commit 5db56d5
Show file tree
Hide file tree
Showing 36 changed files with 713 additions and 940 deletions.
114 changes: 26 additions & 88 deletions cmd/cartesi-rollups-advancer/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,104 +4,42 @@
package root

import (
"context"
"fmt"
"log/slog"
"net/http"
"os/signal"
"syscall"

"github.com/cartesi/rollups-node/internal/advancer"
"github.com/cartesi/rollups-node/internal/advancer/config"
"github.com/cartesi/rollups-node/internal/advancer/machines"
"github.com/cartesi/rollups-node/internal/inspect"
"github.com/cartesi/rollups-node/internal/repository"
"github.com/cartesi/rollups-node/internal/services"
"github.com/cartesi/rollups-node/internal/services/startup"

"github.com/cartesi/rollups-node/pkg/service"
"github.com/spf13/cobra"
)

const CMD_NAME = "advancer"

var (
buildVersion = "devel"
Cmd = &cobra.Command{
Use: CMD_NAME,
Short: "Runs the Advancer",
Long: "Runs the Advancer in standalone mode",
RunE: run,
buildVersion = "devel"
advancerService = advancer.Service{}
createInfo = advancer.CreateInfo{
CreateInfo: service.CreateInfo{
Name: "advancer",
ProcOwner: true,
EnableSignalHandling: true,
TelemetryCreate: true,
TelemetryAddress: ":10001",
Impl: &advancerService,
},
}
)

func getDatabase(ctx context.Context, endpoint string) (*repository.Database, error) {
database, err := repository.Connect(ctx, endpoint)
if err != nil {
return nil, fmt.Errorf("failed to connect to the database: %w", err)
}

return database, nil
var Cmd = &cobra.Command{
Use: createInfo.Name,
Short: "Runs " + createInfo.Name,
Long: "Runs " + createInfo.Name + " in standalone mode",
Run: run,
}

func healthcheckHandler(w http.ResponseWriter, r *http.Request) {
slog.Debug("Advancer received a healthcheck request")
w.WriteHeader(http.StatusOK)
func init() {
createInfo.LoadEnv()
Cmd.Flags().Var(&createInfo.LogLevel,
"log-level",
"log level: debug, info, warn or error")
}

func run(cmd *cobra.Command, args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

c := config.GetAdvancerConfig()
startup.ConfigLogs(c.LogLevel, c.LogPrettyEnabled)

slog.Info("Starting the Cartesi Rollups Node Advancer", "version", buildVersion, "config", c)

database, err := getDatabase(ctx, c.PostgresEndpoint.Value)
if err != nil {
return err
}
defer database.Close()

repo := &repository.MachineRepository{Database: database}

machines, err := machines.Load(ctx, repo, c.MachineServerVerbosity)
if err != nil {
return fmt.Errorf("failed to load the machines: %w", err)
}
defer machines.Close()

inspector, err := inspect.New(machines)
if err != nil {
return fmt.Errorf("failed to create the inspector: %w", err)
}

advancer, err := advancer.New(machines, repo)
if err != nil {
return fmt.Errorf("failed to create the advancer: %w", err)
}

poller, err := advancer.Poller(c.AdvancerPollingInterval)
if err != nil {
return fmt.Errorf("failed to create the advancer service: %w", err)
}

serveMux := http.NewServeMux()
serveMux.Handle("/healthz", http.HandlerFunc(healthcheckHandler))
serveMux.Handle("/inspect/{dapp}", http.Handler(inspector))
serveMux.Handle("/inspect/{dapp}/{payload}", http.Handler(inspector))

httpServer := &http.Server{
Addr: fmt.Sprintf("%v:%v", c.HttpAddress, c.HttpPort),
Handler: services.CorsMiddleware(serveMux),
}

go func() {
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("Could not listen on %s: %v\n", httpServer.Addr, err)
stop()
}
}()

return poller.Start(ctx)
func run(cmd *cobra.Command, args []string) {
cobra.CheckErr(advancer.Create(&createInfo, &advancerService))
advancerService.CreateDefaultHandlers("/" + advancerService.Name)
cobra.CheckErr(advancerService.Serve())
}
5 changes: 2 additions & 3 deletions cmd/cartesi-rollups-claimer/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ var (
createInfo = claimer.CreateInfo{
CreateInfo: service.CreateInfo{
Name: "claimer",
LogLevel: "info",
ProcOwner: true,
EnableSignalHandling: true,
TelemetryCreate: true,
Expand Down Expand Up @@ -46,8 +45,8 @@ func init() {
Cmd.Flags().DurationVar(&createInfo.PollInterval,
"poll-interval", createInfo.PollInterval,
"poll interval")
Cmd.Flags().StringVar(&createInfo.LogLevel,
"log-level", createInfo.LogLevel,
Cmd.Flags().Var(&createInfo.LogLevel,
"log-level",
"log level: debug, info, warn or error")
Cmd.Flags().BoolVar(&createInfo.EnableSubmission,
"claim-submission", createInfo.EnableSubmission,
Expand Down
157 changes: 39 additions & 118 deletions cmd/cartesi-rollups-evm-reader/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,161 +4,82 @@
package root

import (
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"time"

"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/internal/evmreader/service"
"github.com/cartesi/rollups-node/internal/repository"
"github.com/cartesi/rollups-node/internal/services/startup"
"github.com/cartesi/rollups-node/internal/evmreader"
"github.com/cartesi/rollups-node/pkg/service"

"github.com/spf13/cobra"
)

var (
// Should be overridden during the final release build with ldflags
// to contain the actual version number
buildVersion = "devel"
)

const (
CMD_NAME = "evm-reader"
buildVersion = "devel"
readerService = evmreader.Service{}
createInfo = evmreader.CreateInfo{
CreateInfo: service.CreateInfo{
Name: "evm-reader",
ProcOwner: true,
EnableSignalHandling: true,
TelemetryCreate: true,
TelemetryAddress: ":10000",
Impl: &readerService,
},
DefaultBlockString: "safe",
}
)

var Cmd = &cobra.Command{
Use: CMD_NAME,
Short: "Runs EVM Reader",
Long: `Runs EVM Reader in standalone mode`,
Use: createInfo.Name,
Short: "Runs " + createInfo.Name,
Long: "Runs " + createInfo.Name + " in standalone mode",
Run: run,
}
var (
defaultBlock string
postgresEndpoint string
blockchainHttpEndpoint string
blockchainWsEndpoint string
inputBoxAddress string
inputBoxDeploymentBlockNumber uint64
verbose bool
)

func init() {
createInfo.LoadEnv()

Cmd.Flags().StringVarP(&defaultBlock,
"default-block",
"d",
"",
Cmd.Flags().StringVarP(&createInfo.DefaultBlockString,
"default-block", "d", createInfo.DefaultBlockString,
`Default block to be used when fetching new blocks.
One of 'latest', 'safe', 'pending', 'finalized'`)

Cmd.Flags().StringVarP(&postgresEndpoint,
Cmd.Flags().StringVarP(&createInfo.PostgresEndpoint.Value,
"postgres-endpoint",
"p",
"",
createInfo.PostgresEndpoint.Value,
"Postgres endpoint")

Cmd.Flags().StringVarP(&blockchainHttpEndpoint,
Cmd.Flags().StringVarP(&createInfo.BlockchainHttpEndpoint.Value,
"blockchain-http-endpoint",
"b",
"",
createInfo.BlockchainHttpEndpoint.Value,
"Blockchain HTTP Endpoint")

Cmd.Flags().StringVarP(&blockchainWsEndpoint,
Cmd.Flags().StringVarP(&createInfo.BlockchainWsEndpoint.Value,
"blockchain-ws-endpoint",
"w",
"",
createInfo.BlockchainWsEndpoint.Value,
"Blockchain WS Endpoint")

Cmd.Flags().StringVarP(&inputBoxAddress,
"inputbox-address",
"i",
"",
"Input Box contract address")
// Cmd.Flags().StringVarP(&inputBoxAddress,
// "inputbox-address",
// "i",
// "",
// "Input Box contract address")

Cmd.Flags().Uint64VarP(&inputBoxDeploymentBlockNumber,
Cmd.Flags().Uint64VarP(&createInfo.InputBoxDeploymentBlock,
"inputbox-block-number",
"n",
0,
"Input Box deployment block number")

Cmd.Flags().BoolVarP(&verbose,
"verbose",
"v",
false,
"enable verbose logging")
Cmd.Flags().Var(&createInfo.LogLevel,
"log-level",
"log level: debug, info, warn or error")
}

func run(cmd *cobra.Command, args []string) {
startTime := time.Now()

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

c := config.FromEnv()

// Override configs
if verbose {
c.LogLevel = slog.LevelDebug
}
if postgresEndpoint != "" {
c.PostgresEndpoint = config.Redacted[string]{Value: postgresEndpoint}
}
if blockchainHttpEndpoint != "" {
c.BlockchainHttpEndpoint = config.Redacted[string]{Value: blockchainHttpEndpoint}
}
if blockchainWsEndpoint != "" {
c.BlockchainWsEndpoint = config.Redacted[string]{Value: blockchainWsEndpoint}
}
if defaultBlock != "" {
evmReaderDefaultBlock, err := config.ToDefaultBlockFromString(defaultBlock)
cobra.CheckErr(err)
c.EvmReaderDefaultBlock = evmReaderDefaultBlock
}

// setup log
startup.ConfigLogs(c.LogLevel, c.LogPrettyEnabled)

slog.Info("Starting the Cartesi Rollups Node EVM Reader", "version", buildVersion, "config", c)

database, err := repository.Connect(ctx, c.PostgresEndpoint.Value)
if err != nil {
slog.Error("EVM Reader couldn't connect to the database", "error", err)
os.Exit(1)
}
defer database.Close()

_, err = startup.SetupNodePersistentConfig(ctx, database, c)
if err != nil {
slog.Error("EVM Reader couldn't connect to the database", "error", err)
os.Exit(1)
}

// create EVM Reader Service
service := service.NewEvmReaderService(
c.BlockchainHttpEndpoint.Value,
c.BlockchainWsEndpoint.Value,
database,
c.EvmReaderRetryPolicyMaxRetries,
c.EvmReaderRetryPolicyMaxDelay,
)

// logs startup time
ready := make(chan struct{}, 1)
go func() {
select {
case <-ready:
duration := time.Since(startTime)
slog.Info("EVM Reader is ready", "after", duration)
case <-ctx.Done():
}
}()

// start service
if err := service.Start(ctx, ready); err != nil {
slog.Error("EVM Reader exited with an error", "error", err)
os.Exit(1)
}
cobra.CheckErr(evmreader.Create(&createInfo, &readerService))
readerService.CreateDefaultHandlers("/" + readerService.Name)
cobra.CheckErr(readerService.Start(nil, ready))
}
11 changes: 0 additions & 11 deletions cmd/cartesi-rollups-node/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/cartesi/rollups-node/internal/config"
"github.com/cartesi/rollups-node/internal/node"
"github.com/cartesi/rollups-node/internal/repository"
"github.com/cartesi/rollups-node/internal/services/startup"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -53,23 +52,13 @@ func run(cmd *cobra.Command, args []string) error {
}
}

// setup log
startup.ConfigLogs(cfg.LogLevel, cfg.LogPrettyEnabled)
slog.Info("Starting the Cartesi Rollups Node", "version", buildVersion, "config", cfg)

database, err := repository.Connect(ctx, cfg.PostgresEndpoint.Value)
if err != nil {
slog.Error("Node couldn't connect to the database", "error", err)
os.Exit(1)
}
defer database.Close()

_, err = startup.SetupNodePersistentConfig(ctx, database, cfg)
if err != nil {
slog.Error("Node exited with an error", "error", err)
os.Exit(1)
}

// create the node supervisor
supervisor, err := node.Setup(ctx, cfg, database)
if err != nil {
Expand Down
Loading

0 comments on commit 5db56d5

Please sign in to comment.