Skip to content

Commit

Permalink
Merge pull request #30 from spiral/accept_interface_into_providers
Browse files Browse the repository at this point in the history
Accept "Name" interface in the Providers
  • Loading branch information
rustatian authored Jul 21, 2020
2 parents 0d92166 + a6d033a commit 61c6dfc
Show file tree
Hide file tree
Showing 40 changed files with 607 additions and 265 deletions.
49 changes: 49 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
linters:
# please, do not use `enable-all`: it's deprecated and will be removed soon.
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
disable-all: true
enable:
- bodyclose
- depguard
- dogsled
- dupl
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
# - golint
- goprintffuncname
# - gosec
# - gosimple
- govet
- ineffassign
- interfacer
- misspell
- nakedret
- nolintlint
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
# - unused
- varcheck
- whitespace

# don't enable:
# - asciicheck
# - gochecknoglobals
# - gocognit
# - godot
# - godox
# - goerr113
# - maligned
# - nestif
# - prealloc
# - testpackage
# - wsl
11 changes: 4 additions & 7 deletions calculate_deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (c *Cascade) addEdges() error {

/* Add the dependencies (if) which this vertex needs to init
Information we know at this step is:
1. VertexId
1. vertexID
2. Vertex structure value (interface)
3. Provided type
4. Provided type String name
Expand Down Expand Up @@ -171,10 +171,7 @@ func (c *Cascade) addDependersDeps(vertexID string, vertex interface{}) error {

func (c *Cascade) addInitDeps(vertexID string, initMethod reflect.Method) error {
// S2 init args
initArgs, err := functionParameters(initMethod)
if err != nil {
return err
}
initArgs := functionParameters(initMethod)

// iterate over all function parameters
for _, initArg := range initArgs {
Expand All @@ -196,15 +193,15 @@ func (c *Cascade) addInitDeps(vertexID string, initMethod reflect.Method) error
}
tmpIsRef := isReference(initArg)
tmpValue := reflect.ValueOf(c.graph.Vertices[i].Iface)
err = c.graph.Vertices[i].AddProvider(removePointerAsterisk(initArg.String()), tmpValue, tmpIsRef, initArg.Kind())
err := c.graph.Vertices[i].AddProvider(removePointerAsterisk(initArg.String()), tmpValue, tmpIsRef, initArg.Kind())
if err != nil {
return err
}
}
}
}

err = c.graph.AddDep(vertexID, removePointerAsterisk(initArg.String()), structures.Init, isReference(initArg), initArg.Kind())
err := c.graph.AddDep(vertexID, removePointerAsterisk(initArg.String()), structures.Init, isReference(initArg), initArg.Kind())
if err != nil {
return err
}
Expand Down
43 changes: 23 additions & 20 deletions cascade.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package cascade
import (
"errors"
"net/http"

// pprof enabled in debug mode
_ "net/http/pprof"

"reflect"
"sync"
"time"
Expand Down Expand Up @@ -187,12 +190,12 @@ func (c *Cascade) Register(vertex interface{}) error {

ok := t.Implements(reflect.TypeOf((*Service)(nil)).Elem())
if !ok {
return typeNotImplementError
return errTypeNotImplementError
}

/* Depender the type
Information we know at this step is:
1. VertexId
1. vertexID
2. Vertex structure value (interface)
And we fill vertex with this information
*/
Expand All @@ -203,7 +206,7 @@ func (c *Cascade) Register(vertex interface{}) error {
order++
/* Add the types, which (if) current vertex provides
Information we know at this step is:
1. VertexId
1. vertexID
2. Vertex structure value (interface)
3. Provided type
4. Provided type String name
Expand Down Expand Up @@ -254,7 +257,7 @@ func (c *Cascade) Init() error {
return nil
}

func (c *Cascade) Serve() (error, <-chan *Result) {
func (c *Cascade) Serve() (<-chan *Result, error) {
c.rwMutex.Lock()
defer c.rwMutex.Unlock()
c.startMainThread()
Expand All @@ -264,8 +267,8 @@ func (c *Cascade) Serve() (error, <-chan *Result) {
for nCopy != nil {
err := c.configure(nCopy)
if err != nil {
c.logger.Error("backoff failed", zap.String("vertex id", nCopy.Vertex.Id), zap.Error(err))
return err, nil
c.logger.Error("backoff failed", zap.String("vertex id", nCopy.Vertex.ID), zap.Error(err))
return nil, err
}

nCopy = nCopy.Next
Expand All @@ -275,11 +278,11 @@ func (c *Cascade) Serve() (error, <-chan *Result) {
for nCopy != nil {
err := c.serve(nCopy)
if err != nil {
return err, nil
return nil, err
}
nCopy = nCopy.Next
}
return nil, c.userResultsCh
return c.userResultsCh, nil
}

func (c *Cascade) Stop() error {
Expand Down Expand Up @@ -319,18 +322,18 @@ func (c *Cascade) startMainThread() {
return
}

c.logger.Debug("processing error in the main thread", zap.String("vertex id", res.vertexId))
c.logger.Debug("processing error in the main thread", zap.String("vertex id", res.vertexID))
if c.checkLeafErrorTime(res) {
c.logger.Debug("error processing skipped because vertex already restartedTime by the root", zap.String("vertex id", res.vertexId))
c.logger.Debug("error processing skipped because vertex already restartedTime by the root", zap.String("vertex id", res.vertexID))
c.sendResultToUser(res)
c.rwMutex.Unlock()
continue
}

// get vertex from the graph
vertex := c.graph.GetVertex(res.vertexId)
vertex := c.graph.GetVertex(res.vertexID)
if vertex == nil {
c.logger.Error("failed to get vertex from the graph, vertex is nil", zap.String("vertex id from the handleErrorCh channel", res.vertexId))
c.logger.Error("failed to get vertex from the graph, vertex is nil", zap.String("vertex id from the handleErrorCh channel", res.vertexID))
c.userResultsCh <- &Result{
Error: FailedToGetTheVertex,
VertexID: "",
Expand All @@ -341,12 +344,12 @@ func (c *Cascade) startMainThread() {

// reset vertex and dependencies to the initial state
// NumOfDeps and Visited/Visiting
vertices := c.resetVertices(vertex)
vertices := c.graph.Reset(vertex)

// Topologically sort the graph
sorted := structures.TopologicalSort(vertices)
if sorted == nil {
c.logger.Error("sorted list should not be nil", zap.String("vertex id from the handleErrorCh channel", res.vertexId))
c.logger.Error("sorted list should not be nil", zap.String("vertex id from the handleErrorCh channel", res.vertexID))
c.userResultsCh <- &Result{
Error: FailedToSortTheGraph,
VertexID: "",
Expand Down Expand Up @@ -377,10 +380,10 @@ func (c *Cascade) startMainThread() {
for headCopy != nil {
berr := backoff.Retry(c.backoffInit(headCopy.Vertex), b)
if berr != nil {
c.logger.Error("backoff failed", zap.String("vertex id", headCopy.Vertex.Id), zap.Error(berr))
c.logger.Error("backoff failed", zap.String("vertex id", headCopy.Vertex.ID), zap.Error(berr))
c.userResultsCh <- &Result{
Error: ErrorDuringInit,
VertexID: headCopy.Vertex.Id,
VertexID: headCopy.Vertex.ID,
}
c.rwMutex.Unlock()
return
Expand All @@ -396,9 +399,9 @@ func (c *Cascade) startMainThread() {
if berr != nil {
c.userResultsCh <- &Result{
Error: ErrorDuringInit,
VertexID: headCopy.Vertex.Id,
VertexID: headCopy.Vertex.ID,
}
c.logger.Error("backoff failed", zap.String("vertex id", headCopy.Vertex.Id), zap.Error(berr))
c.logger.Error("backoff failed", zap.String("vertex id", headCopy.Vertex.ID), zap.Error(berr))
c.rwMutex.Unlock()
return
}
Expand All @@ -413,9 +416,9 @@ func (c *Cascade) startMainThread() {
if err != nil {
c.userResultsCh <- &Result{
Error: ErrorDuringServe,
VertexID: headCopy.Vertex.Id,
VertexID: headCopy.Vertex.ID,
}
c.logger.Error("fatal error during the serve in the main thread", zap.String("vertex id", headCopy.Vertex.Id), zap.Error(err))
c.logger.Error("fatal error during the serve in the main thread", zap.String("vertex id", headCopy.Vertex.ID), zap.Error(err))
c.rwMutex.Unlock()
return
}
Expand Down
15 changes: 11 additions & 4 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,37 @@ type result struct {
// error from the channel
err error
// unique vertex id
vertexId string
vertexID string
// signal to the vertex goroutine to exit
exit chan struct{}
// internal exit, used to notify main thread to release resources
internalExit bool
}

type (
// TODO namings
// used to gracefully stop and configure the plugins
Graceful interface {
// Configure is used when we need to make preparation and wait for all services till Serve
Configure() error
// Close frees resources allocated by the service
Close() error
}
// this is the main service interface with should implement every plugin
Service interface {
// Serve
Serve() chan error
// Stop
Stop() error
}

Container interface {
Serve() (error, <-chan *Result)
// Name of the service
Named interface {
Name() string
}

// internal container interface
container interface {
Serve() (<-chan *Result, error)
Stop() error
restart() error
Register(service interface{}) error
Expand Down
6 changes: 3 additions & 3 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ var ErrorDuringServe = Error{
Stack: debug.Stack(),
}

var typeNotImplementError = errors.New("type should implement Service interface")
var vertexAlreadyExists = func(name string) error { return fmt.Errorf("vertex `%s` already exists", name) }
var unknownErrorOccurred = errors.New("unknown error occurred during the function call")
var errTypeNotImplementError = errors.New("type should implement Service interface")
var errVertexAlreadyExists = func(name string) error { return fmt.Errorf("vertex `%s` already exists", name) }
var errUnknownErrorOccurred = errors.New("unknown error occurred during the function call")
2 changes: 1 addition & 1 deletion examples/db_http_logger/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ require (
github.com/rs/cors v1.7.0
github.com/spiral/cascade v1.0.0-beta4
go.etcd.io/bbolt v1.3.5
)
)
2 changes: 1 addition & 1 deletion examples/db_http_logger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func main() {
panic(err)
}

err, errCh := container.Serve()
errCh, err := container.Serve()
if err != nil {
panic(err)
}
Expand Down
4 changes: 4 additions & 0 deletions examples/db_http_logger/modules/db/db_layer.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ func (db *DB) Stop() error {
return nil
}

func (db *DB) Name() string {
return "super DATABASE service"
}

/////////////// DB LAYER /////////////////


Expand Down
4 changes: 4 additions & 0 deletions examples/db_http_logger/modules/gzip/gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,7 @@ func (gz *Gzip) Middleware(f http.Handler) http.HandlerFunc {
gziphandler.GzipHandler(f).ServeHTTP(w, r)
}
}

func (gz *Gzip) Name() string {
return "super Gzip middleware"
}
4 changes: 4 additions & 0 deletions examples/db_http_logger/modules/headers/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,8 @@ func (h *Headers) Middleware(f http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f.ServeHTTP(w, r)
}
}

func (h *Headers) Name() string {
return "super Headers middleware"
}
4 changes: 4 additions & 0 deletions examples/db_http_logger/modules/http/http_layer.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,7 @@ func (h *Http) insert(writer http.ResponseWriter, request *http.Request) {
h.db.Insert()
writer.WriteHeader(http.StatusOK)
}

func (h *Http) Name() string {
return "super http service"
}
12 changes: 12 additions & 0 deletions examples/db_http_logger/modules/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package logger

import (
"fmt"

"github.com/spiral/cascade"
)

type Logger struct {
Expand Down Expand Up @@ -29,3 +31,13 @@ func (l *Logger) Stop() error {
return nil
}

func (l *Logger) Provides() []interface{} {
return []interface{}{
l.LoggerInstance,
}
}

func (l *Logger) LoggerInstance(name cascade.Named) (*Logger, error) {
println(name.Name() + " invoke " + "logger")
return l, nil
}
Loading

0 comments on commit 61c6dfc

Please sign in to comment.