-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinstance_manager.go
148 lines (127 loc) · 3.84 KB
/
instance_manager.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
package stableinterfaces
import (
"context"
"errors"
"fmt"
"github.com/danthegoodman1/stableinterfaces/syncx"
"sync"
"sync/atomic"
)
type (
instanceManager struct {
stableInterface StableInterface
connections syncx.Map[string, *connectionPair]
shuttingDown *atomic.Bool
handlingWG *sync.WaitGroup
internalID string
interfaceManager *InterfaceManager
}
)
var (
ErrInstanceIsShuttingDown = errors.New("instance is shuttingDown")
)
func newInstanceManager(im *InterfaceManager, internalID string, stableInterface StableInterface) *instanceManager {
return &instanceManager{
stableInterface: stableInterface,
connections: syncx.NewMap[string, *connectionPair](),
shuttingDown: &atomic.Bool{},
handlingWG: &sync.WaitGroup{},
internalID: internalID,
interfaceManager: im,
}
}
func (im *instanceManager) makeInterfaceContext(ctx context.Context) InterfaceContext {
return InterfaceContext{
Context: ctx,
Shard: instanceInternalIDToShard(im.internalID, int(im.interfaceManager.numShards)),
interfaceManager: im.interfaceManager,
instanceManager: im,
InternalInstanceID: im.internalID,
}
}
func (im *instanceManager) Request(ctx context.Context, payload any) (any, error) {
response, err := im.stableInterface.OnRequest(im.makeInterfaceContext(ctx), payload)
if err != nil {
return nil, wrapStableInterfaceHandlerError(err)
}
return response, nil
}
func (im *instanceManager) Connect(ctx context.Context, meta map[string]any) (*InterfaceConnection, error) {
if !im.interfaceManager.withConnect {
return nil, ErrInterfaceNotWithConnect
}
connID := genRandomID("")
incoming := newIncomingConnection(im.internalID, connID, meta)
doneChan := make(chan any, 1)
go func() {
im.stableInterface.(StableInterfaceWithConnect).OnConnect(im.makeInterfaceContext(ctx), *incoming)
doneChan <- nil
}()
var connPair *connectionPair
select {
case connPair = <-incoming.acceptChan:
break
case <-doneChan:
break
case reason := <-incoming.rejectChan:
return nil, fmt.Errorf("%w, reason: %w", ErrIncomingConnectionRejected, reason)
case <-ctx.Done():
return nil, fmt.Errorf("context done: %w", ctx.Err())
}
if connPair == nil {
// they did not accept or reject
return nil, ErrIncomingConnectionNotHandled
}
connPair.ManagerSide.AddOnCloseListener(func() {
// Remove the connection from the map
im.connections.Delete(connID)
})
im.connections.Store(connID, connPair)
return &connPair.ManagerSide, nil
}
func (im *instanceManager) Alarm(ctx context.Context, attempt int, id string, meta map[string]any) error {
if im.shuttingDown.Load() {
return ErrInstanceIsShuttingDown
}
alarmInstance, ok := im.stableInterface.(StableInterfaceWithAlarm)
if !ok {
return fmt.Errorf("%w -- this is a bug, please report", ErrInterfaceNotWithAlarm)
}
err := alarmInstance.OnAlarm(InterfaceContextWithAttempt{
InterfaceContext: im.makeInterfaceContext(ctx),
Attempt: attempt,
}, id, meta)
if err != nil {
return fmt.Errorf("error in Alarm: %w", err)
}
return nil
}
func (im *instanceManager) Shutdown(ctx context.Context) error {
if !im.shuttingDown.CompareAndSwap(false, true) {
return ErrInstanceIsShuttingDown
}
doneChan := make(chan error)
go func(edc chan error) {
im.shutdown(ctx)
doneChan <- nil
}(doneChan)
select {
case err := <-doneChan:
return err
case <-ctx.Done():
return ctx.Err()
}
}
func (im *instanceManager) shutdown(ctx context.Context) {
im.interfaceManager.logger.Debug(fmt.Sprintf("shutting down instance %s", im.internalID))
// Disconnect all connections
im.connections.Range(func(connID string, conn *connectionPair) bool {
err := conn.Close(ctx)
if err != nil {
im.interfaceManager.logger.Error(fmt.Sprintf("failed to shutdown connection %s", conn.ID), err)
}
return true
})
im.handlingWG.Wait()
return
}