Path: redb/redb.Tests.Integration/Helpers/CommandCounter.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Helpers/CommandCounter.cs
----
using System.Diagnostics;
using redb.Core.Diagnostics;
namespace redb.Tests.Integration.Helpers;
///
/// Counts the database commands an action runs: the spans of the redb.Core ActivitySource (one per command) under a
/// parent span of the caller only, so commands of tests running in parallel are not counted.
///
public static class CommandCounter
{
private const string ProbeName = "redb.Tests.CommandCount";
private static readonly ActivitySource Probe = new(ProbeName);
/// The database commands runs.
public static Task CountAsync(Func action) => CountAsync(action, excluded: null);
///
/// The commands runs other than scalar side commands (db.operation = scalar): its
/// data statements, whatever the provider reads them with, and any metadata it reads. The PostgreSQL statistics guard
/// is such a side command: until the tables have planner statistics it checks them and sets enable_nestloop around a
/// statement with scalar commands, on a recheck interval, so whether a counted call meets it depends on timing.
///
public static Task CountWithoutScalarsAsync(Func action) => CountAsync(action, excluded: RedbTelemetry.Scalar);
private static async Task CountAsync(Func action, string? excluded)
{
var spans = new List();
using var listener = new ActivityListener
{
ShouldListenTo = s => s.Name == RedbActivitySource.SourceName || s.Name == ProbeName,
Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStopped = a => { lock (spans) spans.Add(a); },
};
ActivitySource.AddActivityListener(listener);
ActivityTraceId trace;
using (var parent = Probe.StartActivity("count")!)
{
trace = parent.TraceId;
await action();
}
lock (spans)
return spans.Count(a => a.Source.Name == RedbActivitySource.SourceName && a.TraceId == trace
&& (excluded == null || (a.GetTagItem("db.operation") as string) != excluded));
}
}