Skip to content

Commit

Permalink
🔨 Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
nagdahimanshu committed Feb 26, 2024
1 parent 957baa4 commit 0b938dc
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 48 deletions.
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ APP_NAME = faultdetector
GREEN = \033[1;32m
BLUE = \033[1;34m
COLOR_END = \033[0;39m
CONFIG_PATH = $(realpath $(config))

build: # Builds the application and create a binary at ./bin/
@echo "$(BLUE)» Building fault detector application binary... $(COLOR_END)"
Expand Down Expand Up @@ -61,9 +62,9 @@ docker-run: # Runs docker image, use `make docker-run config={PATH_TO_CONFIG_FIL
ifdef config
@echo "$(BLUE) Running docker image...$(COLOR_END)"
ifdef slack_access_token
@docker run --name $(APP_NAME) -p 8080:8080 -d -v $(config):/home/onchain/faultdetector/config.yaml -t -e SLACK_ACCESS_TOKEN_KEY=$(slack_access_token) $(APP_NAME)
@docker run --name $(APP_NAME) -p 8080:8080 -d -v $(CONFIG_PATH):/home/onchain/faultdetector/config.yaml -t -e SLACK_ACCESS_TOKEN_KEY=$(slack_access_token) $(APP_NAME)
else
@docker run --name $(APP_NAME) -p 8080:8080 -d -v $(config):/home/onchain/faultdetector/config.yaml -t $(APP_NAME)
@docker run --name $(APP_NAME) -p 8080:8080 -d -v $(CONFIG_PATH):/home/onchain/faultdetector/config.yaml -t $(APP_NAME)
endif
else
@echo "$(BLUE) Running docker image...$(COLOR_END)"
Expand Down
2 changes: 1 addition & 1 deletion cmd/faultdetector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func (app *App) Start() {
app.wg.Add(1)
go app.faultDetector.Start()

app.apiServer.AddHandler(app.faultDetector, app.config.Api.RegisterVersions)
app.apiServer.AddHandler(app.faultDetector, app.config.Api.RegisterVersions, app.config.Api.BasePath)
app.wg.Add(1)
go app.apiServer.Start()

Expand Down
13 changes: 5 additions & 8 deletions pkg/api/handlers/v1/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,13 @@ import (
)

type statusResponse struct {
Status string `json:"status"`
Ok bool `json:"ok"`
}

// GetStatus is the handler for the 'GET /api/v1/status' endpoint.
func GetStatus(c *gin.Context, b bool) {
var s statusResponse
if b {
s.Status = "ok"
} else {
s.Status = "not"
func GetStatus(c *gin.Context, isFaultDetected bool) {
status := statusResponse{
Ok: !isFaultDetected,
}
c.IndentedJSON(http.StatusOK, s)
c.IndentedJSON(http.StatusOK, status)
}
21 changes: 0 additions & 21 deletions pkg/api/routes/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,3 @@ import (
func RegisterHandlers(logger log.Logger, router *gin.Engine) {
router.GET("/ping", handlers.GetPing)
}

// RegisterHandlersByGroup is responsible to register all the handlers for routes that are prefixed under a specified base path as a routerGroup.
func RegisterHandlersByGroup(logger log.Logger, routerGroup *gin.RouterGroup, versions []string) {
for _, version := range versions {
RegisterHandlersForVersion(logger, routerGroup, version)
}
}

// RegisterHandlersForVersion is responsible to register API version specific route handlers.
func RegisterHandlersForVersion(logger log.Logger, routerGroup *gin.RouterGroup, version string) {
// TODO should remove?
// group := routerGroup.Group(version)

// switch version {
// case "v1":
// group.GET("/status", v1.GetStatus)

// default:
// logger.Warningf("No routes and handlers defined for version %s. Please verify the API config.", version)
// }
}
15 changes: 3 additions & 12 deletions pkg/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,21 @@ type HTTPServer struct {
errorChan chan error
}

// TODO add comment
func (w *HTTPServer) AddHandler(fd *faultdetector.FaultDetector, versions []string) {
basePath := w.router.BasePath()
// AddHandler is responsible to register route handlers.
func (w *HTTPServer) AddHandler(fd *faultdetector.FaultDetector, versions []string, basePath string) {
baseGroup := w.router.Group(basePath)
for _, version := range versions {
group := baseGroup.Group(version)
switch version {
case "v1":
group.GET("/status", func(c *gin.Context) {
v1.GetStatus(c, fd.GetStatus())
v1.GetStatus(c, fd.IsFaultDetected())
})

default:
w.logger.Warningf("No routes and handlers defined for version %s. Please verify the API config.", version)
}
}

}

// TODO check register handler already called before start
Expand Down Expand Up @@ -96,13 +94,6 @@ func NewHTTPServer(ctx context.Context, logger log.Logger, wg *sync.WaitGroup, c

routes.RegisterHandlers(logger, router)

// TODO should remove
// Register handlers for routes following the base path
// basePath := config.Api.BasePath
// baseGroup := router.Group(basePath)
// logger.Debugf("Registering handlers for endpoints under path '%s'.", basePath)
// routes.RegisterHandlersByGroup(logger, baseGroup, config.Api.RegisterVersions)

host := config.Api.Server.Host
port := config.Api.Server.Port
addr := fmt.Sprintf("%s:%d", host, port)
Expand Down
18 changes: 14 additions & 4 deletions pkg/faultdetector/faultdetector.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ type FaultDetector struct {
oracleContractAccessor OracleAccessor
faultProofWindow uint64
currentOutputIndex uint64
diverged bool // TODO add mutex
diverged bool
ticker *time.Ticker
quitTickerChan chan struct{}
notification *notification.Notification
mutex *sync.RWMutex
}

type faultDetectorMetrics struct {
Expand Down Expand Up @@ -154,6 +155,7 @@ func NewFaultDetector(ctx context.Context, logger log.Logger, errorChan chan err
diverged: false,
metrics: metrics,
notification: notification,
mutex: new(sync.RWMutex),
}

return faultDetector, nil
Expand Down Expand Up @@ -245,7 +247,10 @@ func (fd *FaultDetector) checkFault() error {
outputBlockHeader.Hash(),
)
if calculatedOutputRoot != expectedOutputRoot {
fd.mutex.Lock()
fd.diverged = true
fd.mutex.Unlock()

fd.metrics.stateMismatch.Set(1)
finalizationTime := time.Unix(int64(outputBlockHeader.Time+fd.faultProofWindow), 0)

Expand All @@ -265,18 +270,23 @@ func (fd *FaultDetector) checkFault() error {
// Time taken to execute each batch in milliseconds.
elapsedTime := time.Since(startTime).Milliseconds()
fd.logger.Infof("Successfully checked current batch with index %d --> ok, time taken %dms.", fd.currentOutputIndex, elapsedTime)
fd.mutex.Lock()
fd.diverged = false
fd.mutex.Unlock()

fd.currentOutputIndex++
fd.metrics.stateMismatch.Set(0)
return nil
}

// TODO add comments
func (fd *FaultDetector) GetStatus() bool {
// IsFaultDetected returns status of the fault detector.
func (fd *FaultDetector) IsFaultDetected() bool {
fd.mutex.RLock()
defer fd.mutex.RUnlock()
return fd.diverged
}

// TODO add comments
// GetFaultDetector create [FaultDetector] instance from input values.
func GetFaultDetector(ctx context.Context, logger log.Logger, l1RpcApi *chain.ChainAPIClient, l2RpcApi *chain.ChainAPIClient, oracleContractAccessor OracleAccessor, faultProofWindow uint64, currentOutputIndex uint64, metrics *faultDetectorMetrics, notification *notification.Notification, diverged bool, wg *sync.WaitGroup, errorChan chan error) *FaultDetector {
return &FaultDetector{
ctx: ctx,
Expand Down

0 comments on commit 0b938dc

Please sign in to comment.