AnsiRequestScheduler.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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="request"></param>
  61. /// <returns><see langword="true"/> if request was sent immediately. <see langword="false"/> if it was queued.</returns>
  62. public bool SendOrSchedule (AnsiEscapeSequenceRequest request) { return SendOrSchedule (request, true); }
  63. private bool SendOrSchedule (AnsiEscapeSequenceRequest request, bool addToQueue)
  64. {
  65. if (CanSend (request, out ReasonCannotSend reason))
  66. {
  67. Send (request);
  68. return true;
  69. }
  70. if (reason == ReasonCannotSend.OutstandingRequest)
  71. {
  72. // If we can evict an old request (no response from terminal after ages)
  73. if (EvictStaleRequests (request.Terminator))
  74. {
  75. // Try again after evicting
  76. if (CanSend (request, out _))
  77. {
  78. Send (request);
  79. return true;
  80. }
  81. }
  82. }
  83. if (addToQueue)
  84. {
  85. _queuedRequests.Add (Tuple.Create (request, Now ()));
  86. }
  87. return false;
  88. }
  89. private void EvictStaleRequests ()
  90. {
  91. foreach (string? stale in _lastSend.Where (v => IsStale (v.Value)).Select (k => k.Key))
  92. {
  93. EvictStaleRequests (stale);
  94. }
  95. }
  96. private bool IsStale (DateTime dt) { return Now () - dt > _staleTimeout; }
  97. /// <summary>
  98. /// Looks to see if the last time we sent <paramref name="withTerminator"/>
  99. /// is a long time ago. If so we assume that we will never get a response and
  100. /// can proceed with a new request for this terminator (returning <see langword="true"/>).
  101. /// </summary>
  102. /// <param name="withTerminator"></param>
  103. /// <returns></returns>
  104. private bool EvictStaleRequests (string? withTerminator)
  105. {
  106. if (_lastSend.TryGetValue (withTerminator!, out DateTime dt))
  107. {
  108. if (IsStale (dt))
  109. {
  110. _parser.StopExpecting (withTerminator, false);
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. /// <summary>
  117. /// Identifies and runs any <see cref="_queuedRequests"/> that can be sent based on the
  118. /// current outstanding requests of the parser.
  119. /// </summary>
  120. /// <param name="force">
  121. /// Repeated requests to run the schedule over short period of time will be ignored.
  122. /// Pass <see langword="true"/> to override this behaviour and force evaluation of outstanding requests.
  123. /// </param>
  124. /// <returns>
  125. /// <see langword="true"/> if a request was found and run. <see langword="false"/>
  126. /// if no outstanding requests or all have existing outstanding requests underway in parser.
  127. /// </returns>
  128. public bool RunSchedule (bool force = false)
  129. {
  130. if (!force && Now () - _lastRun < _runScheduleThrottle)
  131. {
  132. return false;
  133. }
  134. // Get oldest request
  135. Tuple<AnsiEscapeSequenceRequest, DateTime>? opportunity = _queuedRequests.MinBy (r => r.Item2);
  136. if (opportunity != null)
  137. {
  138. // Give it another go
  139. if (SendOrSchedule (opportunity.Item1, false))
  140. {
  141. _queuedRequests.Remove (opportunity);
  142. return true;
  143. }
  144. }
  145. EvictStaleRequests ();
  146. return false;
  147. }
  148. private void Send (AnsiEscapeSequenceRequest r)
  149. {
  150. _lastSend.AddOrUpdate (r.Terminator!, _ => Now (), (_, _) => Now ());
  151. _parser.ExpectResponse (r.Terminator, r.ResponseReceived, r.Abandoned, false);
  152. r.Send ();
  153. }
  154. private bool CanSend (AnsiEscapeSequenceRequest r, out ReasonCannotSend reason)
  155. {
  156. if (ShouldThrottle (r))
  157. {
  158. reason = ReasonCannotSend.TooManyRequests;
  159. return false;
  160. }
  161. if (_parser.IsExpecting (r.Terminator))
  162. {
  163. reason = ReasonCannotSend.OutstandingRequest;
  164. return false;
  165. }
  166. reason = default (ReasonCannotSend);
  167. return true;
  168. }
  169. private bool ShouldThrottle (AnsiEscapeSequenceRequest r)
  170. {
  171. if (_lastSend.TryGetValue (r.Terminator!, out DateTime value))
  172. {
  173. return Now () - value < _throttle;
  174. }
  175. return false;
  176. }
  177. }