|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Threading; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using MySqlConnector.Logging; |
| 6 | +using MySqlConnector.Protocol.Serialization; |
| 7 | + |
| 8 | +namespace MySqlConnector.Core |
| 9 | +{ |
| 10 | + internal static class BackgroundConnectionResetHelper |
| 11 | + { |
| 12 | + public static void AddSession(ServerSession session, MySqlConnection? owningConnection) |
| 13 | + { |
| 14 | + var resetTask = session.TryResetConnectionAsync(session.Pool!.ConnectionSettings, IOBehavior.Asynchronous, default); |
| 15 | + lock (s_lock) |
| 16 | + s_sessions.Add(new SessionResetTask(session, resetTask, owningConnection)); |
| 17 | + |
| 18 | + if (Log.IsDebugEnabled()) |
| 19 | + Log.Debug("Started Session{0} reset in background; waiting SessionCount: {1}.", session.Id, s_sessions.Count); |
| 20 | + |
| 21 | + // release only if it is likely to succeed |
| 22 | + if (s_semaphore.CurrentCount == 0) |
| 23 | + { |
| 24 | + Log.Debug("Releasing semaphore."); |
| 25 | + try |
| 26 | + { |
| 27 | + s_semaphore.Release(); |
| 28 | + } |
| 29 | + catch (SemaphoreFullException) |
| 30 | + { |
| 31 | + // ignore |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public static void Start() |
| 37 | + { |
| 38 | + Log.Info("Starting BackgroundConnectionResetHelper worker."); |
| 39 | + lock (s_lock) |
| 40 | + { |
| 41 | + if (s_workerTask is null) |
| 42 | + s_workerTask = Task.Run(async () => await ReturnSessionsAsync()); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public static void Stop() |
| 47 | + { |
| 48 | + Log.Info("Stopping BackgroundConnectionResetHelper worker."); |
| 49 | + s_cancellationTokenSource.Cancel(); |
| 50 | + Task? workerTask; |
| 51 | + lock (s_lock) |
| 52 | + workerTask = s_workerTask; |
| 53 | + |
| 54 | + if (workerTask is not null) |
| 55 | + { |
| 56 | + try |
| 57 | + { |
| 58 | + workerTask.GetAwaiter().GetResult(); |
| 59 | + } |
| 60 | + catch (OperationCanceledException) |
| 61 | + { |
| 62 | + } |
| 63 | + } |
| 64 | + Log.Info("Stopped BackgroundConnectionResetHelper worker."); |
| 65 | + } |
| 66 | + |
| 67 | + public static async Task ReturnSessionsAsync() |
| 68 | + { |
| 69 | + Log.Info("Started BackgroundConnectionResetHelper worker."); |
| 70 | + |
| 71 | + List<Task<bool>> localTasks = new(); |
| 72 | + List<SessionResetTask> localSessions = new(); |
| 73 | + |
| 74 | + // keep running until stopped |
| 75 | + while (!s_cancellationTokenSource.IsCancellationRequested) |
| 76 | + { |
| 77 | + try |
| 78 | + { |
| 79 | + // block until AddSession releases the semaphore |
| 80 | + Log.Info("Waiting for semaphore."); |
| 81 | + await s_semaphore.WaitAsync(s_cancellationTokenSource.Token).ConfigureAwait(false); |
| 82 | + |
| 83 | + // process all sessions that have started being returned |
| 84 | + while (true) |
| 85 | + { |
| 86 | + lock (s_lock) |
| 87 | + { |
| 88 | + if (s_sessions.Count == 0) |
| 89 | + { |
| 90 | + if (localTasks.Count == 0) |
| 91 | + break; |
| 92 | + } |
| 93 | + else |
| 94 | + { |
| 95 | + foreach (var session in s_sessions) |
| 96 | + { |
| 97 | + localSessions.Add(session); |
| 98 | + localTasks.Add(session.ResetTask); |
| 99 | + } |
| 100 | + s_sessions.Clear(); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + if (Log.IsDebugEnabled()) |
| 105 | + Log.Debug("Found SessionCount {0} session(s) to return.", localSessions.Count); |
| 106 | + |
| 107 | + while (localTasks.Count != 0) |
| 108 | + { |
| 109 | + var completedTask = await Task.WhenAny(localTasks).ConfigureAwait(false); |
| 110 | + var index = localTasks.IndexOf(completedTask); |
| 111 | + var session = localSessions[index].Session; |
| 112 | + var connection = localSessions[index].OwningConnection; |
| 113 | + localSessions.RemoveAt(index); |
| 114 | + localTasks.RemoveAt(index); |
| 115 | + await session.Pool!.ReturnAsync(IOBehavior.Asynchronous, session).ConfigureAwait(false); |
| 116 | + GC.KeepAlive(connection); |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + catch (Exception ex) when (!(ex is OperationCanceledException oce && oce.CancellationToken == s_cancellationTokenSource.Token)) |
| 121 | + { |
| 122 | + Log.Error("Unhandled exception: {0}", ex); |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + internal struct SessionResetTask |
| 128 | + { |
| 129 | + public SessionResetTask(ServerSession session, Task<bool> resetTask, MySqlConnection? owningConnection) |
| 130 | + { |
| 131 | + Session = session; |
| 132 | + ResetTask = resetTask; |
| 133 | + OwningConnection = owningConnection; |
| 134 | + } |
| 135 | + |
| 136 | + public ServerSession Session { get; } |
| 137 | + public Task<bool> ResetTask { get; } |
| 138 | + public MySqlConnection? OwningConnection { get; } |
| 139 | + } |
| 140 | + |
| 141 | + static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(BackgroundConnectionResetHelper)); |
| 142 | + static readonly object s_lock = new(); |
| 143 | + static readonly SemaphoreSlim s_semaphore = new(1, 1); |
| 144 | + static readonly CancellationTokenSource s_cancellationTokenSource = new(); |
| 145 | + static readonly List<SessionResetTask> s_sessions = new(); |
| 146 | + static Task? s_workerTask; |
| 147 | + } |
| 148 | +} |
0 commit comments