AnsiRequestScheduler.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System.Collections.Concurrent;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Manages <see cref="AnsiEscapeSequenceRequest"/> made to an <see cref="IAnsiResponseParser"/>.
  5. /// Ensures there are not 2+ outstanding requests with the same terminator, throttles request sends
  6. /// to prevent console becoming unresponsive and handles evicting ignored requests (no reply from
  7. /// terminal).
  8. /// </summary>
  9. public class AnsiRequestScheduler
  10. {
  11. private readonly IAnsiResponseParser _parser;
  12. /// <summary>
  13. /// Function for returning the current time. Use in unit tests to
  14. /// ensure repeatable tests.
  15. /// </summary>
  16. internal Func<DateTime> Now { get; set; }
  17. private readonly HashSet<Tuple<AnsiEscapeSequenceRequest, DateTime>> _queuedRequests = new ();
  18. internal IReadOnlyCollection<AnsiEscapeSequenceRequest> QueuedRequests => _queuedRequests.Select (r => r.Item1).ToList ();
  19. /// <summary>
  20. /// <para>
  21. /// Dictionary where key is ansi request terminator and value is when we last sent a request for
  22. /// this terminator. Combined with <see cref="_throttle"/> this prevents hammering the console
  23. /// with too many requests in sequence which can cause console to freeze as there is no space for
  24. /// regular screen drawing / mouse events etc to come in.
  25. /// </para>
  26. /// <para>
  27. /// When user exceeds the throttle, new requests accumulate in <see cref="_queuedRequests"/> (i.e. remain
  28. /// queued).
  29. /// </para>
  30. /// </summary>
  31. private readonly ConcurrentDictionary<string, DateTime> _lastSend = new ();
  32. /// <summary>
  33. /// Number of milliseconds after sending a request that we allow
  34. /// another request to go out.
  35. /// </summary>
  36. private readonly TimeSpan _throttle = TimeSpan.FromMilliseconds (100);
  37. private readonly TimeSpan _runScheduleThrottle = TimeSpan.FromMilliseconds (100);
  38. /// <summary>
  39. /// If console has not responded to a request after this period of time, we assume that it is never going
  40. /// to respond. Only affects when we try to send a new request with the same terminator - at which point
  41. /// we tell the parser to stop expecting the old request and start expecting the new request.
  42. /// </summary>
  43. private readonly TimeSpan _staleTimeout = TimeSpan.FromSeconds (1);
  44. private readonly DateTime _lastRun;
  45. /// <summary>
  46. /// Creates a new instance.
  47. /// </summary>
  48. /// <param name="parser"></param>
  49. /// <param name="now"></param>
  50. public AnsiRequestScheduler (IAnsiResponseParser parser, Func<DateTime>? now = null)
  51. {
  52. _parser = parser;
  53. Now = now ?? (() => DateTime.Now);
  54. _lastRun = Now ();
  55. }
  56. /// <summary>
  57. /// Sends the <paramref name="request"/> immediately or queues it if there is already
  58. /// an outstanding request for the given <see cref="AnsiEscapeSequence.Terminator"/>.
  59. /// </summary>
  60. /// <param name="driver"></param>
  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 (IDriver? driver, AnsiEscapeSequenceRequest request) { return SendOrSchedule (driver, request, true); }
  64. private bool SendOrSchedule (IDriver? driver, AnsiEscapeSequenceRequest request, bool addToQueue)
  65. {
  66. if (CanSend (request, out ReasonCannotSend reason))
  67. {
  68. Send (driver, 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 (driver, 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="driver"></param>
  122. /// <param name="force">
  123. /// Repeated requests to run the schedule over short period of time will be ignored.
  124. /// Pass <see langword="true"/> to override this behaviour and force evaluation of outstanding requests.
  125. /// </param>
  126. /// <returns>
  127. /// <see langword="true"/> if a request was found and run. <see langword="false"/>
  128. /// if no outstanding requests or all have existing outstanding requests underway in parser.
  129. /// </returns>
  130. public bool RunSchedule (IDriver? driver, bool force = false)
  131. {
  132. if (!force && Now () - _lastRun < _runScheduleThrottle)
  133. {
  134. return false;
  135. }
  136. // Get oldest request
  137. Tuple<AnsiEscapeSequenceRequest, DateTime>? opportunity = _queuedRequests.MinBy (r => r.Item2);
  138. if (opportunity != null)
  139. {
  140. // Give it another go
  141. if (SendOrSchedule (driver, opportunity.Item1, false))
  142. {
  143. _queuedRequests.Remove (opportunity);
  144. return true;
  145. }
  146. }
  147. EvictStaleRequests ();
  148. return false;
  149. }
  150. private void Send (IDriver? driver, AnsiEscapeSequenceRequest r)
  151. {
  152. _lastSend.AddOrUpdate (r.Terminator!, _ => Now (), (_, _) => Now ());
  153. _parser.ExpectResponse (r.Terminator, r.ResponseReceived, r.Abandoned, false);
  154. r.Send (driver);
  155. }
  156. private bool CanSend (AnsiEscapeSequenceRequest r, out ReasonCannotSend reason)
  157. {
  158. if (ShouldThrottle (r))
  159. {
  160. reason = ReasonCannotSend.TooManyRequests;
  161. return false;
  162. }
  163. if (_parser.IsExpecting (r.Terminator))
  164. {
  165. reason = ReasonCannotSend.OutstandingRequest;
  166. return false;
  167. }
  168. reason = default (ReasonCannotSend);
  169. return true;
  170. }
  171. private bool ShouldThrottle (AnsiEscapeSequenceRequest r)
  172. {
  173. if (_lastSend.TryGetValue (r.Terminator!, out DateTime value))
  174. {
  175. return Now () - value < _throttle;
  176. }
  177. return false;
  178. }
  179. }