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