ActorProxy.cs 7.3 KB

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