Skip to content

Commit c5ca41c

Browse files
committed
Change metrics duration units to seconds. Fixes #1396
1 parent 8d56d85 commit c5ca41c

File tree

8 files changed

+39
-39
lines changed

8 files changed

+39
-39
lines changed

docs/content/diagnostics/metrics.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ Name | Type | Unit | Description
3434
--- | --- | --- | ---
3535
`db.client.connections.usage` | UpDownCounter | `{connection}` | The number of connections that are currently in the state described by the state tag.
3636
`db.client.connections.pending_requests` | UpDownCounter | `{request}` | The number of pending requests for an open connection, cumulative for the entire pool.
37-
`db.client.connections.create_time` | Histogram | `ms` | The time it took to create a new connection.
38-
`db.client.connections.use_time` | Histogram | `ms` | The time between borrowing a connection and returning it to the pool.
39-
`db.client.connections.wait_time` | Histogram | `ms` | The time it took to obtain an open connection from the pool.
37+
`db.client.connections.create_time` | Histogram | `s` | The time it took to create a new connection.
38+
`db.client.connections.use_time` | Histogram | `s` | The time between borrowing a connection and returning it to the pool.
39+
`db.client.connections.wait_time` | Histogram | `s` | The time it took to obtain an open connection from the pool.
4040
`db.client.connections.idle.max` | UpDownCounter | `{connection}` | The maximum number of idle open connections allowed; this corresponds to `MaximumPoolSize` in the connection string.
4141
`db.client.connections.idle.min` | UpDownCounter | `{connection}` | The minimum number of idle open connections allowed; this corresponds to `MinimumPoolSize` in the connection string.
4242
`db.client.connections.max` | UpDownCounter | `{connection}` | The maximum number of open connections allowed; this corresponds to `MaximumPoolSize` in the connection string.

src/MySqlConnector/Core/ConnectionPool.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
7272
if (ConnectionSettings.ConnectionReset || session.DatabaseOverride is not null)
7373
{
7474
if (timeoutMilliseconds != 0)
75-
session.SetTimeout(Math.Max(1, timeoutMilliseconds - (int) Utility.GetElapsedMilliseconds(startingTimestamp)));
75+
session.SetTimeout(Math.Max(1, timeoutMilliseconds - Utility.GetElapsedMilliseconds(startingTimestamp)));
7676
reuseSession = await session.TryResetConnectionAsync(ConnectionSettings, connection, ioBehavior, cancellationToken).ConfigureAwait(false);
7777
session.SetTimeout(Constants.InfiniteTimeout);
7878
}
@@ -104,7 +104,7 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
104104
Log.ReturningPooledSession(m_logger, Id, session.Id, leasedSessionsCountPooled);
105105

106106
session.LastLeasedTimestamp = Stopwatch.GetTimestamp();
107-
MetricsReporter.RecordWaitTime(this, Utility.GetElapsedMilliseconds(startingTimestamp, session.LastLeasedTimestamp));
107+
MetricsReporter.RecordWaitTime(this, Utility.GetElapsedSeconds(startingTimestamp, session.LastLeasedTimestamp));
108108
return session;
109109
}
110110
}
@@ -123,7 +123,7 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
123123
Log.ReturningNewSession(m_logger, Id, session.Id, leasedSessionsCountNew);
124124

125125
session.LastLeasedTimestamp = Stopwatch.GetTimestamp();
126-
MetricsReporter.RecordCreateTime(this, Utility.GetElapsedMilliseconds(startingTimestamp, session.LastLeasedTimestamp));
126+
MetricsReporter.RecordCreateTime(this, Utility.GetElapsedSeconds(startingTimestamp, session.LastLeasedTimestamp));
127127
return session;
128128
}
129129
catch (Exception ex)

