ActorProxy.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using MongoDB.Bson.Serialization.Attributes;
  5. namespace Model
  6. {
  7. public abstract class ActorTask
  8. {
  9. [BsonIgnore]
  10. public ActorProxy proxy;
  11. [BsonElement]
  12. public AMessage message;
  13. public abstract Task<AResponse> Run();
  14. public abstract void RunFail(int error);
  15. }
  16. /// <summary>
  17. /// 普通消息,不需要response
  18. /// </summary>
  19. public class ActorMessageTask: ActorTask
  20. {
  21. public ActorMessageTask(ActorProxy proxy, AMessage message)
  22. {
  23. this.proxy = proxy;
  24. this.message = message;
  25. }
  26. public override async Task<AResponse> Run()
  27. {
  28. ActorRequest request = new ActorRequest() { Id = this.proxy.Id, AMessage = this.message };
  29. ActorResponse response = await this.proxy.RealCall<ActorResponse>(request, this.proxy.CancellationTokenSource.Token);
  30. return response;
  31. }
  32. public override void RunFail(int error)
  33. {
  34. }
  35. }
  36. /// <summary>
  37. /// Rpc消息,需要等待返回
  38. /// </summary>
  39. /// <typeparam name="Response"></typeparam>
  40. public class ActorRpcTask<Response> : ActorTask where Response: AResponse
  41. {
  42. [BsonIgnore]
  43. public readonly TaskCompletionSource<Response> Tcs = new TaskCompletionSource<Response>();
  44. public ActorRpcTask(ActorProxy proxy, ARequest message)
  45. {
  46. this.proxy = proxy;
  47. this.message = message;
  48. }
  49. public override async Task<AResponse> Run()
  50. {
  51. ActorRpcRequest request = new ActorRpcRequest() { Id = this.proxy.Id, AMessage = this.message };
  52. ActorRpcResponse response = await this.proxy.RealCall<ActorRpcResponse>(request, this.proxy.CancellationTokenSource.Token);
  53. if (response.Error != ErrorCode.ERR_NotFoundActor)
  54. {
  55. this.Tcs.SetResult((Response)response.AMessage);
  56. }
  57. return response;
  58. }
  59. public override void RunFail(int error)
  60. {
  61. this.Tcs.SetException(new RpcException(error, ""));
  62. }
  63. }
  64. [ObjectEvent]
  65. public class ActorProxyEvent : ObjectEvent<ActorProxy>, IAwake, IStart
  66. {
  67. public void Awake()
  68. {
  69. this.Get().Awake();
  70. }
  71. public void Start()
  72. {
  73. this.Get().Start();
  74. }
  75. }
  76. public sealed class ActorProxy : Entity
  77. {
  78. // actor的地址
  79. public string Address;
  80. // 已发送等待回应的消息
  81. public EQueue<ActorTask> RunningTasks;
  82. // 还没发送的消息
  83. public EQueue<ActorTask> WaitingTasks;
  84. // 发送窗口大小
  85. public int WindowSize = 1;
  86. // 最大窗口
  87. public const int MaxWindowSize = 1;
  88. private TaskCompletionSource<ActorTask> tcs;
  89. public CancellationTokenSource CancellationTokenSource;
  90. private int failTimes;
  91. public void Awake()
  92. {
  93. this.RunningTasks = new EQueue<ActorTask>();
  94. this.WaitingTasks = new EQueue<ActorTask>();
  95. this.WindowSize = 1;
  96. this.CancellationTokenSource = new CancellationTokenSource();
  97. }
  98. public void Start()
  99. {
  100. this.UpdateAsync();
  101. }
  102. private void Add(ActorTask task)
  103. {
  104. this.WaitingTasks.Enqueue(task);
  105. this.AllowGet();
  106. }
  107. private void Remove()
  108. {
  109. ActorTask task = this.RunningTasks.Dequeue();
  110. this.AllowGet();
  111. }
  112. private void AllowGet()
  113. {
  114. if (this.tcs == null || this.WaitingTasks.Count <= 0 || this.RunningTasks.Count >= this.WindowSize)
  115. {
  116. return;
  117. }
  118. ActorTask task = this.WaitingTasks.Dequeue();
  119. this.RunningTasks.Enqueue(task);
  120. var t = this.tcs;
  121. this.tcs = null;
  122. t.SetResult(task);
  123. }
  124. private Task<ActorTask> GetAsync()
  125. {
  126. if (this.WaitingTasks.Count > 0)
  127. {
  128. ActorTask task = this.WaitingTasks.Dequeue();
  129. this.RunningTasks.Enqueue(task);
  130. return Task.FromResult(task);
  131. }
  132. this.tcs = new TaskCompletionSource<ActorTask>();
  133. return this.tcs.Task;
  134. }
  135. private async void UpdateAsync()
  136. {
  137. if (this.Address == null)
  138. {
  139. int appId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(this.Id);
  140. this.Address = Game.Scene.GetComponent<StartConfigComponent>().Get(appId).GetComponent<InnerConfig>().Address;
  141. }
  142. while (true)
  143. {
  144. ActorTask actorTask = await this.GetAsync();
  145. this.RunTask(actorTask);
  146. }
  147. }
  148. private async void RunTask(ActorTask task)
  149. {
  150. try
  151. {
  152. AResponse response = await task.Run();
  153. // 如果没找到Actor,发送窗口减少为1,重试
  154. if (response.Error == ErrorCode.ERR_NotFoundActor)
  155. {
  156. this.CancellationTokenSource.Cancel();
  157. this.WindowSize = 1;
  158. ++this.failTimes;
  159. while (this.WaitingTasks.Count > 0)
  160. {
  161. ActorTask actorTask = this.WaitingTasks.Dequeue();
  162. this.RunningTasks.Enqueue(actorTask);
  163. }
  164. ObjectHelper.Swap(ref this.RunningTasks, ref this.WaitingTasks);
  165. // 失败3次则清空actor发送队列,返回失败
  166. if (this.failTimes > 3)
  167. {
  168. while (this.WaitingTasks.Count > 0)
  169. {
  170. ActorTask actorTask = this.WaitingTasks.Dequeue();
  171. actorTask.RunFail(response.Error);
  172. }
  173. return;
  174. }
  175. // 等待一会再发送
  176. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(this.failTimes * 500);
  177. int appId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(this.Id);
  178. this.Address = Game.Scene.GetComponent<StartConfigComponent>().Get(appId).GetComponent<InnerConfig>().Address;
  179. this.CancellationTokenSource = new CancellationTokenSource();
  180. this.AllowGet();
  181. return;
  182. }
  183. // 发送成功
  184. this.failTimes = 0;
  185. if (this.WindowSize < MaxWindowSize)
  186. {
  187. ++this.WindowSize;
  188. }
  189. this.Remove();
  190. }
  191. catch (Exception e)
  192. {
  193. Log.Error(e.ToString());
  194. }
  195. }
  196. public void Send(AMessage message)
  197. {
  198. ActorMessageTask task = new ActorMessageTask(this, message);
  199. this.Add(task);
  200. }
  201. public Task<Response> Call<Response>(ARequest request)where Response : AResponse
  202. {
  203. ActorRpcTask<Response> task = new ActorRpcTask<Response>(this, request);
  204. this.Add(task);
  205. return task.Tcs.Task;
  206. }
  207. public async Task<Response> RealCall<Response>(ActorRequest request, CancellationToken cancellationToken) where Response: AResponse
  208. {
  209. try
  210. {
  211. //Log.Debug($"realcall {MongoHelper.ToJson(request)} {this.Address}");
  212. request.Id = this.Id;
  213. Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(this.Address);
  214. Response response = await session.Call<Response>(request, cancellationToken);
  215. return response;
  216. }
  217. catch (RpcException e)
  218. {
  219. Log.Error($"{this.Address} {e}");
  220. throw;
  221. }
  222. }
  223. public string DebugQueue(EQueue<ActorTask> tasks)
  224. {
  225. string s = "";
  226. foreach (ActorTask task in tasks)
  227. {
  228. s += $" {task.message.GetType().Name}";
  229. }
  230. return s;
  231. }
  232. public override void Dispose()
  233. {
  234. if (this.Id == 0)
  235. {
  236. return;
  237. }
  238. base.Dispose();
  239. }
  240. }
  241. }