github.com/moleculer-go/moleculer@v0.3.3/moleculer.go (about)

     1  package moleculer
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"time"
     7  
     8  	bus "github.com/moleculer-go/goemitter"
     9  	"github.com/moleculer-go/moleculer/util"
    10  	"go.mongodb.org/mongo-driver/bson"
    11  
    12  	log "github.com/sirupsen/logrus"
    13  )
    14  
    15  type ForEachFunc func(iterator func(key interface{}, value Payload) bool)
    16  
    17  // Payload contains the data sent/return to actions.
    18  // I has convinience methods to read action parameters by name with the right type.
    19  type Payload interface {
    20  	First() Payload
    21  	Sort(field string) Payload
    22  	Remove(fields ...string) Payload
    23  	AddItem(value interface{}) Payload
    24  	Add(field string, value interface{}) Payload
    25  	AddMany(map[string]interface{}) Payload
    26  	MapArray() []map[string]interface{}
    27  	RawMap() map[string]interface{}
    28  	Bson() bson.M
    29  	BsonArray() bson.A
    30  	Map() map[string]Payload
    31  	Exists() bool
    32  	IsError() bool
    33  	Error() error
    34  	ErrorPayload() Payload
    35  	Value() interface{}
    36  	ValueArray() []interface{}
    37  	Int() int
    38  	IntArray() []int
    39  	Int64() int64
    40  	Int64Array() []int64
    41  	Uint() uint64
    42  	UintArray() []uint64
    43  	Float32() float32
    44  	Float32Array() []float32
    45  	Float() float64
    46  	FloatArray() []float64
    47  	String() string
    48  	StringArray() []string
    49  	Bool() bool
    50  	BoolArray() []bool
    51  	ByteArray() []byte
    52  	Time() time.Time
    53  	TimeArray() []time.Time
    54  	Array() []Payload
    55  	At(index int) Payload
    56  	Len() int
    57  	Get(path string, defaultValue ...interface{}) Payload
    58  	//Only return a payload containing only the field specified
    59  	Only(path string) Payload
    60  	IsArray() bool
    61  	IsMap() bool
    62  	ForEach(iterator func(key interface{}, value Payload) bool)
    63  	MapOver(tranform func(in Payload) Payload) Payload
    64  }
    65  
    66  // ActionSchema is used by the validation engine to check if parameters sent to the action are valid.
    67  type ActionSchema interface {
    68  }
    69  
    70  type ObjectSchema struct {
    71  	Source interface{}
    72  }
    73  
    74  type Action struct {
    75  	Name        string
    76  	Handler     ActionHandler
    77  	Schema      ActionSchema
    78  	Settings    map[string]interface{}
    79  	Description string
    80  }
    81  
    82  type Event struct {
    83  	Name    string
    84  	Group   string
    85  	Handler EventHandler
    86  }
    87  
    88  type ServiceSchema struct {
    89  	Name         string
    90  	Version      string
    91  	Dependencies []string
    92  	Settings     map[string]interface{}
    93  	Metadata     map[string]interface{}
    94  	Hooks        map[string]interface{}
    95  	Mixins       []Mixin
    96  	Actions      []Action
    97  	Events       []Event
    98  	Created      CreatedFunc
    99  	Started      LifecycleFunc
   100  	Stopped      LifecycleFunc
   101  }
   102  
   103  type Mixin struct {
   104  	Name         string
   105  	Dependencies []string
   106  	Settings     map[string]interface{}
   107  	Metadata     map[string]interface{}
   108  	Hooks        map[string]interface{}
   109  	Actions      []Action
   110  	Events       []Event
   111  	Created      CreatedFunc
   112  	Started      LifecycleFunc
   113  	Stopped      LifecycleFunc
   114  }
   115  
   116  type TransporterFactoryFunc func() interface{}
   117  type StrategyFactoryFunc func() interface{}
   118  
   119  type Config struct {
   120  	LogLevel                   string
   121  	LogFormat                  string
   122  	DiscoverNodeID             func() string
   123  	Transporter                string
   124  	TransporterFactory         TransporterFactoryFunc
   125  	StrategyFactory            StrategyFactoryFunc
   126  	HeartbeatFrequency         time.Duration
   127  	HeartbeatTimeout           time.Duration
   128  	OfflineCheckFrequency      time.Duration
   129  	OfflineTimeout             time.Duration
   130  	NeighboursCheckTimeout     time.Duration
   131  	WaitForDependenciesTimeout time.Duration
   132  	Middlewares                []Middlewares
   133  	Namespace                  string
   134  	RequestTimeout             time.Duration
   135  	MCallTimeout               time.Duration
   136  	RetryPolicy                RetryPolicy
   137  	MaxCallLevel               int
   138  	Metrics                    bool
   139  	MetricsRate                float32
   140  	DisableInternalServices    bool
   141  	DisableInternalMiddlewares bool
   142  	DontWaitForNeighbours      bool
   143  	WaitForNeighboursInterval  time.Duration
   144  	Created                    func()
   145  	Started                    func()
   146  	Stopped                    func()
   147  
   148  	Services map[string]interface{}
   149  }
   150  
   151  var DefaultConfig = Config{
   152  	LogLevel:                   "INFO",
   153  	LogFormat:                  "TEXT",
   154  	DiscoverNodeID:             discoverNodeID,
   155  	Transporter:                "MEMORY",
   156  	HeartbeatFrequency:         5 * time.Second,
   157  	HeartbeatTimeout:           15 * time.Second,
   158  	OfflineCheckFrequency:      20 * time.Second,
   159  	OfflineTimeout:             10 * time.Minute,
   160  	DontWaitForNeighbours:      true,
   161  	NeighboursCheckTimeout:     2 * time.Second,
   162  	WaitForDependenciesTimeout: 2 * time.Second,
   163  	Metrics:                    false,
   164  	MetricsRate:                1,
   165  	DisableInternalServices:    false,
   166  	DisableInternalMiddlewares: false,
   167  	Created:                    func() {},
   168  	Started:                    func() {},
   169  	Stopped:                    func() {},
   170  	MaxCallLevel:               100,
   171  	RetryPolicy: RetryPolicy{
   172  		Enabled: false,
   173  	},
   174  	RequestTimeout:            3 * time.Second,
   175  	MCallTimeout:              5 * time.Second,
   176  	WaitForNeighboursInterval: 200 * time.Millisecond,
   177  }
   178  
   179  // discoverNodeID - should return the node id for this machine
   180  func discoverNodeID() string {
   181  	hostname, err := os.Hostname()
   182  	if err != nil {
   183  		hostname = "node-" + util.RandomString(2)
   184  	}
   185  	return fmt.Sprint(hostname, "-", util.RandomString(5))
   186  }
   187  
   188  type RetryPolicy struct {
   189  	Enabled  bool
   190  	Retries  int
   191  	Delay    int
   192  	MaxDelay int
   193  	Factor   int
   194  	Check    func(error) bool
   195  }
   196  
   197  type ActionHandler func(context Context, params Payload) interface{}
   198  type EventHandler func(context Context, params Payload)
   199  type CreatedFunc func(ServiceSchema, *log.Entry)
   200  type LifecycleFunc func(BrokerContext, ServiceSchema)
   201  
   202  type LoggerFunc func(name string, value string) *log.Entry
   203  type BusFunc func() *bus.Emitter
   204  type isStartedFunc func() bool
   205  type LocalNodeFunc func() Node
   206  type InstanceIDFunc func() string
   207  type ActionDelegateFunc func(context BrokerContext, opts ...Options) chan Payload
   208  type EmitEventFunc func(context BrokerContext)
   209  type ServiceForActionFunc func(string) []*ServiceSchema
   210  type MultActionDelegateFunc func(callMaps map[string]map[string]interface{}) chan map[string]Payload
   211  type BrokerContextFunc func() BrokerContext
   212  type MiddlewareHandlerFunc func(name string, params interface{}) interface{}
   213  type PublishFunc func(...interface{})
   214  type WaitForFunc func(...string) error
   215  type MiddlewareHandler func(params interface{}, next func(...interface{}))
   216  
   217  type Middlewares map[string]MiddlewareHandler
   218  
   219  type Middleware interface {
   220  	CallHandlers(name string, params interface{}) interface{}
   221  }
   222  type Node interface {
   223  	GetID() string
   224  	ExportAsMap() map[string]interface{}
   225  	IsAvailable() bool
   226  	Available()
   227  	Unavailable()
   228  	IsExpired(timeout time.Duration) bool
   229  	Update(id string, info map[string]interface{}) (bool, []map[string]interface{})
   230  
   231  	IncreaseSequence()
   232  	HeartBeat(heartbeat map[string]interface{})
   233  	Publish(service map[string]interface{})
   234  }
   235  
   236  type Options struct {
   237  	Meta   Payload
   238  	NodeID string
   239  }
   240  
   241  type Context interface {
   242  	//context methods used by services
   243  	MCall(map[string]map[string]interface{}) chan map[string]Payload
   244  	Call(actionName string, params interface{}, opts ...Options) chan Payload
   245  	Emit(eventName string, params interface{}, groups ...string)
   246  	Broadcast(eventName string, params interface{}, groups ...string)
   247  	Logger() *log.Entry
   248  
   249  	Payload() Payload
   250  	Meta() Payload
   251  }
   252  
   253  type BrokerContext interface {
   254  	Call(actionName string, params interface{}, opts ...Options) chan Payload
   255  	Emit(eventName string, params interface{}, groups ...string)
   256  
   257  	ChildActionContext(actionName string, params Payload, opts ...Options) BrokerContext
   258  	ChildEventContext(eventName string, params Payload, groups []string, broadcast bool) BrokerContext
   259  
   260  	ActionName() string
   261  	EventName() string
   262  	Payload() Payload
   263  	Groups() []string
   264  	IsBroadcast() bool
   265  	Caller() string
   266  
   267  	//export context info in a map[string]
   268  	AsMap() map[string]interface{}
   269  
   270  	SetTargetNodeID(targetNodeID string)
   271  	TargetNodeID() string
   272  
   273  	ID() string
   274  	RequestID() string
   275  	Meta() Payload
   276  	UpdateMeta(Payload)
   277  	Logger() *log.Entry
   278  
   279  	Publish(...interface{})
   280  	WaitFor(services ...string) error
   281  }
   282  
   283  // Needs Refactoring..2 broker interfaces.. one for regiwstry.. and for for all others.
   284  type BrokerDelegates struct {
   285  	InstanceID         InstanceIDFunc
   286  	LocalNode          LocalNodeFunc
   287  	Logger             LoggerFunc
   288  	Bus                BusFunc
   289  	IsStarted          isStartedFunc
   290  	Config             Config
   291  	MultActionDelegate MultActionDelegateFunc
   292  	ActionDelegate     ActionDelegateFunc
   293  	EmitEvent          EmitEventFunc
   294  	BroadcastEvent     EmitEventFunc
   295  	HandleRemoteEvent  EmitEventFunc
   296  	ServiceForAction   ServiceForActionFunc
   297  	BrokerContext      BrokerContextFunc
   298  	MiddlewareHandler  MiddlewareHandlerFunc
   299  	Publish            PublishFunc
   300  	WaitFor            WaitForFunc
   301  }