Skip to content

Commit 90ccf42

Browse files
authored
Add Telemetry to Application Name (#3683)
## Why make this change? Closes #3216 DAB ships as an open-source container customers run anywhere, so we have little visibility into how it is configured or which features are used. This change encodes an anonymous usage fingerprint into the connection's `Application Name`, which the database side already records (e.g. `sys.dm_exec_sessions.program_name`), giving aggregate insight with no new endpoints, no network calls, and no per-customer data. ## What is this change? Embeds an anonymous, decodable usage-telemetry token into the `Application Name` of the connection strings DAB uses for SQL Server / Azure SQL, DWSQL, and PostgreSQL. - **Format:** `dab_oss_<version>+<context>|<runtime>|<entity>+` a version plus three flag sections (Context = 4, Runtime = 20, Entity = 14). Values use `0`/`1` (off/on), `M` (missing section), `X` (not applicable at pool open), `?` (not yet modeled). - **Pooling-safe (Model A):** only fields known when a pooled connection opens are encoded (the data-source engine as `Source`); per-request facets (protocol/object/role) are `X` so the connection-pool key, and therefore pool count, is unchanged. - **Where it's injected:** at config load (`RuntimeConfigLoader`) and on the hosted/late-config `POST /configuration` paths (`RuntimeConfigProvider.Initialize`). Embedding is **idempotent** (skips if the `dab_oss_` marker is already present). - **Multi-database:** the global runtime + merged entity fingerprint is encoded at every pool (the token has no correlation id, so any single sampled connection reflects the whole deployment); `Source` still varies per pool. - **Opt-out:** `DAB_TELEMETRY_APPNAME_OPT_OUT=1` reduces the value to version-only. - **Hosted label:** an existing `DAB_APP_NAME_ENV` value (e.g. `dab_hosted`) is preserved as a comma prefix and never suppresses the token. - **CLI:** new offline `dab appname` command to encode (`--config`) or decode (`--decode`) a token; `-o/--output` writes to a file. - **Logging:** the computed token (never the connection string) is logged at Debug via a bounded, drop-oldest `LogBuffer` flushed once the logger is available. - **Scope:** MySQL and Cosmos DB connection strings are left unchanged. - Design doc: `docs/design/application-name-telemetry.md`. ## How was this tested? - [x] Integration Tests - [x] Unit Tests Added encoder/decoder unit tests (token shape, every flag/section, Source + auth-provider maps, opt-out, host-label prefix, truncation-tolerant decode), connection-string injection tests for MSSQL/DWSQL/PostgreSQL (incl. user-supplied `Application Name` prefix) and no-op cases for MySQL/Cosmos, multi-database and hosted/late-config (`/configuration` + `/configuration/v2`) tests, an idempotency test, `LogBuffer` bound/flush tests, and CLI encode/decode/error/opt-out tests. ## Sample Request(s) Encode the token for a config (offline, no DB connection): ```bash dab appname --config dab-config.json # dab_oss_2.0.0+XXXX|110000M1M000MMMMMWMM|100?111001110?+ ``` Decode a token back to a human-readable legend: ```bash dab appname --decode "dab_oss_2.0.0+XXSX|110000M1M000MMMMMWMM|100?111001110?+" ``` Observe it on the SQL Server side: ```sql SELECT program_name FROM sys.dm_exec_sessions WHERE program_name LIKE 'dab_oss%' OR program_name LIKE '%,dab_oss%'; ```
1 parent 7ae1372 commit 90ccf42

17 files changed

Lines changed: 2534 additions & 84 deletions

‎docs/design/application-name-telemetry.md‎

Lines changed: 249 additions & 0 deletions
Large diffs are not rendered by default.

‎src/Cli.Tests/EndToEndTests.cs‎

Lines changed: 157 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT License.
33

44
using Azure.DataApiBuilder.Config.Converters;
5+
using Azure.DataApiBuilder.Config.Telemetry;
56
using Azure.DataApiBuilder.Product;
67
using Azure.DataApiBuilder.Service;
78
using Cli.Constants;
@@ -128,7 +129,10 @@ public void TestInitializingRestAndGraphQLGlobalSettings()
128129
replacementSettings: replacementSettings));
129130

