AnsiRequestScheduler.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Manages <see cref="AnsiEscapeSequenceRequest"/> made to an <see cref="IAnsiResponseParser"/>.
  6. /// Ensures there are not 2+ outstanding requests with the same terminator, throttles request sends
  7. /// to prevent console becoming unresponsive and handles evicting ignored requests (no reply from
  8. /// terminal).
  9. /// </summary>
  10. public class AnsiRequestScheduler
  11. {
  12. private readonly IAnsiResponseParser _parser;
  13. /// <summary>
  14. /// Function for returning the current time. Use in unit tests to
  15. /// ensure repeatable tests.
  16. /// </summary>
  17. internal Func<DateTime> Now { get; set; }
  18. private readonly HashSet<Tuple<AnsiEscapeSequenceRequest, DateTime>> _queuedRequests = new ();
  19. internal IReadOnlyCollection<AnsiEscapeSequenceRequest> QueuedRequests => _queuedRequests.Select (r => r.Item1).ToList ();
  20. /// <summary>
  21. /// <para>
  22. /// Dictionary where key is ansi request terminator and value is when we last sent a request for
  23. /// this terminator. Combined with <see cref="_throttle"/> this prevents hammering the console
  24. /// with too many requests in sequence which can cause console to freeze as there is no space for
  25. /// regular screen drawing / mouse events etc to come in.
  26. /// </para>
  27. /// <para>
  28. /// When user exceeds the throttle, new requests accumulate in <see cref="_queuedRequests"/> (i.e. remain
  29. /// queued).
  30. /// </para>
  31. /// </summary>
  32. private readonly ConcurrentDictionary<string, DateTime> _lastSend = new ();
  33. /// <summary>
  34. /// Number of milliseconds after sending a request that we allow
  35. /// another request to go out.
  36. /// </summary>
  37. private readonly TimeSpan _throttle = TimeSpan.FromMilliseconds (100);
  38. private readonly TimeSpan _runScheduleThrottle = TimeSpan.FromMilliseconds (100);
  39. /// <summary>
  40. /// If console has not responded to a request after this period of time, we assume that it is never going
  41. /// to respond. Only affects when we try to send a new request with the same terminator - at which point
  42. /// we tell the parser to stop expecting the old request and start expecting the new request.
  43. /// </summary>
  44. private readonly TimeSpan _staleTimeout = TimeSpan.FromSeconds (1);
  45. private readonly DateTime _lastRun;
  46. /// <summary>
  47. /// Creates a new instance.
  48. /// </summary>
  49. /// <param name="parser"></param>
  50. /// <param name="now"></param>
  51. public AnsiRequestScheduler (IAnsiResponseParser parser, Func<DateTime>? now = null)
  52. {
  53. _parser = parser;
  54. Now = now ?? (() => DateTime.Now);
  55. _lastRun = Now ();
  56. }
  57. /// <summary>
  58. /// Sends the <paramref name="request"/> immediately or queues it if there is already
  59. /// an outstanding request for the given <see cref="AnsiEscapeSequence.Terminator"/>.
  60. /// </summary>
  61. /// <param name="request"></param>
  62. /// <returns><see langword="true"/> if request was sent immediately. <see langword="false"/> if it was queued.</returns>
  63. public bool SendOrSchedule (AnsiEscapeSequenceRequest request) { return SendOrSchedule (request, true); }
  64. private bool SendOrSchedule (AnsiEscapeSequenceRequest request, bool addToQueue)
  65. {
  66. if (CanSend (request, out ReasonCannotSend reason))
  67. {
  68. Send (request);
  69. return true;
  70. }
  71. if (reason == ReasonCannotSend.OutstandingRequest)
  72. {
  73. // If we can evict an old request (no response from terminal after ages)
  74. if (EvictStaleRequests (request.Terminator))
  75. {
  76. // Try again after evicting
  77. if (CanSend (request, out _))
  78. {
  79. Send (request);
  80. return true;
  81. }
  82. }
  83. }
  84. if (addToQueue)
  85. {
  86. _queuedRequests.Add (Tuple.Create (request, Now ()));
  87. }
  88. return false;
  89. }
  90. private void EvictStaleRequests ()
  91. {
  92. foreach (string? stale in _lastSend.Where (v => IsStale (v.Value)).Select (k => k.Key))
  93. {
  94. EvictStaleRequests (stale);
  95. }
  96. }
  97. private bool IsStale (DateTime dt) { return Now () - dt > _staleTimeout; }
  98. /// <summary>
  99. /// Looks to see if the last time we sent <paramref name="withTerminator"/>
  100. /// is a long time ago. If so we assume that we will never get a response and
  101. /// can proceed with a new request for this terminator (returning <see langword="true"/>).
  102. /// </summary>
  103. /// <param name="withTerminator"></param>
  104. /// <returns></returns>
  105. private bool EvictStaleRequests (string? withTerminator)
  106. {
  107. if (_lastSend.TryGetValue (withTerminator!, out DateTime dt))
  108. {
  109. if (IsStale (dt))
  110. {
  111. _parser.StopExpecting (withTerminator, false);
  112. return true;
  113. }
  114. }
  115. return false;
  116. }
  117. /// <summary>
  118. /// Identifies and runs any <see cref="_queuedRequests"/> that can be sent based on the
  119. /// current outstanding requests of the parser.
  120. /// </summary>
  121. /// <param name="force">
  122. /// Repeated requests to run the schedule over short period of time will be ignored.
  123. /// Pass <see langword="true"/> to override this behaviour and force evaluation of outstanding requests.
  124. /// </param>
  125. /// <returns>
  126. /// <see langword="true"/> if a request was found and run. <see langword="false"/>
  127. /// if no outstanding requests or all have existing outstanding requests underway in parser.
  128. /// </returns>
  129. public bool RunSchedule (bool force = false)
  130. {
  131. if (!force && Now () - _lastRun < _runScheduleThrottle)
  132. {
  133. return false;
  134. }
  135. // Get oldest request
  136. Tuple<AnsiEscapeSequenceRequest, DateTime>? opportunity = _queuedRequests.MinBy (r => r.Item2);
  137. if (opportunity != null)
  138. {
  139. // Give it another go
  140. if (SendOrSchedule (opportunity.Item1, false))
  141. {
  142. _queuedRequests.Remove (opportunity);
  143. return true;
  144. }
  145. }
  146. EvictStaleRequests ();
  147. return false;
  148. }
  149. private void Send (AnsiEscapeSequenceRequest r)
  150. {
  151. _lastSend.AddOrUpdate (r.Terminator!, _ => Now (), (_, _) => Now ());
  152. _parser.ExpectResponse (r.Terminator, r.ResponseReceived, r.Abandoned, false);
  153. r.Send ();
  154. }
  155. private bool CanSend (AnsiEscapeSequenceRequest r, out ReasonCannotSend reason)
  156. {
  157. if (ShouldThrottle (r))
  158. {
  159. reason = ReasonCannotSend.TooManyRequests;
  160. return false;
  161. }
  162. if (_parser.IsExpecting (r.Terminator))
  163. {
  164. reason = ReasonCannotSend.OutstandingRequest;
  165. return false;
  166. }
  167. reason = default (ReasonCannotSend);
  168. return true;
  169. }
  170. private bool ShouldThrottle (AnsiEscapeSequenceRequest r)
  171. {
  172. if (_lastSend.TryGetValue (r.Terminator!, out DateTime value))
  173. {
  174. return Now () - value < _throttle;
  175. }
  176. return false;
  177. }
  178. }