Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
markus621 committed Jul 30, 2024
1 parent fdc7729 commit bec9634
Show file tree
Hide file tree
Showing 16 changed files with 148 additions and 268 deletions.
142 changes: 0 additions & 142 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,144 +1,2 @@
# Grape
Application module aggregator

## Base config file

***config.yaml***

```yaml
env: dev
level: 3
log: /var/log/simple.log
pig: /var/run/simple.pid
```
level:
* 0 - error only
* 1 - + warning
* 2 - + info
* 3 - + debug
## Example
```go
package main

import (
"fmt"

"go.osspkg.com/grape"
"go.osspkg.com/logx"
"go.osspkg.com/xc"
)

type (
//Simple model
Simple struct{}
//Config model
Config struct {
Env string `yaml:"env"`
}
)

//NewSimple init Simple
func NewSimple(_ Config) *Simple {
fmt.Println("--> call NewSimple")
return &Simple{}
}

//Up method for start Simple in DI container
func (s *Simple) Up(_ xc.Context) error {
fmt.Println("--> call *Simple.Up")
return nil
}

//Down method for stop Simple in DI container
func (s *Simple) Down(_ xc.Context) error {
fmt.Println("--> call *Simple.Down")
return nil
}

func main() {
grape.New().
Logger(logx.Default()).
ConfigFile(
"./config.yaml",
Config{},
).
Modules(
NewSimple,
).
Run()
}
```

## HowTo

***Run the app***

```go
grape.New()
.ConfigFile(<path to config file: string>, <config objects separate by comma: ...interface{}>)
.Modules(<config objects separate by comma: ...interface{}>)
.Run()
```

***Supported types for initialization***

* Function that returns an object or interface

*All incoming dependencies will be injected automatically*

```go
type Simple1 struct{}
func NewSimple1(_ *logx.Logger) *Simple1 { return &Simple1{} }
```

*Returns the interface*

```go
type Simple2 struct{}
type Simple2Interface interface{
Get() string
}
func NewSimple2() Simple2Interface { return &Simple2{} }
func (s2 *Simple2) Get() string {
return "Hello world"
}
```

*If the object has the `Up(xc.Context) error` and `Down() error` methods, they will be called `Up(xc.Context) error`
when the app starts, and `Down() error` when it finishes. This allows you to automatically start and stop routine
processes inside the module*

```go
var _ service.IServiceCtx = (*Simple3)(nil)
type Simple3 struct{}
func NewSimple3(_ *Simple4) *Simple3 { return &Simple3{} }
func (s3 *Simple3) Up(_ xc.Context) error { return nil }
func (s3 *Simple3) Down(_ xc.Context) error { return nil }
```

* Named type

```go
type HelloWorld string
```

* Object structure

```go
type Simple4 struct{
S1 *Simple1
S2 Simple2Interface
HW HelloWorld
}
```

* Object reference or type