src/MySqlConnector/Core/MetricsReporter.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ internal static class MetricsReporter
99
public static void RemoveIdle(ConnectionPool pool) => s_connectionsUsageCounter.Add(-1, pool.IdleStateTagList);
1010
public static void AddUsed(ConnectionPool pool) => s_connectionsUsageCounter.Add(1, pool.UsedStateTagList);
1111
public static void RemoveUsed(ConnectionPool pool) => s_connectionsUsageCounter.Add(-1, pool.UsedStateTagList);
12-
public static void RecordCreateTime(ConnectionPool pool, float milliseconds) => s_createTimeHistory.Record(milliseconds, pool.PoolNameTagList);
13-
public static void RecordUseTime(ConnectionPool pool, float milliseconds) => s_useTimeHistory.Record(milliseconds, pool.PoolNameTagList);
14-
public static void RecordWaitTime(ConnectionPool pool, float milliseconds) => s_waitTimeHistory.Record(milliseconds, pool.PoolNameTagList);
12+
public static void RecordCreateTime(ConnectionPool pool, double seconds) => s_createTimeHistory.Record(seconds, pool.PoolNameTagList);
13+
public static void RecordUseTime(ConnectionPool pool, double seconds) => s_useTimeHistory.Record(seconds, pool.PoolNameTagList);
14+
public static void RecordWaitTime(ConnectionPool pool, double seconds) => s_waitTimeHistory.Record(seconds, pool.PoolNameTagList);
1515

1616
public static void AddPendingRequest(ConnectionPool? pool)
1717
{
@@ -48,10 +48,10 @@ static IEnumerable<Measurement<int>> GetMinimumConnections() =>
4848
unit: "{connection}", description: "The number of connections that are currently in the state described by the state tag.");
4949
private static readonly UpDownCounter<int> s_pendingRequestsCounter = ActivitySourceHelper.Meter.CreateUpDownCounter<int>("db.client.connections.pending_requests",
5050
unit: "{request}", description: "The number of pending requests for an open connection, cumulative for the entire pool.");
51-
private static readonly Histogram<float> s_createTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<float>("db.client.connections.create_time",
52-
unit: "ms", description: "The time it took to create a new connection.");
53-
private static readonly Histogram<float> s_useTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<float>("db.client.connections.use_time",
54-
unit: "ms", description: "The time between borrowing a connection and returning it to the pool.");
55-
private static readonly Histogram<float> s_waitTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<float>("db.client.connections.wait_time",
56-
unit: "ms", description: "The time it took to obtain an open connection from the pool.");
51+
private static readonly Histogram<double> s_createTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<double>("db.client.connections.create_time",
52+
unit: "s", description: "The time it took to create a new connection.");
53+
private static readonly Histogram<double> s_useTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<double>("db.client.connections.use_time",
54+
unit: "s", description: "The time between borrowing a connection and returning it to the pool.");
55+
private static readonly Histogram<double> s_waitTimeHistory = ActivitySourceHelper.Meter.CreateHistogram<double>("db.client.connections.wait_time",
56+
unit: "s", description: "The time it took to obtain an open connection from the pool.");
5757
}

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public ValueTask ReturnToPoolAsync(IOBehavior ioBehavior, MySqlConnection? ownin
7878
LastReturnedTimestamp = Stopwatch.GetTimestamp();
7979
if (Pool is null)
8080
return default;
81-
MetricsReporter.RecordUseTime(Pool, Utility.GetElapsedMilliseconds(LastLeasedTimestamp, LastReturnedTimestamp));
81+
MetricsReporter.RecordUseTime(Pool, Utility.GetElapsedSeconds(LastLeasedTimestamp, LastReturnedTimestamp));
8282
LastLeasedTimestamp = 0;
8383
return Pool.ReturnAsync(ioBehavior, this);
8484
}
@@ -456,7 +456,7 @@ public async Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancella
456456

457457
var byteHandler = m_socket is null ? new StreamByteHandler(m_stream!) : (IByteHandler) new SocketByteHandler(m_socket);
458458
if (cs.ConnectionTimeout != 0)
459-
byteHandler.RemainingTimeout = Math.Max(1, cs.ConnectionTimeoutMilliseconds - (int) Utility.GetElapsedMilliseconds(startingTimestamp));
459+
byteHandler.RemainingTimeout = Math.Max(1, cs.ConnectionTimeoutMilliseconds - Utility.GetElapsedMilliseconds(startingTimestamp));
460460
m_payloadHandler = new StandardPayloadHandler(byteHandler);
461461

462462
payload = await ReceiveAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
@@ -1218,7 +1218,7 @@ private async Task<bool> OpenNamedPipeAsync(ConnectionSettings cs, long starting
12181218
}
12191219

