Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
256ea2f
Adds FbTransactionInfo.GetTransactionId().
fdcastel Oct 25, 2024
7dd65e8
Adds .NET distributed tracing instrumentation.
fdcastel Oct 25, 2024
7fe1327
Add metrics.
fdcastel Oct 26, 2024
2968ea3
Fix NullReferenceException when StartActivity returns null
fdcastel Mar 23, 2026
9b25148
Fix Stopwatch elapsed time conversion
fdcastel Mar 23, 2026
c198a6a
Rename db.system to db.system.name per OTel semantic conventions v1.40+
fdcastel Mar 23, 2026
4781900
Set db.namespace attribute on spans from connection database name
fdcastel Mar 23, 2026
4f83e23
Set error.type attribute on failure spans
fdcastel Mar 23, 2026
78c6d3b
Gate db.query.text and db.query.parameter.* behind opt-in flags
fdcastel Mar 23, 2026
ecdb4cd
Read ActivitySource/Meter version from assembly metadata
fdcastel Mar 23, 2026
49382fb
Fix activity lifecycle: record metrics on error path, prevent stale r…
fdcastel Mar 23, 2026
594a23b
Remove non-standard and deprecated telemetry attributes
fdcastel Mar 23, 2026
f68747f
Add server.port, db.stored_procedure.name; fix server.address in metrics
fdcastel Mar 23, 2026
98f6f6d
Add db.query.summary and db.operation.name for Text commands
fdcastel Mar 23, 2026
4aa1e01
Add debug assertions in TraceCommandStop and TraceCommandException
fdcastel Mar 23, 2026
43d9462
Initialize MetricsConnectionAttributes to empty array
fdcastel Mar 23, 2026
425ae5a
Avoid dictionary allocation in observable metric callbacks
fdcastel Mar 23, 2026
395a907
Add InstrumentAdvice with histogram bucket boundaries on .NET 9+
fdcastel Mar 23, 2026
7402540
Add FbTelemetry public class with ActivitySource and Meter names
fdcastel Mar 23, 2026
36d884f
Add OpenTelemetry integration documentation
fdcastel Mar 23, 2026
ec1c68b
Fix IndexOfAny compilation on all target frameworks
fdcastel Mar 23, 2026
7b3e3a0
Refactor: Benchmarks.
fdcastel Oct 26, 2024
0c4a764
Updates run-benchmark.ps1.
fdcastel May 18, 2025
ed46d7a
Fix solution file: update benchmark project path and folder name
fdcastel Mar 23, 2026
04208fe
Add LargeFetchBenchmark for bulk read throughput across data types
fdcastel Mar 23, 2026
8fa39ed
Extract shared BenchmarkConfig to eliminate duplication
fdcastel Mar 23, 2026
5852c9a
Extract BenchmarkBase with shared ConnectionString and env-var override
fdcastel Mar 23, 2026
3ad15fa
Update benchmark toolchain from .NET 8 to .NET 10
fdcastel Mar 23, 2026
0ecaa3a
Add GitHub Markdown exporter and fastest-to-slowest ordering
fdcastel Mar 23, 2026
671604a
Replace single-value [Params] with constants
fdcastel Mar 23, 2026
32c46bb
Return values from Fetch benchmarks to prevent dead-code elimination
fdcastel Mar 23, 2026
3c3ce6e
Add async benchmark variants for Execute and Fetch
fdcastel Mar 23, 2026
c12627e
Add connection open/close benchmark
fdcastel Mar 23, 2026
6f9e2d8
Add -Disasm and -Profile flags to run-benchmark.ps1
fdcastel Mar 23, 2026
1ec795d
Fix build errors: remove duplicate braces, add missing using
fdcastel Mar 23, 2026
533d57c
Add benchmark documentation
fdcastel Mar 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Adds .NET distributed tracing instrumentation.
  • Loading branch information
fdcastel committed Mar 23, 2026
commit 7dd65e8320ebc1210dfa4c9e5a83524db3bef011
125 changes: 89 additions & 36 deletions src/FirebirdSql.Data.FirebirdClient/FirebirdClient/FbCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FirebirdSql.Data.Common;
using FirebirdSql.Data.Logging;
using FirebirdSql.Data.Trace;
using Microsoft.Extensions.Logging;

namespace FirebirdSql.Data.FirebirdClient;
Expand All @@ -50,6 +52,7 @@ public sealed class FbCommand : DbCommand, IFbPreparedCommand, IDescriptorFiller
private int? _commandTimeout;
private int _fetchSize;
private Type[] _expectedColumnTypes;
private Activity _currentActivity;

#endregion

Expand Down Expand Up @@ -1064,6 +1067,13 @@ internal void Release()
_statement.Dispose2();
_statement = null;
}

if (_currentActivity != null)
{
// Do not set status to Ok: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
_currentActivity.Dispose();
_currentActivity = null;
}
}
Task IFbPreparedCommand.ReleaseAsync(CancellationToken cancellationToken) => ReleaseAsync(cancellationToken);
internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
Expand All @@ -1082,6 +1092,13 @@ internal async Task ReleaseAsync(CancellationToken cancellationToken = default)
await _statement.Dispose2Async(cancellationToken).ConfigureAwait(false);
_statement = null;
}

if (_currentActivity != null)
{
// Do not set status to Ok: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
_currentActivity.Dispose();
_currentActivity = null;
}
}