130131
SqlConnectionStringBuilder builder = new(runtimeConfig.DataSource!.ConnectionString);
131-
Assert.AreEqual(ProductInfo.GetDataApiBuilderUserAgent(), builder.ApplicationName);
132+
// Application Name now embeds the dab_oss telemetry block (dab_oss_<version>+<payload>+),
133+
// so assert it begins with the product user agent rather than exact-matching it.
134+
Assert.IsTrue(builder.ApplicationName.StartsWith(ProductInfo.GetDataApiBuilderUserAgent()),
135+
$"Expected Application Name to start with '{ProductInfo.GetDataApiBuilderUserAgent()}' but was '{builder.ApplicationName}'.");
132136

133137
Assert.IsNotNull(runtimeConfig);
134138
Assert.AreEqual(DatabaseType.MSSQL, runtimeConfig.DataSource.DatabaseType);
@@ -139,6 +143,158 @@ public void TestInitializingRestAndGraphQLGlobalSettings()
139143
Assert.IsTrue(runtimeConfig.Runtime.GraphQL?.Enabled);
140144
}
141145

146+
/// <summary>
147+
/// The `appname` command encodes the telemetry Application Name from a config (offline — no
148+
/// validation and no database connection) and decodes a telemetry string back into a
149+
/// human-readable description.
150+
/// </summary>
151+
[TestMethod]
152+
public void TestAppNameEncodeAndDecode()
153+
{
154+
// Arrange: a minimal, self-contained MSSQL config in the mock file system.
155+
string configJson = @"{
156+
""$schema"": ""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch/dab.draft.schema.json"",
157+
""data-source"": { ""database-type"": ""mssql"", ""connection-string"": ""Server=localhost;Database=demo;User Id=sa;Password=Placeholder1;"" },
158+
""runtime"": { ""rest"": { ""enabled"": true }, ""graphql"": { ""enabled"": true }, ""host"": { ""mode"": ""development"", ""authentication"": { ""provider"": ""StaticWebApps"" } } },
159+
""entities"": { ""Book"": { ""source"": { ""object"": ""dbo.books"", ""type"": ""table"" }, ""permissions"": [ { ""role"": ""anonymous"", ""actions"": [ ""read"" ] } ] } }
160+
}";
161+
_fileSystem!.File.WriteAllText("appname-config.json", configJson);
162+
163+
// Act: encode to an output file. This must succeed offline (no validation / no DB connection).
164+
int encodeCode = Program.Execute(
165+
new[] { "appname", "--config", "appname-config.json", "--output", "appname-out.txt" },
166+
_cliLogger!, _fileSystem!, _runtimeConfigLoader!);
167+
168+
// Assert: encode succeeded and produced a well-formed telemetry string.
169+
Assert.AreEqual(0, encodeCode, "appname --config should succeed offline");
170+
string telemetry = _fileSystem.File.ReadAllText("appname-out.txt");
171+
Assert.IsTrue(telemetry.StartsWith("dab_oss_"), telemetry);
172+
Assert.IsTrue(telemetry.EndsWith("+"), telemetry);
173+
174+
// Act: decode the produced string back into a human-readable description.
175+
int decodeCode = Program.Execute(
176+
new[] { "appname", "--decode", telemetry, "--output", "appname-decoded.txt" },
177+
_cliLogger!, _fileSystem!, _runtimeConfigLoader!);
178+
179+
// Assert: decode succeeded and produced recognizable lines.
180+
Assert.AreEqual(0, decodeCode, "appname --decode should succeed");
181+
string decoded = _fileSystem.File.ReadAllText("appname-decoded.txt");
182+
Assert.IsTrue(decoded.Contains("Version: dab_oss_"), decoded);
183+
Assert.IsTrue(decoded.Contains("runtime.rest.enabled"), decoded);
184+
Assert.IsTrue(decoded.Contains("entities.any.table"), decoded);
185+
}
186+
187+
/// <summary>
188+
/// The `appname` encode path accepts absolute config and output paths. The relative-path case is
189+
/// covered by <see cref="TestAppNameEncodeAndDecode"/>.
190+
/// </summary>
191+
[TestMethod]
192+
public void TestAppNameEncodeSupportsAbsolutePaths()
193+
{
194+
string configPath = _fileSystem!.Path.GetFullPath("absolute-appname-config.json");
195+
string outputPath = _fileSystem.Path.GetFullPath("absolute-appname-output.txt");
196+
string configJson = @"{
197+
""$schema"": ""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch/dab.draft.schema.json"",
198+
""data-source"": { ""database-type"": ""mssql"", ""connection-string"": ""Server=localhost;Database=demo;"" },
199+
""entities"": { }
200+
}";
201+
_fileSystem.File.WriteAllText(configPath, configJson);
202+
203+
int code = Program.Execute(
204+
new[] { "appname", "--config", configPath, "--output", outputPath },
205+
_cliLogger!, _fileSystem, _runtimeConfigLoader!);
206+
207+
Assert.AreEqual(CliReturnCode.SUCCESS, code, "appname should support absolute config and output paths.");
208+
Assert.IsTrue(_fileSystem.File.Exists(outputPath), "The absolute output path should be written.");
209+
Assert.IsTrue(_fileSystem.File.ReadAllText(outputPath).StartsWith("dab_oss_", StringComparison.Ordinal));
210+
}
211+
212+
/// <summary>
213+
/// The `appname` encode path returns GENERAL_ERROR (and writes no output file) when the config
214+
/// file cannot be found.
215+
/// </summary>
216+
[TestMethod]
217+
public void TestAppNameEncodeFailsWhenConfigMissing()
218+
{
219+
int code = Program.Execute(
220+
new[] { "appname", "--config", "does-not-exist.json", "--output", "appname-out.txt" },
221+
_cliLogger!, _fileSystem!, _runtimeConfigLoader!);
222+
223+
Assert.AreEqual(CliReturnCode.GENERAL_ERROR, code, "appname encode should fail when the config cannot be found.");
224+
Assert.IsFalse(_fileSystem!.File.Exists("appname-out.txt"), "No output file should be written on failure.");
225+
}
226+
227+
/// <summary>
228+
/// The `appname` encode path writes the telemetry string to stdout when --output is omitted.
229+
/// </summary>
230+
[TestMethod]
231+
public void TestAppNameEncodeWritesToStdout()
232+
{
233+
string configJson = @"{
234+
""$schema"": ""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch/dab.draft.schema.json"",
235+
""data-source"": { ""database-type"": ""mssql"", ""connection-string"": ""Server=localhost;Database=demo;User Id=sa;Password=Placeholder1;"" },
236+
""runtime"": { ""rest"": { ""enabled"": true }, ""graphql"": { ""enabled"": true } },
237+
""entities"": { }
238+
}";
239+
_fileSystem!.File.WriteAllText("appname-config.json", configJson);
240+
241+
TextWriter originalOut = Console.Out;
242+
StringWriter capturedOut = new();
243+
Console.SetOut(capturedOut);
244+
int code;
245+
try
246+
{
247+
code = Program.Execute(
248+
new[] { "appname", "--config", "appname-config.json" },
249+
_cliLogger!, _fileSystem!, _runtimeConfigLoader!);
250+
}
251+
finally
252+
{
253+
Console.SetOut(originalOut);
254+
}
255+
256+
Assert.AreEqual(CliReturnCode.SUCCESS, code, "appname encode to stdout should succeed.");
257+
string stdout = capturedOut.ToString();
258+
Assert.IsTrue(stdout.Contains("dab_oss_"), $"stdout should contain the telemetry marker but was '{stdout}'.");
259+
Assert.IsTrue(stdout.TrimEnd().EndsWith("+"), $"stdout telemetry should end with '+' but was '{stdout}'.");
260+
}
261+
262+
/// <summary>
263+
/// The `appname` command is a design-time inspection tool: it always shows the full telemetry
264+
/// encoding so users can see what would be collected, independent of the runtime opt-out switch
265+
/// (DAB_TELEMETRY_APPNAME_OPT_OUT). This pins that intentional behavior.
266+
/// </summary>
267+
[TestMethod]
268+
public void TestAppNameEncodeIsIndependentOfOptOut()
269+
{
270+
string? originalOptOut = Environment.GetEnvironmentVariable(ApplicationNameTelemetry.OPT_OUT_ENV_VAR);
271+
Environment.SetEnvironmentVariable(ApplicationNameTelemetry.OPT_OUT_ENV_VAR, "1");
272+
try
273+
{
274+
string configJson = @"{
275+
""$schema"": ""https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch/dab.draft.schema.json"",
276+
""data-source"": { ""database-type"": ""mssql"", ""connection-string"": ""Server=localhost;Database=demo;User Id=sa;Password=Placeholder1;"" },
277+
""runtime"": { ""rest"": { ""enabled"": true }, ""graphql"": { ""enabled"": true } },
278+
""entities"": { }
279+
}";
280+
_fileSystem!.File.WriteAllText("appname-config.json", configJson);
281+
282+
int code = Program.Execute(
283+
new[] { "appname", "--config", "appname-config.json", "--output", "appname-out.txt" },
284+
_cliLogger!, _fileSystem!, _runtimeConfigLoader!);
285+
286+
Assert.AreEqual(CliReturnCode.SUCCESS, code, "appname encode should succeed even when opted out.");
287+
string telemetry = _fileSystem.File.ReadAllText("appname-out.txt");
288+
Assert.IsTrue(
289+
telemetry.StartsWith("dab_oss_") && telemetry.EndsWith("+"),
290+
$"appname should show the full telemetry encoding regardless of opt-out, but was '{telemetry}'.");
291+
}
292+
finally
293+
{
294+
Environment.SetEnvironmentVariable(ApplicationNameTelemetry.OPT_OUT_ENV_VAR, originalOptOut);
295+
}
296+
}
297+
142298
/// <summary>
143299
/// Test to validate the usage of --graphql.multiple-mutations.create.enabled option of the init command for all database types.
144300
///

