actor_system.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package ruleEngine
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/gogf/gf/os/grpool"
  7. "github.com/gogf/gf/util/guid"
  8. "golang.org/x/time/rate"
  9. "sparrow/pkg/entities"
  10. "sparrow/pkg/models"
  11. "sparrow/pkg/protocol"
  12. "sparrow/pkg/server"
  13. "sync"
  14. "time"
  15. )
  16. // SystemContext actor system context, with some func
  17. type SystemContext struct {
  18. ActorSystem System
  19. AppActor Ref
  20. ClusterService ClusterService
  21. RuleChainService RuleChainService
  22. TenantService TenantService
  23. EventService EventService
  24. // 调试信息的限流器
  25. debugPerTenantLimits map[string]*rate.Limiter
  26. }
  27. type SystemContextServiceConfig struct {
  28. ClusterService ClusterService
  29. RuleChainService RuleChainService
  30. TenantService TenantService
  31. EventService EventService
  32. }
  33. func NewSystemContext(sys System, config SystemContextServiceConfig) *SystemContext {
  34. if config.TenantService == nil || config.RuleChainService == nil || config.ClusterService == nil ||
  35. config.EventService == nil {
  36. panic("RuleEngine init error: services is not set")
  37. }
  38. return &SystemContext{
  39. ActorSystem: sys,
  40. ClusterService: config.ClusterService,
  41. RuleChainService: config.RuleChainService,
  42. TenantService: config.TenantService,
  43. debugPerTenantLimits: make(map[string]*rate.Limiter),
  44. EventService: config.EventService,
  45. }
  46. }
  47. // PersistDebugInput 保存输入调试信息
  48. func (s *SystemContext) PersistDebugInput(tenantId string, entityId entities.EntityId, msg *protocol.Message, relationType string, err error) error {
  49. return s.persistDebugAsync(tenantId, entityId, "IN", msg, relationType, err)
  50. }
  51. // PersistDebugOutput 保存输出调试信息
  52. func (s *SystemContext) PersistDebugOutput(tenantId string, entityId entities.EntityId, msg *protocol.Message, relationType string, err error) error {
  53. return s.persistDebugAsync(tenantId, entityId, "OUT", msg, relationType, err)
  54. }
  55. func (s *SystemContext) persistDebugAsync(tenantId string, id entities.EntityId, eType string, msg *protocol.Message, rType string, errInfo error) error {
  56. var limiter *rate.Limiter
  57. if v, ok := s.debugPerTenantLimits[tenantId]; !ok {
  58. limiter = rate.NewLimiter(10, 200)
  59. s.debugPerTenantLimits[tenantId] = limiter
  60. } else {
  61. limiter = v
  62. }
  63. if limiter.AllowN(time.Now(), 200) {
  64. var errStr string
  65. if v, ok := msg.MetaData["error"]; ok {
  66. errStr = v.(string)
  67. }
  68. if errInfo != nil {
  69. errStr = errInfo.Error()
  70. }
  71. buf, err := json.Marshal(msg.MetaData)
  72. if err != nil {
  73. server.Log.WithField("method", "persistDebugAsync").Error(err)
  74. }
  75. if s.EventService != nil {
  76. if err := s.EventService.SaveAsync(&models.Event{
  77. RecordId: guid.S(),
  78. ServerId: server.InternalIP,
  79. EventType: eType,
  80. EntityType: id.GetEntityType().String(),
  81. EntityId: id.GetId(),
  82. MessageId: msg.Id,
  83. RelationType: rType,
  84. Data: msg.Data,
  85. MetaData: string(buf),
  86. Error: errStr,
  87. }); err != nil {
  88. return err
  89. }
  90. }
  91. }
  92. return nil
  93. }
  94. func (s *SystemContext) Tell(msg protocol.ActorMsg) {
  95. s.AppActor.Tell(msg)
  96. }
  97. func (s *SystemContext) TellWithHighPriority(msg protocol.ActorMsg) {
  98. s.AppActor.TellWithHighPriority(msg)
  99. }
  100. // System actor system interface
  101. type System interface {
  102. // CreateDispatcher 创建分发器
  103. CreateDispatcher(name string, dispatcher IDispatcher) error
  104. // DestroyDispatcher 销毁分发器
  105. DestroyDispatcher(name string) error
  106. // GetActor 获取一个actor ref
  107. GetActor(actorId string) Ref
  108. // CreateRootActor create root actor
  109. CreateRootActor(dispatcherName string, creator Creator) (Ref, error)
  110. // CreateChildActor create child actor by parent actor
  111. CreateChildActor(dispatcherName string, creator Creator, parentId string) (Ref, error)
  112. // Tell tell actor a message
  113. Tell(actorId string, msg protocol.ActorMsg) error
  114. // TellWithHighPriority tell actor message with high priority
  115. TellWithHighPriority(actorId string, msg protocol.ActorMsg) error
  116. // StopActorById stop actor by actor id
  117. StopActorById(actorId string) error
  118. // StopActorByRef stop actor by actor ref
  119. StopActorByRef(ref Ref) error
  120. // BroadcastToChildren broadcast message to children
  121. BroadcastToChildren(parentActorId string, msg protocol.ActorMsg) error
  122. }
  123. // DefaultActorSystem a default actor system implements System interface
  124. type DefaultActorSystem struct {
  125. dispatchers map[string]IDispatcher
  126. actors map[string]*MailBox
  127. parentActors map[string][]string
  128. scheduler *grpool.Pool
  129. config *DefaultActorSystemConfig
  130. mu sync.Mutex
  131. }
  132. // DefaultActorSystemConfig system config
  133. type DefaultActorSystemConfig struct {
  134. SchedulerPoolSize int // 系统调度执行池大小
  135. AppDispatcherPoolSize int // 应用调度执行池大小
  136. TenantDispatcherPoolSize int // 租户执行池大小
  137. RuleEngineDispatcherPoolSize int // 规则引擎执行池大小
  138. }
  139. func NewDefaultActorSystem(config *DefaultActorSystemConfig) *DefaultActorSystem {
  140. return &DefaultActorSystem{
  141. dispatchers: make(map[string]IDispatcher),
  142. parentActors: make(map[string][]string),
  143. // scheduler: grpool.New(config.SchedulerPoolSize),
  144. config: config,
  145. actors: make(map[string]*MailBox),
  146. }
  147. }
  148. func (d *DefaultActorSystem) CreateDispatcher(name string, dispatcher IDispatcher) error {
  149. if _, ok := d.dispatchers[name]; ok {
  150. return errors.New(fmt.Sprintf("dispatcher name :%s is already registered!", name))
  151. }
  152. d.dispatchers[name] = dispatcher
  153. return nil
  154. }
  155. func (d *DefaultActorSystem) DestroyDispatcher(name string) error {
  156. if _, ok := d.dispatchers[name]; !ok {
  157. return errors.New(fmt.Sprintf("dispatcher %s is not registered!", name))
  158. }
  159. if err := d.dispatchers[name].Destroy(); err != nil {
  160. return err
  161. }
  162. delete(d.dispatchers, name)
  163. return nil
  164. }
  165. func (d *DefaultActorSystem) GetActor(actorId string) Ref {
  166. if ref, ok := d.actors[actorId]; !ok {
  167. return nil
  168. } else {
  169. return ref
  170. }
  171. }
  172. func (d *DefaultActorSystem) CreateRootActor(dispatcherName string, creator Creator) (Ref, error) {
  173. return d.creator(dispatcherName, creator, "")
  174. }
  175. func (d *DefaultActorSystem) Tell(actorId string, msg protocol.ActorMsg) error {
  176. return d.tell(actorId, msg, false)
  177. }
  178. func (d *DefaultActorSystem) TellWithHighPriority(actorId string, msg protocol.ActorMsg) error {
  179. return d.tell(actorId, msg, true)
  180. }
  181. func (d *DefaultActorSystem) tell(actorId string, msg protocol.ActorMsg, isHighPriority bool) error {
  182. if mailBox, ok := d.actors[actorId]; ok {
  183. if isHighPriority {
  184. mailBox.TellWithHighPriority(msg)
  185. } else {
  186. mailBox.Tell(msg)
  187. }
  188. } else {
  189. return errors.New(fmt.Sprintf("actor with id %s is not registered!", actorId))
  190. }
  191. return nil
  192. }
  193. func (d *DefaultActorSystem) stop(actorId string) error {
  194. children := d.parentActors[actorId]
  195. if len(children) > 0 {
  196. for _, child := range children {
  197. _ = d.stop(child)
  198. }
  199. }
  200. if m, found := d.actors[actorId]; found {
  201. return m.destroy()
  202. }
  203. return nil
  204. }
  205. func (d *DefaultActorSystem) StopActorById(actorId string) error {
  206. return d.stop(actorId)
  207. }
  208. func (d *DefaultActorSystem) StopActorByRef(ref Ref) error {
  209. return d.stop(ref.GetActorId())
  210. }
  211. func (d *DefaultActorSystem) BroadcastToChildren(parentActorId string, msg protocol.ActorMsg) error {
  212. children := d.parentActors[parentActorId]
  213. for _, item := range children {
  214. if err := d.Tell(item, msg); err != nil {
  215. return err
  216. }
  217. }
  218. return nil
  219. }
  220. func (d *DefaultActorSystem) CreateChildActor(dispatcherName string, creator Creator, parentId string) (Ref, error) {
  221. return d.creator(dispatcherName, creator, parentId)
  222. }
  223. func (d *DefaultActorSystem) creator(name string, creator Creator, parentId string) (Ref, error) {
  224. d.mu.Lock()
  225. defer d.mu.Unlock()
  226. dispatcher := d.dispatchers[name]
  227. if dispatcher == nil {
  228. return nil, errors.New(fmt.Sprintf("dispatcher %s not found!", name))
  229. }
  230. actorId := creator.CreateActorId()
  231. var actorMailBox *MailBox
  232. actorMailBox = d.actors[actorId]
  233. if actorMailBox != nil {
  234. server.Log.Debugf("actor with id :%s is already registered!", actorId)
  235. } else {
  236. server.Log.Debugf("creating actor with id :%s", actorId)
  237. actor := creator.CreateActor()
  238. var parentActor Ref
  239. if parentId != "" {
  240. parentActor = d.GetActor(parentId)
  241. if parentActor == nil {
  242. return nil, errors.New(fmt.Sprintf("Parent actor with id :%s is not registered!", parentId))
  243. }
  244. }
  245. mailBox := NewMailBox(d, actorId, parentActor, actor, dispatcher)
  246. d.actors[actorId] = mailBox
  247. if err := mailBox.Init(); err != nil {
  248. server.Log.Error(err)
  249. return nil, err
  250. }
  251. actorMailBox = mailBox
  252. if parentActor != nil {
  253. d.parentActors[parentId] = append(d.parentActors[parentId], actorId)
  254. }
  255. }
  256. return actorMailBox, nil
  257. }