forked from asynkron/protoactor-go
/
local_context.go
521 lines (443 loc) · 11.7 KB
/
local_context.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package actor
import (
"errors"
"time"
"github.com/AsynkronIT/protoactor-go/log"
"github.com/emirpasic/gods/stacks/linkedliststack"
)
type contextState int32
const (
stateNone contextState = iota
stateAlive
stateRestarting
stateStopping
stateStopped
)
type localContext struct {
message interface{}
parent *PID
self *PID
actor Actor
supervisor SupervisorStrategy
producer Producer
inboundMiddleware ActorFunc
outboundMiddleware SenderFunc
behavior behaviorStack
receive ActorFunc
children PIDSet
watchers PIDSet
watching PIDSet
stash *linkedliststack.Stack
state contextState
receiveTimeout time.Duration
t *time.Timer
restartStats *RestartStatistics
}
func newLocalContext(producer Producer, supervisor SupervisorStrategy, inboundMiddleware []InboundMiddleware, outboundMiddleware []OutboundMiddleware, parent *PID) *localContext {
this := &localContext{
parent: parent,
producer: producer,
supervisor: supervisor,
}
// Construct the inbound middleware chain with the final receiver at the end
if inboundMiddleware != nil {
this.inboundMiddleware = makeInboundMiddlewareChain(inboundMiddleware, func(ctx Context) {
if _, ok := this.message.(*PoisonPill); ok {
this.self.Stop()
} else {
this.receive(ctx)
}
})
}
// Construct the outbound middleware chain with the final sender at the end
this.outboundMiddleware = makeOutboundMiddlewareChain(outboundMiddleware, func(_ Context, target *PID, envelope *MessageEnvelope) {
target.ref().SendUserMessage(target, envelope)
})
this.incarnateActor()
return this
}
func (ctx *localContext) Actor() Actor {
return ctx.actor
}
func (ctx *localContext) Message() interface{} {
envelope, ok := ctx.message.(*MessageEnvelope)
if ok {
return envelope.Message
}
return ctx.message
}
func (ctx *localContext) Sender() *PID {
envelope, ok := ctx.message.(*MessageEnvelope)
if ok {
return envelope.Sender
}
return nil
}
func (ctx *localContext) MessageHeader() ReadonlyMessageHeader {
envelope, ok := ctx.message.(*MessageEnvelope)
if ok {
if envelope.Header != nil {
return envelope.Header
}
}
return emptyMessageHeader
}
func (ctx *localContext) Tell(pid *PID, message interface{}) {
ctx.sendUserMessage(pid, message)
}
func (ctx *localContext) Forward(pid *PID) {
if msg, ok := ctx.Message().(SystemMessage); ok {
// SystemMessage cannot be forwarded
plog.Error("SystemMessage cannot be forwarded", log.Message(msg))
return
}
ctx.sendUserMessage(pid, ctx.message)
}
func (ctx *localContext) sendUserMessage(pid *PID, message interface{}) {
if ctx.outboundMiddleware != nil {
if env, ok := message.(*MessageEnvelope); ok {
ctx.outboundMiddleware(ctx, pid, env)
} else {
ctx.outboundMiddleware(ctx, pid, &MessageEnvelope{
Header: nil,
Message: message,
Sender: nil,
})
}
} else {
pid.ref().SendUserMessage(pid, message)
}
}
func (ctx *localContext) Request(pid *PID, message interface{}) {
env := &MessageEnvelope{
Header: nil,
Message: message,
Sender: ctx.Self(),
}
ctx.sendUserMessage(pid, env)
}
func (ctx *localContext) RequestFuture(pid *PID, message interface{}, timeout time.Duration) *Future {
future := NewFuture(timeout)
env := &MessageEnvelope{
Header: nil,
Message: message,
Sender: future.PID(),
}
ctx.sendUserMessage(pid, env)
return future
}
func (ctx *localContext) Stash() {
if ctx.stash == nil {
ctx.stash = linkedliststack.New()
}
ctx.stash.Push(ctx.message)
}
func (ctx *localContext) cancelTimer() {
if ctx.t != nil {
ctx.t.Stop()
ctx.t = nil
ctx.receiveTimeout = 0
}
}
func (ctx *localContext) receiveTimeoutHandler() {
if ctx.t != nil {
ctx.cancelTimer()
ctx.self.Tell(receiveTimeoutMessage)
}
}
func (ctx *localContext) SetReceiveTimeout(d time.Duration) {
if d == ctx.receiveTimeout {
return
}
if ctx.t != nil {
ctx.t.Stop()
}
if d < time.Millisecond {
// anything less than than 1 millisecond is set to zero
d = 0
}
ctx.receiveTimeout = d
if d > 0 {
if ctx.t == nil {
ctx.t = time.AfterFunc(d, ctx.receiveTimeoutHandler)
} else {
ctx.t.Reset(d)
}
}
}
func (ctx *localContext) ReceiveTimeout() time.Duration {
return ctx.receiveTimeout
}
func (ctx *localContext) Children() []*PID {
r := make([]*PID, ctx.children.Len())
ctx.children.ForEach(func(i int, p PID) {
r[i] = &p
})
return r
}
func (ctx *localContext) Self() *PID {
return ctx.self
}
func (ctx *localContext) Parent() *PID {
return ctx.parent
}
func (ctx *localContext) Receive(message interface{}) {
ctx.processMessage(message)
}
func (ctx *localContext) RestartStats() *RestartStatistics {
//lazy initialize the child restart stats if this is the first time
//further mutations are handled within "restart"
if ctx.restartStats == nil {
ctx.restartStats = NewRestartStatistics()
}
return ctx.restartStats
}
func (ctx *localContext) EscalateFailure(reason interface{}, message interface{}) {
failure := &Failure{Reason: reason, Who: ctx.self, RestartStats: ctx.RestartStats()}
ctx.self.sendSystemMessage(suspendMailboxMessage)
if ctx.parent == nil {
handleRootFailure(failure)
} else {
//TODO: Akka recursively suspends all children also on failure
//Not sure if I think this is the right way to go, why do children need to wait for their parents failed state to recover?
ctx.parent.sendSystemMessage(failure)
}
}
func (ctx *localContext) InvokeUserMessage(md interface{}) {
if ctx.state == stateStopped {
//already stopped
return
}
influenceTimeout := true
if ctx.receiveTimeout > 0 {
_, influenceTimeout = md.(NotInfluenceReceiveTimeout)
envelope, ok := md.(*MessageEnvelope)
if ok {
_, influenceTimeout = envelope.Message.(NotInfluenceReceiveTimeout)
}
influenceTimeout = !influenceTimeout
if influenceTimeout {
ctx.t.Stop()
}
}
ctx.processMessage(md)
if ctx.receiveTimeout > 0 && influenceTimeout {
ctx.t.Reset(ctx.receiveTimeout)
}
}
func (ctx *localContext) processMessage(m interface{}) {
ctx.message = m
if ctx.inboundMiddleware != nil {
ctx.inboundMiddleware(ctx)
} else {
if _, ok := m.(*PoisonPill); ok {
ctx.self.Stop()
} else {
ctx.receive(ctx)
}
}
ctx.message = nil
}
func (ctx *localContext) incarnateActor() {
pid := ctx.producer()
ctx.state = stateAlive
ctx.actor = pid
ctx.receive = pid.Receive
}
func (ctx *localContext) InvokeSystemMessage(message interface{}) {
switch msg := message.(type) {
case *continuation:
ctx.message = msg.message // apply the message that was present when we started the await
msg.f() // invoke the continuation in the current actor context
ctx.message = nil // release the message
case *Started:
ctx.InvokeUserMessage(msg) // forward
case *Watch:
ctx.handleWatch(msg)
case *Unwatch:
ctx.handleUnwatch(msg)
case *Stop:
ctx.handleStop(msg)
case *Terminated:
ctx.handleTerminated(msg)
case *Failure:
ctx.handleFailure(msg)
case *Restart:
ctx.handleRestart(msg)
default:
plog.Error("unknown system message", log.Message(msg))
}
}
func (ctx *localContext) handleWatch(msg *Watch) {
if ctx.state >= stateStopping {
msg.Watcher.sendSystemMessage(&Terminated{
Who: ctx.self,
})
} else {
ctx.watchers.Add(msg.Watcher)
}
}
func (ctx *localContext) handleUnwatch(msg *Unwatch) {
ctx.watchers.Remove(msg.Watcher)
}
func (ctx *localContext) handleRestart(msg *Restart) {
ctx.state = stateRestarting
ctx.InvokeUserMessage(restartingMessage)
ctx.children.ForEach(func(_ int, pid PID) {
pid.Stop()
})
ctx.tryRestartOrTerminate()
}
//I am stopping
func (ctx *localContext) handleStop(msg *Stop) {
if ctx.state >= stateStopping {
//already stopping or stopped
return
}
ctx.state = stateStopping
ctx.InvokeUserMessage(stoppingMessage)
ctx.children.ForEach(func(_ int, pid PID) {
pid.Stop()
})
ctx.tryRestartOrTerminate()
}
//child stopped, check if we can stop or restart (if needed)
func (ctx *localContext) handleTerminated(msg *Terminated) {
ctx.children.Remove(msg.Who)
ctx.watching.Remove(msg.Who)
ctx.InvokeUserMessage(msg)
ctx.tryRestartOrTerminate()
}
//offload the supervision completely to the supervisor strategy
func (ctx *localContext) handleFailure(msg *Failure) {
if strategy, ok := ctx.actor.(SupervisorStrategy); ok {
strategy.HandleFailure(ctx, msg.Who, msg.RestartStats, msg.Reason, msg.Message)
return
}
ctx.supervisor.HandleFailure(ctx, msg.Who, msg.RestartStats, msg.Reason, msg.Message)
}
func (ctx *localContext) tryRestartOrTerminate() {
if ctx.t != nil {
ctx.t.Stop()
ctx.t = nil
ctx.receiveTimeout = 0
}
if !ctx.children.Empty() {
return
}
switch ctx.state {
case stateRestarting:
ctx.restart()
case stateStopping:
ctx.stopped()
}
}
func (ctx *localContext) restart() {
ctx.incarnateActor()
ctx.InvokeUserMessage(startedMessage)
if ctx.stash != nil {
for !ctx.stash.Empty() {
msg, _ := ctx.stash.Pop()
ctx.InvokeUserMessage(msg)
}
}
ctx.self.sendSystemMessage(resumeMailboxMessage)
}
func (ctx *localContext) stopped() {
ProcessRegistry.Remove(ctx.self)
ctx.InvokeUserMessage(stoppedMessage)
otherStopped := &Terminated{Who: ctx.self}
ctx.watchers.ForEach(func(i int, pid PID) {
pid.sendSystemMessage(otherStopped)
})
ctx.state = stateStopped
}
func (ctx *localContext) SetBehavior(behavior ActorFunc) {
ctx.behavior.Clear()
ctx.receive = behavior
}
func (ctx *localContext) PushBehavior(behavior ActorFunc) {
ctx.behavior.Push(ctx.receive)
ctx.receive = behavior
}
func (ctx *localContext) PopBehavior() {
if ctx.behavior.Len() == 0 {
panic("Cannot unbecome actor base behavior")
}
ctx.receive, _ = ctx.behavior.Pop()
}
func (ctx *localContext) Watch(who *PID) {
who.sendSystemMessage(&Watch{
Watcher: ctx.self,
})
ctx.watching.Add(who)
}
func (ctx *localContext) Unwatch(who *PID) {
who.sendSystemMessage(&Unwatch{
Watcher: ctx.self,
})
ctx.watching.Remove(who)
}
func (ctx *localContext) Respond(response interface{}) {
// If the message is addressed to nil forward it to the dead letter channel
if ctx.Sender() == nil {
deadLetter.SendUserMessage(nil, response)
return
}
ctx.Tell(ctx.Sender(), response)
}
func (ctx *localContext) Spawn(props *Props) *PID {
pid, _ := ctx.SpawnNamed(props, ProcessRegistry.NextId())
return pid
}
func (ctx *localContext) SpawnPrefix(props *Props, prefix string) *PID {
pid, _ := ctx.SpawnNamed(props, prefix+ProcessRegistry.NextId())
return pid
}
func (ctx *localContext) SpawnNamed(props *Props, name string) (*PID, error) {
if props.guardianStrategy != nil {
panic(errors.New("Props used to spawn child cannot have GuardianStrategy"))
}
pid, err := props.spawn(ctx.self.Id+"/"+name, ctx.self)
if err != nil {
return pid, err
}
ctx.children.Add(pid)
ctx.Watch(pid)
return pid, nil
}
func (ctx *localContext) GoString() string {
return ctx.self.String()
}
func (ctx *localContext) String() string {
return ctx.self.String()
}
func (ctx *localContext) AwaitFuture(f *Future, cont func(res interface{}, err error)) {
wrapper := func() {
cont(f.result, f.err)
}
message := ctx.message
//invoke the callback when the future completes
f.continueWith(func(res interface{}, err error) {
//send the wrapped callaback as a continuation message to self
ctx.self.sendSystemMessage(&continuation{
f: wrapper,
message: message,
})
})
}
func (*localContext) RestartChildren(pids ...*PID) {
for _, pid := range pids {
pid.sendSystemMessage(restartMessage)
}
}
func (*localContext) StopChildren(pids ...*PID) {
for _, pid := range pids {
pid.sendSystemMessage(stopMessage)
}
}
func (*localContext) ResumeChildren(pids ...*PID) {
for _, pid := range pids {
pid.sendSystemMessage(resumeMailboxMessage)
}
}