‎src/Cli/Commands/AppNameOptions.cs‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System.IO.Abstractions;
5+
using Azure.DataApiBuilder.Config;
6+
using Azure.DataApiBuilder.Config.ObjectModel;
7+
using Azure.DataApiBuilder.Config.Telemetry;
8+
using Azure.DataApiBuilder.Core.Configurations;
9+
using Cli.Constants;
10+
using CommandLine;
11+
using Microsoft.Extensions.Logging;
12+
13+
namespace Cli.Commands
14+
{
15+
/// <summary>
16+
/// Options for the <c>appname</c> command, which encodes the DAB telemetry Application Name
17+
/// from a config file, or decodes a telemetry Application Name into a human-readable description.
18+
/// </summary>
19+
[Verb("appname", isDefault: false, HelpText = "Show or decode the DAB telemetry 'Application Name' embedded in datasource connections.", Hidden = false)]
20+
public class AppNameOptions : Options
21+
{
22+
public AppNameOptions(string? decode = null, string? output = null, string? config = null)
23+
: base(config)
24+
{
25+
Decode = decode;
26+
Output = output;
27+
}
28+
29+
/// <summary>
30+
/// When provided, decodes the given telemetry Application Name string into a human-readable
31+
/// description instead of encoding from a config file. Decoding is tolerant of truncation.
32+
/// </summary>
33+
[Option("decode", Required = false, HelpText = "Decode a telemetry Application Name string into a human-readable description.")]
34+
public string? Decode { get; }
35+
36+
/// <summary>
37+
/// Optional file path to write the result to. When omitted, the result is written to stdout.
38+
/// </summary>
39+
[Option('o', "output", Required = false, HelpText = "Write the result to the specified file instead of stdout.")]
40+
public string? Output { get; }
41+
42+
/// <summary>
43+
/// Handles the <c>appname</c> command.
44+
/// </summary>
45+
public int Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSystem fileSystem)
46+
{
47+
// Decode mode: a pure, tolerant string decode. No config or validation is required.
48+
// Presence of the option (even with an empty/whitespace value) selects decode mode; the
49+
// decoder itself reports a friendly message for empty input.
50+
if (Decode is not null)
51+
{
52+
IReadOnlyList<string> decodedLines = ApplicationNameTelemetry.Decode(Decode);
53+
WriteResult(string.Join(Environment.NewLine, decodedLines), fileSystem, logger, trailingNewLine: true);
54+
return CliReturnCode.SUCCESS;
55+
}
56+
57+
// Encode mode: parse the config and emit the telemetry Application Name.
58+
// We intentionally do NOT run full `validate` here — validation opens a database
59+
// connection, whereas encoding only needs the parsed runtime/entity settings.
60+
// Requiring a live database would defeat the purpose of this static inspection command.
61+
if (!ConfigGenerator.TryGetConfigForRuntimeEngine(Config, loader, fileSystem, out _))
62+
{
63+
logger.LogError("Could not determine the config file to use.");
64+
return CliReturnCode.GENERAL_ERROR;
65+
}
66+
67+
RuntimeConfigProvider runtimeConfigProvider = new(loader);
68+
if (!runtimeConfigProvider.TryGetConfig(out RuntimeConfig? runtimeConfig) || runtimeConfig is null)
69+
{
70+
logger.LogError("Failed to parse the config file.");
71+
return CliReturnCode.GENERAL_ERROR;
72+
}
73+
74+
// There is no live connection context at design time, so the context fields
75+
// (Protocol/Object/Source/Role) are emitted as placeholders.
76+
string telemetryAppName = ApplicationNameTelemetry.EncodeTelemetryString(runtimeConfig, liveDataSource: null);
77+
WriteResult(telemetryAppName, fileSystem, logger, trailingNewLine: false);
78+
return CliReturnCode.SUCCESS;
79+
}
80+
81+
/// <summary>
82+
/// Writes the result to the output file when <c>--output</c> is provided, otherwise to stdout.
83+
/// </summary>
84+
private void WriteResult(string content, IFileSystem fileSystem, ILogger logger, bool trailingNewLine)
85+
{
86+
if (!string.IsNullOrWhiteSpace(Output))
87+
{
88+
// Mirror stdout behavior: append a trailing newline for human-readable (decode) output,
89+
// but keep encode output exact (no trailing newline) so it can be copied/piped verbatim.
90+
string fileContent = trailingNewLine ? content + Environment.NewLine : content;
91+
fileSystem.File.WriteAllText(Output, fileContent);
92+
logger.LogInformation("Wrote output to '{outputFile}'.", Output);
93+
}
94+
else if (trailingNewLine)
95+
{
96+
Console.WriteLine(content);
97+
}
98+
else
99+
{
100+
Console.Write(content);
101+
}
102+
}
103+
}
104+
}