void IFbPreparedCommand.TransactionCompleted() => TransactionCompleted();
Expand Down Expand Up @@ -1302,6 +1319,26 @@ private async ValueTask UpdateParameterValuesAsync(Descriptor descriptor, Cancel

#endregion

#region Tracing

private void TraceCommandStart()
{
Debug.Assert(_currentActivity == null);
if (FbActivitySource.Source.HasListeners())
_currentActivity = FbActivitySource.CommandStart(this);
}

private void TraceCommandException(Exception e)
{
if (_currentActivity != null)
{
FbActivitySource.CommandException(_currentActivity, e);
_currentActivity = null;
}
}

#endregion Tracing

#region Private Methods

private void Prepare(bool returnsSet)
Expand Down Expand Up @@ -1446,57 +1483,73 @@ private async Task PrepareAsync(bool returnsSet, CancellationToken cancellationT
private void ExecuteCommand(CommandBehavior behavior, bool returnsSet)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
Prepare(returnsSet);

Prepare(returnsSet);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
_statement.Execute(CommandTimeout * 1000, this);
}

// Execute
_statement.Execute(CommandTimeout * 1000, this);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}
private async Task ExecuteCommandAsync(CommandBehavior behavior, bool returnsSet, CancellationToken cancellationToken = default)
{
LogMessages.CommandExecution(Log, this);
TraceCommandStart();
try
{
await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);

await PrepareAsync(returnsSet, cancellationToken).ConfigureAwait(false);
if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;

if ((behavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess ||
(behavior & CommandBehavior.SingleResult) == CommandBehavior.SingleResult ||
(behavior & CommandBehavior.SingleRow) == CommandBehavior.SingleRow ||
(behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection ||
behavior == CommandBehavior.Default)
{
// Set the fetch size
_statement.FetchSize = _fetchSize;
// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;

// Set if it's needed the Records Affected information
_statement.ReturnRecordsAffected = _connection.ConnectionOptions.ReturnRecordsAffected;
// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
}

// Validate input parameter count
if (_namedParameters.Count > 0 && !HasParameters)
{
throw FbException.Create("Must declare command parameters.");
// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}

// Execute
await _statement.ExecuteAsync(CommandTimeout * 1000, this, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
TraceCommandException(e);
throw;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" />
</ItemGroup>
<Import Project="..\FirebirdSql.Data.External\FirebirdSql.Data.External.projitems" Label="Shared" />
</Project>
137 changes: 137 additions & 0 deletions src/FirebirdSql.Data.FirebirdClient/Trace/FbActivitySource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using FirebirdSql.Data.FirebirdClient;

namespace FirebirdSql.Data.Trace
{
internal static class FbActivitySource
{
internal static readonly ActivitySource Source = new("FirebirdSql.Data", "1.0.0");

internal static Activity CommandStart(FbCommand command)
{
// Reference: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/database/database-spans.md
var dbName = command.Connection.Database;

string dbOperationName = null;
string dbCollectionName = null;
string activityName;

switch (command.CommandType)
{
case CommandType.StoredProcedure:
dbOperationName = "EXECUTE PROCEDURE";
activityName = $"{dbOperationName} {command.CommandText}";
break;

case CommandType.TableDirect:
dbOperationName = "SELECT";
dbCollectionName = command.CommandText;
activityName = $"{dbOperationName} {dbCollectionName}";
break;

case CommandType.Text:
activityName = dbName;
break;

default:
throw new InvalidEnumArgumentException($"Invalid value for 'System.Data.CommandType' ({(int)command.CommandType}).");
}

var activity = Source.StartActivity(activityName, ActivityKind.Client);
if (activity.IsAllDataRequested)
{
activity.SetTag("db.system", "firebird");

if (dbCollectionName != null)
{
activity.SetTag("db.collection.name", dbCollectionName);
}

// db.namespace

if (dbOperationName != null)
{
activity.SetTag("db.operation.name", dbOperationName);
}

// db.response.status_code

// error.type (handled by RecordException)

// server.port

// db.operation.batch.size

// db.query_summary

activity.SetTag("db.query.text", command.CommandText);

// network.peer.address

// network.peer.port

if (command.Connection.DataSource != null)
{
activity.SetTag("server.address", command.Connection.DataSource);
}

foreach (FbParameter p in command.Parameters)
{
var name = p.ParameterName;
var value = NormalizeDbNull(p.InternalValue);
activity.SetTag($"db.query.parameter.{name}", value);

}

// Only for explicit transactions.
if (command.Transaction != null)
{
FbTransactionInfo fbInfo = new FbTransactionInfo(command.Transaction);

var transactionId = fbInfo.GetTransactionId();
activity.SetTag($"db.transaction_id", transactionId);

// TODO: Firebird 4+ only (or remove?)
/*
var snapshotId = fbInfo.GetTransactionSnapshotNumber();
if (snapshotId != 0)
{
activity.SetTag($"db.snapshot_id", snapshotId);
}
*/
}
}

return activity;
}

internal static void CommandException(Activity activity, Exception exception, bool escaped = true)
{
// Reference: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/exceptions/exceptions-spans.md
activity.AddEvent(
new("exception", tags: new()
{
{ "exception.message", exception.Message },
{ "exception.type", exception.GetType().FullName },
{ "exception.escaped", escaped },
{ "exception.stacktrace", exception.ToString() },
})
);

string errorDescription = exception is FbException fbException
? fbException.SQLSTATE
: exception.Message;

activity.SetStatus(ActivityStatusCode.Error, errorDescription);
activity.Dispose();
}

private static object NormalizeDbNull(object value) =>
value == DBNull.Value || value == null
? null
: value;
}
}