```go
s1 := &Simple1{}
hw := HelloWorld("Hello!!")
```
19 changes: 12 additions & 7 deletions application.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import (
"go.osspkg.com/config"
"go.osspkg.com/console"
"go.osspkg.com/events"
config2 "go.osspkg.com/grape/config"
"go.osspkg.com/grape/container"
"go.osspkg.com/grape/env"
"go.osspkg.com/grape/internal"
"go.osspkg.com/grape/reflect"
"go.osspkg.com/logx"
"go.osspkg.com/xc"
)
Expand All @@ -33,7 +38,7 @@ type (
resolvers []config.Resolver
configs Modules
modules Modules
packages Container
packages container.TContainer
logHandler *_log
log logx.Logger
appContext xc.Context
Expand All @@ -48,7 +53,7 @@ func New() Grape {
resolvers: make([]config.Resolver, 0, 2),
modules: Modules{},
configs: Modules{},
packages: NewContainer(ctx),
packages: container.New(ctx),
appContext: ctx,
exitFunc: func(_ int) {},
}
Expand Down Expand Up @@ -208,7 +213,7 @@ func (a *_grape) Call(call interface{}) {
func (a *_grape) prepareConfig(interactive bool) {
var err error
if len(a.configFilePath) == 0 {
a.logHandler = newLog(LogConfig{
a.logHandler = newLog(config2.LogConfig{
Level: 4,
FilePath: "/dev/stdout",
Format: "string",
Expand All @@ -227,7 +232,7 @@ func (a *_grape) prepareConfig(interactive bool) {
if err = resolver.Build(); err != nil {
console.FatalIfErr(err, "prepare config file: %s", a.configFilePath)
}
appConfig := &Config{}
appConfig := &config2.Config{}
if err = resolver.Decode(appConfig); err != nil {
console.FatalIfErr(err, "decode config file: %s", a.configFilePath)
}
Expand All @@ -243,12 +248,12 @@ func (a *_grape) prepareConfig(interactive bool) {
}
a.logHandler.Handler(a.log)
a.modules = a.modules.Add(
ENV(appConfig.Env),
env.ENV(appConfig.Env),
)

// decode all configs
var configs []interface{}
configs, err = typingReflectPtr(a.configs, func(c interface{}) error {
configs, err = reflect.TypingPtr(a.configs, func(c interface{}) error {
return resolver.Decode(c)
})
if err != nil {
Expand All @@ -259,7 +264,7 @@ func (a *_grape) prepareConfig(interactive bool) {
a.modules = a.modules.Add(configs...)

if !interactive && len(a.pidFilePath) > 0 {
if err = pid2file(a.pidFilePath); err != nil {
if err = internal.SavePidToFile(a.pidFilePath); err != nil {
a.log.WithFields(logx.Fields{
"err": err.Error(),
"file": a.pidFilePath,
Expand Down
2 changes: 1 addition & 1 deletion config.go → config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/

package grape
package config

type (
// Config config model
Expand Down
41 changes: 22 additions & 19 deletions container.go → container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,30 @@
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/

package grape
package container

import (
"fmt"
"reflect"

"go.osspkg.com/algorithms/graph/kahn"
"go.osspkg.com/errors"
errors2 "go.osspkg.com/grape/errors"
reflect2 "go.osspkg.com/grape/reflect"
"go.osspkg.com/grape/services"
"go.osspkg.com/syncing"
"go.osspkg.com/xc"
)

type (
_container struct {
kahn *kahn.Graph
srv *serviceTree
srv services.TServices
store *objectStorage
status syncing.Switch
}

Container interface {
TContainer interface {
Start() error
Register(items ...interface{}) error
Invoke(item interface{}) error
Expand All @@ -32,10 +35,10 @@ type (
}
)

func NewContainer(ctx xc.Context) Container {
func New(ctx xc.Context) TContainer {
return &_container{
kahn: kahn.New(),
srv: newServiceTree(ctx),
srv: services.New(ctx),
store: newObjectStorage(),
status: syncing.NewSwitch(),
}
Expand All @@ -52,7 +55,7 @@ func (v *_container) Stop() error {
// Start - initialize dependencies and start
func (v *_container) Start() error {
if !v.status.On() {
return errDepAlreadyRunning
return errors2.ErrDepAlreadyRunning
}
if err := v.srv.MakeAsUp(); err != nil {
return err
Expand All @@ -68,7 +71,7 @@ func (v *_container) Start() error {

func (v *_container) Register(items ...interface{}) error {
if v.srv.IsOn() {
return errDepAlreadyRunning
return errors2.ErrDepAlreadyRunning
}

for _, item := range items {
Expand All @@ -88,17 +91,17 @@ func (v *_container) Register(items ...interface{}) error {

func (v *_container) BreakPoint(item interface{}) error {
if v.srv.IsOn() {
return errDepAlreadyRunning
return errors2.ErrDepAlreadyRunning
}
ref := reflect.TypeOf(item)
switch ref.Kind() {
case reflect.Func:
default:
return errBreakPointType
return errors2.ErrBreakPointType
}
address, ok := getReflectAddress(ref, item)
address, ok := reflect2.GetAddress(ref, item)
if !ok {
return errBreakPointAddress
return errors2.ErrBreakPointAddress
}
v.kahn.BreakPoint(address)
return nil
Expand All @@ -117,13 +120,13 @@ func (v *_container) prepare() error {
}
for i := 0; i < item.ReflectType.NumIn(); i++ {
inRefType := item.ReflectType.In(i)
inAddress, _ := getReflectAddress(inRefType, nil)
inAddress, _ := reflect2.GetAddress(inRefType, nil)
v.kahn.Add(inAddress, item.Address)
}

for i := 0; i < item.ReflectType.NumOut(); i++ {
outRefType := item.ReflectType.Out(i)
outAddress, _ := getReflectAddress(outRefType, nil)
outAddress, _ := reflect2.GetAddress(outRefType, nil)
v.kahn.Add(item.Address, outAddress)
}

Expand All @@ -133,7 +136,7 @@ func (v *_container) prepare() error {
}
for i := 0; i < item.ReflectType.NumField(); i++ {
inRefType := item.ReflectType.Field(i).Type
inAddress, _ := getReflectAddress(inRefType, nil)
inAddress, _ := reflect2.GetAddress(inRefType, nil)
v.kahn.Add(inAddress, item.Address)
}

Expand All @@ -147,7 +150,7 @@ func (v *_container) prepare() error {

func (v *_container) Invoke(obj interface{}) error {
if v.srv.IsOff() {
return errDepNotRunning
return errors2.ErrDepNotRunning
}
item, _, err := v.callArgs(obj)
if err != nil {
Expand Down Expand Up @@ -185,7 +188,7 @@ func (v *_container) callArgs(obj interface{}) (*objectStorageItem, []reflect.Va
args := make([]reflect.Value, 0, item.ReflectType.NumIn())
for i := 0; i < item.ReflectType.NumIn(); i++ {
inRefType := item.ReflectType.In(i)
inAddress, ok := getReflectAddress(inRefType, item.Value)
inAddress, ok := reflect2.GetAddress(inRefType, item.Value)
if !ok {
return nil, nil, fmt.Errorf("dependency [%s] is not supported", inAddress)
}
Expand All @@ -208,7 +211,7 @@ func (v *_container) callArgs(obj interface{}) (*objectStorageItem, []reflect.Va
args := make([]reflect.Value, 0, 1)
for i := 0; i < item.ReflectType.NumField(); i++ {
inRefType := item.ReflectType.Field(i)
inAddress, ok := getReflectAddress(inRefType.Type, nil)
inAddress, ok := reflect2.GetAddress(inRefType.Type, nil)
if !ok {
return nil, nil, fmt.Errorf("dependency [%s] is not supported", inAddress)
}
Expand Down Expand Up @@ -239,7 +242,7 @@ func (v *_container) run() error {
defer v.srv.IterateOver()

for _, name := range v.kahn.Result() {
if name == root || name == errName {
if name == root || name == reflect2.ErrorName {
continue
}
item, err := v.store.GetByAddress(name)
Expand All @@ -266,7 +269,7 @@ func (v *_container) run() error {
return errors.Wrapf(err, "initialize error")
}
if item, err = v.store.GetByReflect(arg.Type(), arg.Interface()); err != nil {
if errors.Is(err, errIsTypeError) {
if errors.Is(err, errors2.ErrIsTypeError) {
continue
}
return errors.Wrapf(err, "initialize error")
Expand Down
Loading

0 comments on commit bec9634

Please sign in to comment.