‎src/Cli/Program.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public static int Execute(string[] args, ILogger cliLogger, IFileSystem fileSyst
8888
});
8989

9090
// Parsing user arguments and executing required methods.
91-
int result = parser.ParseArguments<InitOptions, AddOptions, UpdateOptions, StartOptions, ValidateOptions, ExportOptions, AddTelemetryOptions, ConfigureOptions, AutoConfigOptions, AutoConfigSimulateOptions>(args)
91+
int result = parser.ParseArguments<InitOptions, AddOptions, UpdateOptions, StartOptions, ValidateOptions, ExportOptions, AddTelemetryOptions, ConfigureOptions, AutoConfigOptions, AutoConfigSimulateOptions, AppNameOptions>(args)
9292
.MapResult(
9393
(InitOptions options) => options.Handler(cliLogger, loader, fileSystem),
9494
(AddOptions options) => options.Handler(cliLogger, loader, fileSystem),
@@ -100,6 +100,7 @@ public static int Execute(string[] args, ILogger cliLogger, IFileSystem fileSyst
100100
(AutoConfigOptions options) => options.Handler(cliLogger, loader, fileSystem),
101101
(AutoConfigSimulateOptions options) => options.Handler(cliLogger, loader, fileSystem),
102102
(ExportOptions options) => options.Handler(cliLogger, loader, fileSystem),
103+
(AppNameOptions options) => options.Handler(cliLogger, loader, fileSystem),
103104
errors => DabCliParserErrorHandler.ProcessErrorsAndReturnExitCode(errors));
104105

105106
return result;

‎src/Config/DeserializationVariableReplacementSettings.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ public class DeserializationVariableReplacementSettings
1818
public bool DoReplaceAkvVar { get; set; }
1919
public EnvironmentVariableReplacementFailureMode EnvFailureMode { get; set; } = EnvironmentVariableReplacementFailureMode.Throw;
2020

21+
/// <summary>
22+
/// When true, connection-string Application Name (telemetry) injection is skipped during this
23+
/// parse. This is set for nested child config loads in a multi-database setup: a child config
24+
/// lacks the global runtime section and knows only its own entities, so the top-level load
25+
/// performs the injection once over the fully-merged config for every data source.
26+
/// </summary>
27+
public bool SkipApplicationNameInjection { get; set; }
28+
2129
// @env\(' : match @env('
2230
// @akv\(' : match @akv('
2331
// .*? : lazy match any character except newline 0 or more times

‎src/Config/FileSystemRuntimeConfigLoader.cs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,11 @@ private void HotReloadConfig(bool isDevMode, ILogger? logger = null)
360360
IsNewConfigValidated = false;
361361
SignalConfigChanged();
362362

363+
// Telemetry (and any other) logs buffered during the reload parse are otherwise only
364+
// drained once at startup. Flush them now so hot-reload logs are actually emitted and the
365+
// shared static buffer does not accumulate entries across successive reloads.
366+
FlushLogBuffer();
367+
363368
logger?.LogInformation("Hot-reload process finished.");
364369
}
365370

