route.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package simple
  2. import (
  3. cfacade "github.com/mhaya/facade"
  4. clog "github.com/mhaya/logger"
  5. cproto "github.com/mhaya/net/proto"
  6. )
  7. var (
  8. nodeRouteMap = map[uint32]*NodeRoute{}
  9. onDataRouteFunc = DefaultDataRoute
  10. )
  11. type (
  12. NodeRoute struct {
  13. NodeType string
  14. ActorID string
  15. FuncName string
  16. }
  17. DataRouteFunc func(agent *Agent, msg *Message, route *NodeRoute)
  18. )
  19. func AddNodeRoute(mid uint32, nodeRoute *NodeRoute) {
  20. if nodeRoute == nil {
  21. return
  22. }
  23. nodeRouteMap[mid] = nodeRoute
  24. }
  25. func GetNodeRoute(mid uint32) (*NodeRoute, bool) {
  26. routeActor, found := nodeRouteMap[mid]
  27. return routeActor, found
  28. }
  29. func DefaultDataRoute(agent *Agent, msg *Message, route *NodeRoute) {
  30. session := agent.session
  31. session.Mid = msg.MID
  32. // current node
  33. if agent.NodeType() == route.NodeType {
  34. targetPath := cfacade.NewChildPath(agent.NodeId(), route.ActorID, session.Sid)
  35. LocalDataRoute(agent, session, msg, route, targetPath)
  36. return
  37. }
  38. if !session.IsBind() {
  39. clog.Warnf("[sid = %s,uid = %d] Session is not bind with UID. failed to forward message.[route = %+v]",
  40. agent.SID(),
  41. agent.UID(),
  42. route,
  43. )
  44. return
  45. }
  46. member, found := agent.Discovery().Random(route.NodeType)
  47. if !found {
  48. return
  49. }
  50. targetPath := cfacade.NewPath(member.GetNodeId(), route.ActorID)
  51. ClusterLocalDataRoute(agent, session, msg, route, member.GetNodeId(), targetPath)
  52. }
  53. func LocalDataRoute(agent *Agent, session *cproto.Session, msg *Message, nodeRoute *NodeRoute, targetPath string) {
  54. message := cfacade.GetMessage()
  55. message.Source = session.AgentPath
  56. message.Target = targetPath
  57. message.FuncName = nodeRoute.FuncName
  58. message.Session = session
  59. message.Args = msg.Data
  60. agent.ActorSystem().PostLocal(&message)
  61. }
  62. func ClusterLocalDataRoute(agent *Agent, session *cproto.Session, msg *Message, nodeRoute *NodeRoute, nodeID, targetPath string) error {
  63. clusterPacket := cproto.GetClusterPacket()
  64. clusterPacket.SourcePath = session.AgentPath
  65. clusterPacket.TargetPath = targetPath
  66. clusterPacket.FuncName = nodeRoute.FuncName
  67. clusterPacket.Session = session // agent session
  68. clusterPacket.ArgBytes = msg.Data // packet -> message -> data
  69. return agent.Cluster().PublishLocal(nodeID, clusterPacket)
  70. }