12201220
var namedPipeStream = new NamedPipeClientStream(cs.HostNames![0], cs.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
1221-
var timeout = Math.Max(1, cs.ConnectionTimeoutMilliseconds - (int) Utility.GetElapsedMilliseconds(startingTimestamp));
1221+
var timeout = Math.Max(1, cs.ConnectionTimeoutMilliseconds - Utility.GetElapsedMilliseconds(startingTimestamp));
12221222
try
12231223
{
12241224
using (cancellationToken.Register(namedPipeStream.Dispose))

src/MySqlConnector/MySqlConnection.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -907,7 +907,7 @@ private async ValueTask<ServerSession> CreateSessionAsync(ConnectionPool? pool,
907907
// the cancellation token for connection is controlled by 'cancellationToken' (if it can be cancelled), ConnectionTimeout
908908
// (from the connection string, if non-zero), or a combination of both
909909
if (connectionSettings.ConnectionTimeout != 0)
910-
timeoutSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(Math.Max(1, connectionSettings.ConnectionTimeoutMilliseconds - (int) Utility.GetElapsedMilliseconds(startingTimestamp))));
910+
timeoutSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(Math.Max(1, connectionSettings.ConnectionTimeoutMilliseconds - Utility.GetElapsedMilliseconds(startingTimestamp))));
911911
if (cancellationToken.CanBeCanceled && timeoutSource is not null)
912912
linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutSource.Token);
913913
var connectToken = linkedSource?.Token ?? timeoutSource?.Token ?? cancellationToken;

src/MySqlConnector/Utilities/Utility.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -568,21 +568,21 @@ public static void GetOSDetails(out string? os, out string osDescription, out st
568568
/// <summary>
569569
/// Gets the elapsed time (in milliseconds) since the specified <paramref name="startingTimestamp"/> (which must be a value returned from <see cref="Stopwatch.GetTimestamp"/>.
570570
/// </summary>
571-
public static float GetElapsedMilliseconds(long startingTimestamp) =>
571+
public static int GetElapsedMilliseconds(long startingTimestamp) =>
572572
#if NET7_0_OR_GREATER
573-
(float) Stopwatch.GetElapsedTime(startingTimestamp).TotalMilliseconds;
573+
(int) Stopwatch.GetElapsedTime(startingTimestamp).TotalMilliseconds;
574574
#else
575-
GetElapsedMilliseconds(startingTimestamp, Stopwatch.GetTimestamp());
575+
(int) ((Stopwatch.GetTimestamp() - startingTimestamp) * 1000L / Stopwatch.Frequency);
576576
#endif
577577

578578
/// <summary>
579-
/// Gets the elapsed time (in milliseconds) between the specified <paramref name="startingTimestamp"/> and <paramref name="endingTimestamp"/>. (These must be values returned from <see cref="Stopwatch.GetTimestamp"/>.)
579+
/// Gets the elapsed time (in seconds) between the specified <paramref name="startingTimestamp"/> and <paramref name="endingTimestamp"/>. (These must be values returned from <see cref="Stopwatch.GetTimestamp"/>.)
580580
/// </summary>
581-
public static float GetElapsedMilliseconds(long startingTimestamp, long endingTimestamp) =>
581+
public static double GetElapsedSeconds(long startingTimestamp, long endingTimestamp) =>
582582
#if NET7_0_OR_GREATER
583-
(float) Stopwatch.GetElapsedTime(startingTimestamp, endingTimestamp).TotalMilliseconds;
583+
Stopwatch.GetElapsedTime(startingTimestamp, endingTimestamp).TotalSeconds;
584584
#else
585-
(endingTimestamp - startingTimestamp) * 1000.0f / Stopwatch.Frequency;
585+
(endingTimestamp - startingTimestamp) / (double) Stopwatch.Frequency;
586586
#endif
587587

588588
#if NET462

tests/MySqlConnector.Tests/Metrics/ConnectionTimeTests.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public async Task ConnectionTime()
1111
await connection.OpenAsync();
1212
var measurements = GetAndClearMeasurements("db.client.connections.create_time");
1313
var time = Assert.Single(measurements);
14-
Assert.InRange(time, 0, 300);
14+
Assert.InRange(time, 0, 0.3);
1515
}
1616

