ActorProxy.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. 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. if (this.Id == 0)
  145. {
  146. return;
  147. }
  148. ActorTask actorTask = await this.GetAsync();
  149. if (actorTask == null)
  150. {
  151. return;
  152. }
  153. try
  154. {
  155. this.RunTask(actorTask);
  156. }
  157. catch (Exception e)
  158. {
  159. Log.Error(e.ToString());
  160. return;
  161. }
  162. }
  163. }
  164. private async void RunTask(ActorTask task)
  165. {
  166. try
  167. {
  168. AResponse response = await task.Run();
  169. // 如果没找到Actor,发送窗口减少为1,重试
  170. if (response.Error == ErrorCode.ERR_NotFoundActor)
  171. {
  172. this.CancellationTokenSource.Cancel();
  173. this.WindowSize = 1;
  174. ++this.failTimes;
  175. while (this.WaitingTasks.Count > 0)
  176. {
  177. ActorTask actorTask = this.WaitingTasks.Dequeue();
  178. this.RunningTasks.Enqueue(actorTask);
  179. }
  180. ObjectHelper.Swap(ref this.RunningTasks, ref this.WaitingTasks);
  181. // 失败3次则清空actor发送队列,返回失败
  182. if (this.failTimes > 3)
  183. {
  184. while (this.WaitingTasks.Count > 0)
  185. {
  186. ActorTask actorTask = this.WaitingTasks.Dequeue();
  187. actorTask.RunFail(response.Error);
  188. }
  189. // 失败直接删除actorproxy
  190. Game.Scene.GetComponent<ActorProxyComponent>().Remove(this.Id);
  191. return;
  192. }
  193. // 等待一会再发送
  194. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(this.failTimes * 500);
  195. int appId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(this.Id);
  196. this.Address = Game.Scene.GetComponent<StartConfigComponent>().Get(appId).GetComponent<InnerConfig>().Address;
  197. this.CancellationTokenSource = new CancellationTokenSource();
  198. this.AllowGet();
  199. return;
  200. }
  201. // 发送成功
  202. this.failTimes = 0;
  203. if (this.WindowSize < MaxWindowSize)
  204. {
  205. ++this.WindowSize;
  206. }
  207. this.Remove();
  208. }
  209. catch (Exception e)
  210. {
  211. Log.Error(e.ToString());
  212. }
  213. }
  214. public void Send(AMessage message)
  215. {
  216. ActorMessageTask task = new ActorMessageTask(this, message);
  217. this.Add(task);
  218. }
  219. public Task<Response> Call<Response>(ARequest request)where Response : AResponse
  220. {
  221. ActorRpcTask<Response> task = new ActorRpcTask<Response>(this, request);
  222. this.Add(task);
  223. return task.Tcs.Task;
  224. }
  225. public async Task<Response> RealCall<Response>(ActorRequest request, CancellationToken cancellationToken) where Response: AResponse
  226. {
  227. try
  228. {
  229. //Log.Debug($"realcall {MongoHelper.ToJson(request)} {this.Address}");
  230. request.Id = this.Id;
  231. Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(this.Address);
  232. Response response = await session.Call<Response>(request, cancellationToken);
  233. return response;
  234. }
  235. catch (RpcException e)
  236. {
  237. Log.Error($"{this.Address} {e}");
  238. throw;
  239. }
  240. }
  241. public string DebugQueue(EQueue<ActorTask> tasks)
  242. {
  243. string s = "";
  244. foreach (ActorTask task in tasks)
  245. {
  246. s += $" {task.message.GetType().Name}";
  247. }
  248. return s;
  249. }
  250. public override void Dispose()
  251. {
  252. if (this.Id == 0)
  253. {
  254. return;
  255. }
  256. base.Dispose();
  257. this.tcs?.SetResult(null);
  258. }
  259. }
  260. }