Skip to content

Commit

Permalink
Add a NewEngine function to create a new instance of the Engine struct
Browse files Browse the repository at this point in the history
  • Loading branch information
mostafa committed Oct 15, 2023
1 parent 91998ea commit f1c70bf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 31 deletions.
39 changes: 18 additions & 21 deletions network/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,8 @@ import (
"github.com/rs/zerolog"
)

type Option struct {
EnableTicker bool
}

type Action int

const (
None Action = iota
Close
Shutdown
)

type TCPSocketOpt int

const (
TCPNoDelay TCPSocketOpt = iota
TCPDelay
)

// Engine is the network engine.
// TODO: Move this to the Server struct.
type Engine struct {
listener net.Listener
host string
Expand All @@ -41,25 +24,39 @@ type Engine struct {
mu *sync.RWMutex
}

// CountConnections returns the current number of connections.
func (engine *Engine) CountConnections() int {
engine.mu.RLock()
defer engine.mu.RUnlock()
return int(engine.connections)
}

// Stop stops the engine.
func (engine *Engine) Stop(ctx context.Context) error {
_, cancel := context.WithDeadline(ctx, time.Now().Add(config.DefaultEngineStopTimeout))
defer cancel()

var err error
engine.running.Store(false)
if engine.listener != nil {
if err := engine.listener.Close(); err != nil {
if err = engine.listener.Close(); err != nil {
engine.logger.Error().Err(err).Msg("Failed to close listener")
}
} else {
engine.logger.Error().Msg("Listener is not initialized")
}
engine.stopServer <- struct{}{}
close(engine.stopServer)
return nil
return err
}

// NewEngine creates a new engine.
func NewEngine(logger zerolog.Logger) Engine {
return Engine{
connections: 0,
logger: logger,
running: &atomic.Bool{},
stopServer: make(chan struct{}),
mu: &sync.RWMutex{},
}
}
23 changes: 13 additions & 10 deletions network/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"os"
"strconv"
"sync"
"sync/atomic"
"time"

v1 "github.com/gatewayd-io/gatewayd-plugin-sdk/plugin/v1"
Expand All @@ -21,6 +20,18 @@ import (
"go.opentelemetry.io/otel/attribute"
)

type Option struct {
EnableTicker bool
}

type Action int

const (
None Action = iota
Close
Shutdown
)

type Server struct {
engine Engine
proxy IProxy
Expand Down Expand Up @@ -382,15 +393,6 @@ func (s *Server) Run() *gerr.GatewayDError {
}
}

// Start the server.
s.engine = Engine{
connections: 0,
logger: s.logger,
stopServer: make(chan struct{}),
mu: &sync.RWMutex{},
running: &atomic.Bool{},
}

if action := s.OnBoot(s.engine); action != None {
return nil
}
Expand Down Expand Up @@ -564,6 +566,7 @@ func NewServer(
pluginRegistry: pluginRegistry,
pluginTimeout: pluginTimeout,
mu: &sync.RWMutex{},
engine: NewEngine(logger),
}

// Try to resolve the address and log an error if it can't be resolved.
Expand Down

0 comments on commit f1c70bf

Please sign in to comment.