ActorProxy.cs 6.5 KB

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