@@ -551,13 +556,10 @@ public void SetLogger(ILogger<FileSystemRuntimeConfigLoader> logger)
551556
}
552557

553558
/// <summary>
554-
/// Flush all logs from the buffer after the log level is set from the RuntimeConfig.
555-
/// Logger needs to be present, or else the logs will be lost.
559+
/// The logger this loader emits to once set, consumed by the base
560+
/// <see cref="RuntimeConfigLoader.FlushLogBuffer"/> to drain buffered logs.
556561
/// </summary>
557-
public void FlushLogBuffer()
558-
{
559-
_logBuffer.FlushToLogger(_logger!);
560-
}
562+
protected override ILogger? Logger => _logger;
561563

562564
/// <summary>
563565
/// Helper method that sends the log to the buffer if the logger has not being set up.

‎src/Config/LogBuffer.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ namespace Azure.DataApiBuilder.Config
1212
/// </summary>
1313
public class LogBuffer
1414
{
15+
/// <summary>
16+
/// Upper bound on buffered entries. Prevents unbounded growth when the buffer is never drained
17+
/// (e.g. a loader with no logger in a hot-reload loop). The oldest entries are dropped first.
18+
/// </summary>
19+
internal const int MAX_BUFFERED_ENTRIES = 1000;
20+
1521
private readonly ConcurrentQueue<(LogLevel LogLevel, string Message, Exception? Exception)> _logBuffer;
1622
private readonly object _flushLock = new();
1723

@@ -26,6 +32,12 @@ public LogBuffer()
2632
public void BufferLog(LogLevel logLevel, string message, Exception? exception = null)
2733
{
2834
_logBuffer.Enqueue((logLevel, message, exception));
35+
36+
// Keep the buffer bounded so it cannot grow without limit if it is never drained. Dropping
37+
// the oldest entries first preserves the most recent (most useful) diagnostics.
38+
while (_logBuffer.Count > MAX_BUFFERED_ENTRIES && _logBuffer.TryDequeue(out _))
39+
{
40+
}
2941
}
3042

3143
/// <summary>

0 commit comments

Comments
 (0)