-
Notifications
You must be signed in to change notification settings - Fork 11
/
system.go
320 lines (267 loc) · 6.84 KB
/
system.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
package actor
import (
"fmt"
"github.com/golang/protobuf/proto"
"io"
"reflect"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/wwj31/dogactor/actor/actorerr"
"github.com/wwj31/dogactor/actor/internal/innermsg"
"github.com/wwj31/dogactor/log"
"github.com/wwj31/dogactor/logger"
"github.com/wwj31/dogactor/tools"
)
/*
actor system
*/
type System struct {
Stopped chan struct{}
// bind the inter-service communication port
// to system-assigned random port
Addr string
name string
waitStop *sync.WaitGroup // stop wait
stopping atomic.Bool // state of stopping
actorCache sync.Map // all local actor
newList chan *actor // newcomers
clusterId Id // exactly one of etcd(based service discovery) or mq
requestWaiter string // implement sync request
protoIndex *tools.ProtoIndex
evDispatcher
}
func NewSystem(op ...SystemOption) (*System, error) {
s := &System{
Stopped: make(chan struct{}, 1),
waitStop: &sync.WaitGroup{},
newList: make(chan *actor, 100),
}
s.evDispatcher = newEvent(s)
for _, f := range op {
if e := f(s); e != nil {
return nil, fmt.Errorf("%w %v", actorerr.ActorSystemOptionErr, e.Error())
}
}
log.Init()
if s.protoIndex == nil {
log.SysLog.Warnw("without protobuf index,can't find ptoro struct")
}
s.requestWaiter = "waiter_" + s.name + "_" + tools.XUID()
_ = s.NewActor(s.requestWaiter, &waiter{}, SetLocalized())
// first,create waiter and cluster
for len(s.newList) > 0 {
wait := make(chan struct{})
s.runActor(<-s.newList, wait)
<-wait
}
go func() {
for {
select {
case newcomer, ok := <-s.newList:
if !ok {
return
}
s.runActor(newcomer, nil)
}
}
}()
return s, nil
}
func (s *System) Stop() {
if s.stopping.CompareAndSwap(false, true) {
go func() {
// notify all actor to stop
s.actorCache.Range(func(key, value interface{}) bool {
value.(*actor).stop()
return true
})
var _stop bool
for !_stop {
var actorId string
s.actorCache.Range(func(key, value interface{}) bool {
if key == s.clusterId || key == s.requestWaiter {
return true
}
actorId = key.(string)
log.SysLog.Warnw("spare actor...", "actorId", actorId)
return false
})
if actorId == "" {
_stop = true
}
time.Sleep(time.Second)
runtime.Gosched()
}
if err := s.Send("", s.requestWaiter, "", "stop"); err != nil {
log.SysLog.Errorw("stop request waiter send failed", "err", err)
}
s.waitStop.Wait()
close(s.newList)
log.SysLog.Infof("System Exit")
s.Stopped <- struct{}{}
}()
}
}
// NewActor new an actor for system
// id is invalid if contain '@' or '$'
func (s *System) NewActor(id Id, handler spawnActor, opt ...Option) error {
newer := &actor{
system: s,
id: id,
handler: handler,
msgChain: make([]func(message Message) bool, 0, 1),
mailBox: mailBox{ch: make(chan Message, 100)},
remote: true,
}
newer.appendHandler(func(message Message) bool {
handler.OnHandle(message)
return false
})
newer.appendHandler(func(message Message) bool {
if fn, ok := message.Payload().(func()); ok {
fn()
return false
}
return true
})
newer.status.Store(starting)
handler.initActor(newer)
for _, f := range opt {
f(newer)
}
return s.add(newer)
}
// Add startup a new actor
func (s *System) add(actor *actor) error {
if s.stopping.Load() {
return fmt.Errorf("%w actor:%v", actorerr.RegisterActorSystemErr, actor.ID())
}
if _, has := s.actorCache.LoadOrStore(actor.ID(), actor); has {
return fmt.Errorf("%w actor:%v", actorerr.RegisterActorSameIdErr, actor.ID())
}
s.waitStop.Add(1)
var err error
tools.Try(
func() { s.newList <- actor },
func(ex interface{}) {
s.waitStop.Done()
s.actorCache.Delete(actor.ID())
err = fmt.Errorf("add actor failed with exception:%v ", ex)
})
return err
}
// Send try to send the message to target
func (s *System) Send(sourceId, targetId Id, requestId RequestId, msg any) (err error) {
defer func() {
if err != nil {
err = errFormat(err, sourceId, targetId, requestId, reflect.TypeOf(msg).String())
}
}()
var atr *actor
if localActor, ok := s.actorCache.Load(targetId); ok {
atr = localActor.(*actor)
}
// when the actor into draining mode or not found locally,
// send the message to the cluster.
var sendToCluster bool
if atr == nil {
sendToCluster = true
} else {
if drainer, ok := atr.handler.(Drainer); ok {
sendToCluster = drainer.isDraining()
}
}
if sendToCluster {
pt, canRemote := msg.(proto.Message)
if canRemote {
v, _ := s.actorCache.Load(s.Cluster())
atr = v.(*actor)
bytes, marshalErr := proto.Marshal(pt)
if marshalErr != nil {
return fmt.Errorf("%w %v", actorerr.ProtoMarshalErr, err)
}
// remote message
actorMsg := &innermsg.ActorMessage{
SourceId: sourceId,
TargetId: targetId,
RequestId: requestId.String(),
MsgName: s.protoIndex.MsgName(pt),
Data: bytes,
}
msg, _ = actorMsg.Marshal()
} else {
return actorerr.ActorMsgTypeCanNotRemoteErr
}
}
if atr == nil {
return actorerr.ActorNotFoundErr
}
localMsg := innermsg.NewActorMessage() // local message
localMsg.SourceId = sourceId
localMsg.TargetId = targetId
localMsg.RequestId = requestId.String()
localMsg.SetPayload(msg)
return atr.push(localMsg)
}
func (s *System) HasActor(actorId string) bool {
_, ok := s.actorCache.Load(actorId)
return ok
}
// if ok != nil, caller wait for actor call init to finish
func (s *System) runActor(actor *actor, ok chan<- struct{}) {
if s.stopping.Load() {
return
}
go actor.init(ok)
}
func (s *System) WaiterId() string {
return s.requestWaiter
}
func (s *System) SetCluster(id Id) {
s.clusterId = id
}
func (s *System) Cluster() Id {
return s.clusterId
}
func (s *System) ProtoIndex() *tools.ProtoIndex {
return s.protoIndex
}
type SystemOption func(*System) error
// ProtoIndex index proto struct
func ProtoIndex(pi *tools.ProtoIndex) SystemOption {
return func(system *System) error {
system.protoIndex = pi
return nil
}
}
func Name(name string) SystemOption {
return func(system *System) error {
system.name = name
return nil
}
}
func LogFileName(path, fileName string) SystemOption {
return func(system *System) error {
log.SysLogOption.LogPath = path
log.SysLogOption.FileName = fileName
return nil
}
}
func LogLevel(level logger.Level) SystemOption {
return func(system *System) error {
log.SysLogOption.Level = level
return nil
}
}
func Output(out io.Writer) SystemOption {
return func(system *System) error {
log.SysLogOption.ExtraWriter = append(log.SysLogOption.ExtraWriter, out)
log.SysLogOption.LogPath = ""
return nil
}
}
func errFormat(err error, sourceId, targetId Id, requestId RequestId, msg string) error {
return fmt.Errorf("%w s:[%v] t:[%v],r:[%v] msg:[%v]", err, sourceId, targetId, requestId, msg)
}