1717
[Fact(Skip = MetricsSkip)]
@@ -25,7 +25,7 @@ public async Task ConnectionTimeWithDelay()
2525
await connection.OpenAsync();
2626
var measurements = GetAndClearMeasurements("db.client.connections.create_time");
2727
var time = Assert.Single(measurements);
28-
Assert.InRange(time, 1000, 1300);
28+
Assert.InRange(time, 1.0, 1.3);
2929
}
3030

3131
[Fact(Skip = MetricsSkip)]
@@ -41,7 +41,7 @@ public async Task OpenFromPoolTime()
4141
await connection.OpenAsync();
4242
var measurements = GetAndClearMeasurements("db.client.connections.wait_time");
4343
var time = Assert.Single(measurements);
44-
Assert.InRange(time, 0, 200);
44+
Assert.InRange(time, 0, 0.2);
4545
}
4646

4747
[Fact(Skip = MetricsSkip)]
@@ -58,7 +58,7 @@ public async Task OpenFromPoolTimeWithDelay()
5858
await connection.OpenAsync();
5959
var measurements = GetAndClearMeasurements("db.client.connections.wait_time");
6060
var time = Assert.Single(measurements);
61-
Assert.InRange(time, 1000, 1200);
61+
Assert.InRange(time, 1.0, 1.2);
6262
}
6363

6464
[Fact(Skip = MetricsSkip)]
@@ -72,7 +72,7 @@ public async Task UseTime()
7272
connection.Close();
7373

7474
var time = Assert.Single(GetAndClearMeasurements("db.client.connections.use_time"));
75-
Assert.InRange(time, 0, 100);
75+
Assert.InRange(time, 0, 0.1);
7676
}
7777

7878
[Fact(Skip = MetricsSkip)]
@@ -87,6 +87,6 @@ public async Task UseTimeWithDelay()
8787
connection.Close();
8888

8989
var time = Assert.Single(GetAndClearMeasurements("db.client.connections.use_time"));
90-
Assert.InRange(time, 500, 600);
90+
Assert.InRange(time, 0.5, 0.6);
9191
}
9292
}

tests/MySqlConnector.Tests/Metrics/MetricsTestsBase.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public MetricsTestsBase()
2323
}
2424
};
2525
m_meterListener.SetMeasurementEventCallback<int>(OnMeasurementRecorded);
26-
m_meterListener.SetMeasurementEventCallback<float>(OnMeasurementRecorded);
26+
m_meterListener.SetMeasurementEventCallback<double>(OnMeasurementRecorded);
2727
m_meterListener.Start();
2828
}
2929

@@ -68,11 +68,11 @@ protected void AssertMeasurement(string name, int expected)
6868
Assert.Equal(expected, m_measurements.GetValueOrDefault(name));
6969
}
7070

71-
protected List<float> GetAndClearMeasurements(string name)
71+
protected List<double> GetAndClearMeasurements(string name)
7272
{
7373
if (!m_timeMeasurements.TryGetValue(name, out var list))
74-
list = new List<float>();
75-
m_timeMeasurements[name] = new List<float>();
74+
list = new();
75+
m_timeMeasurements[name] = new List<double>();
7676
return list;
7777
}
7878

@@ -96,7 +96,7 @@ private void OnMeasurementRecorded(Instrument instrument, int measurement, ReadO
9696
}
9797
}
9898

99-
private void OnMeasurementRecorded(Instrument instrument, float measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
99+
private void OnMeasurementRecorded(Instrument instrument, double measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
100100
{
101101
var (poolName, stateTag) = GetTags(tags);
102102
if (poolName != PoolName)
@@ -105,7 +105,7 @@ private void OnMeasurementRecorded(Instrument instrument, float measurement, Rea
105105
lock (m_timeMeasurements)
106106
{
107107
if (!m_timeMeasurements.TryGetValue(instrument.Name, out var list))
108-
list = m_timeMeasurements[instrument.Name] = new List<float>();
108+
list = m_timeMeasurements[instrument.Name] = new List<double>();
109109
list.Add(measurement);
110110
}
111111
}
@@ -126,6 +126,6 @@ private void OnMeasurementRecorded(Instrument instrument, float measurement, Rea
126126

127127

128128
private readonly Dictionary<string, int> m_measurements;
129-
private readonly Dictionary<string, List<float>> m_timeMeasurements;
129+
private readonly Dictionary<string, List<double>> m_timeMeasurements;
130130
private readonly MeterListener m_meterListener;
131131
}

0 commit comments

Comments
 (0)