ActorProxy.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 : Disposer
  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. // 最近发送消息的时间
  89. public long LastSendTime;
  90. private TaskCompletionSource<ActorTask> tcs;
  91. public CancellationTokenSource CancellationTokenSource;
  92. private int failTimes;
  93. public void Awake()
  94. {
  95. this.LastSendTime = TimeHelper.Now();
  96. this.RunningTasks = new EQueue<ActorTask>();
  97. this.WaitingTasks = new EQueue<ActorTask>();
  98. this.WindowSize = 1;
  99. this.CancellationTokenSource = new CancellationTokenSource();
  100. }
  101. public void Start()
  102. {
  103. this.UpdateAsync();
  104. }
  105. private void Add(ActorTask task)
  106. {
  107. this.WaitingTasks.Enqueue(task);
  108. this.AllowGet();
  109. }
  110. private void Remove()
  111. {
  112. this.RunningTasks.Dequeue();
  113. this.AllowGet();
  114. }
  115. private void AllowGet()
  116. {
  117. if (this.tcs == null || this.WaitingTasks.Count <= 0 || this.RunningTasks.Count >= this.WindowSize)
  118. {
  119. return;
  120. }
  121. ActorTask task = this.WaitingTasks.Dequeue();
  122. this.RunningTasks.Enqueue(task);
  123. var t = this.tcs;
  124. this.tcs = null;
  125. t.SetResult(task);
  126. }
  127. private Task<ActorTask> GetAsync()
  128. {
  129. if (this.WaitingTasks.Count > 0)
  130. {
  131. ActorTask task = this.WaitingTasks.Dequeue();
  132. this.RunningTasks.Enqueue(task);
  133. return Task.FromResult(task);
  134. }
  135. this.tcs = new TaskCompletionSource<ActorTask>();
  136. return this.tcs.Task;
  137. }
  138. private async void UpdateAsync()
  139. {
  140. if (this.Address == null)
  141. {
  142. int appId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(this.Id);
  143. this.Address = Game.Scene.GetComponent<StartConfigComponent>().Get(appId).GetComponent<InnerConfig>().Address;
  144. }
  145. while (true)
  146. {
  147. if (this.Id == 0)
  148. {
  149. return;
  150. }
  151. ActorTask actorTask = await this.GetAsync();
  152. if (actorTask == null)
  153. {
  154. return;
  155. }
  156. try
  157. {
  158. this.RunTask(actorTask);
  159. }
  160. catch (Exception e)
  161. {
  162. Log.Error(e.ToString());
  163. return;
  164. }
  165. }
  166. }
  167. private async void RunTask(ActorTask task)
  168. {
  169. try
  170. {
  171. AResponse response = await task.Run();
  172. // 如果没找到Actor,发送窗口减少为1,重试
  173. if (response.Error == ErrorCode.ERR_NotFoundActor)
  174. {
  175. this.CancellationTokenSource.Cancel();
  176. this.WindowSize = 1;
  177. ++this.failTimes;
  178. while (this.WaitingTasks.Count > 0)
  179. {
  180. ActorTask actorTask = this.WaitingTasks.Dequeue();
  181. this.RunningTasks.Enqueue(actorTask);
  182. }
  183. ObjectHelper.Swap(ref this.RunningTasks, ref this.WaitingTasks);
  184. // 失败3次则清空actor发送队列,返回失败
  185. if (this.failTimes > 3)
  186. {
  187. while (this.WaitingTasks.Count > 0)
  188. {
  189. ActorTask actorTask = this.WaitingTasks.Dequeue();
  190. actorTask.RunFail(response.Error);
  191. }
  192. // 失败直接删除actorproxy
  193. Game.Scene.GetComponent<ActorProxyComponent>().Remove(this.Id);
  194. return;
  195. }
  196. // 等待一会再发送
  197. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(this.failTimes * 500);
  198. int appId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(this.Id);
  199. this.Address = Game.Scene.GetComponent<StartConfigComponent>().Get(appId).GetComponent<InnerConfig>().Address;
  200. this.CancellationTokenSource = new CancellationTokenSource();
  201. this.AllowGet();
  202. return;
  203. }
  204. // 发送成功
  205. this.failTimes = 0;
  206. if (this.WindowSize < MaxWindowSize)
  207. {
  208. ++this.WindowSize;
  209. }
  210. this.Remove();
  211. }
  212. catch (Exception e)
  213. {
  214. Log.Error(e.ToString());
  215. }
  216. }
  217. public void Send(AMessage message)
  218. {
  219. this.LastSendTime = TimeHelper.Now();
  220. ActorMessageTask task = new ActorMessageTask(this, message);
  221. this.Add(task);
  222. }
  223. public Task<Response> Call<Response>(ARequest request)where Response : AResponse
  224. {
  225. this.LastSendTime = TimeHelper.Now();
  226. ActorRpcTask<Response> task = new ActorRpcTask<Response>(this, request);
  227. this.Add(task);
  228. return task.Tcs.Task;
  229. }
  230. public async Task<Response> RealCall<Response>(ActorRequest request, CancellationToken cancellationToken) where Response: AResponse
  231. {
  232. try
  233. {
  234. //Log.Debug($"realcall {MongoHelper.ToJson(request)} {this.Address}");
  235. request.Id = this.Id;
  236. Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(this.Address);
  237. Response response = await session.Call<Response>(request, cancellationToken);
  238. return response;
  239. }
  240. catch (RpcException e)
  241. {
  242. Log.Error($"{this.Address} {e}");
  243. throw;
  244. }
  245. }
  246. public string DebugQueue(EQueue<ActorTask> tasks)
  247. {
  248. string s = "";
  249. foreach (ActorTask task in tasks)
  250. {
  251. s += $" {task.message.GetType().Name}";
  252. }
  253. return s;
  254. }
  255. public override void Dispose()
  256. {
  257. if (this.Id == 0)
  258. {
  259. return;
  260. }
  261. base.Dispose();
  262. this.tcs?.SetResult(null);
  263. }
  264. }
  265. }