From f6ccdfaaa59a8cf75bd1d74839baa9cd7ba7b584 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:17:36 +0100 Subject: [PATCH 01/29] docs(decisions): record the client API redesign and manual versioning - ADR-0005: the public API of a client no longer mirrors the REST contract; it has kinds of text, outcomes as values and splitting inside the client, so that it can be ported to other languages - ADR-0006: the Dax.Formatter package version is written by hand as three numbers in version.json, and NBGV only stamps it; this replaces one rule of ADR-0004, which stays accepted --- ...e-the-client-api-from-the-rest-contract.md | 79 +++++++++++++++++++ ...e-dax-formatter-package-version-by-hand.md | 73 +++++++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md create mode 100644 docs/decisions/0006-write-the-dax-formatter-package-version-by-hand.md diff --git a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md new file mode 100644 index 0000000..45fa5a0 --- /dev/null +++ b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md @@ -0,0 +1,79 @@ +--- +status: accepted +date: 2026-11-22 +decision-makers: Alberto Spelta +--- + +# Decouple the client API from the REST contract + +## Context and Problem Statement + +`Dax.Formatter` 1.2 exposes the request and response of the REST contract as its public API. A caller builds a request object, gets back responses to match with its own objects by position, and reads the outcome from an empty `Formatted` and a nullable `Errors`. A call waits at most 60 seconds, whatever its size, and a call with thousands of expressions goes out as one request, which can fail for its size or its duration ([sql-bi/DaxFormatter#40](https://github.com/sql-bi/DaxFormatter/issues/40), [sql-bi/Bravo#963](https://github.com/sql-bi/Bravo/issues/963)). The tools that format the objects of a model each write the same code around the client: a `[x] :=` line before every expression, its removal from the result, and the match of results by index. A TypeScript client library and a Python client are planned ([backlog](../backlog.md)). What should the public API of a DAX Formatter client be, so that it stays the same when the service contract changes, and the same across languages? + +## Considered Options + +* Keep the request and response of the REST contract as the public API, and add splitting and timeouts to it +* Keep the 1.x types and add a layer of helpers for expressions and batches +* A new API on a model of its own: kinds of text, outcomes as values, splitting inside the client + +## Decision Outcome + +Chosen option: "A new API on a model of its own", because the work that every caller repeats belongs to the client, and an API that doesn't show the wire format can keep its shape when the contract changes and be ported to other languages. It is version 2.0.0 of the package, with breaking changes; [`client-api.md`](../design/client-api.md) describes the model. + +- The public types are the client, its options, the options of a call, the result of a text, a syntax error, a progress value and one exception. The types of the wire format are internal. +- A call says what its texts are with a kind. `Auto` sends a text as it is; `Expression` is the DAX of one model object without its name, user-defined functions included. There is no `Query` kind, which would behave like `Auto`, and no `Function` kind: the client recognizes a function body by itself. +- An outcome is a value: a syntax error is part of the result of its text. A failure of the service or of the network is one exception type with a reason, and a cancellation by the caller is the cancellation exception of the language. +- A result can carry the caller's object, so nothing is matched by position. A call returns every result, in the order of the input, or throws. +- The client splits a large call into requests, limits how many are in progress, retries the failures that can be temporary and reports progress. How much a request carries is an internal constant, not an option. +- The client uses only the endpoint that takes several texts, which formats DAX only: the client doesn't format MDX. +- The client doesn't convert line breaks: the service returns those inside strings and comments as they were sent, so converting all of them would change the content of strings. It doesn't halve a request that timed out: the service keeps working on a request that the client abandoned, so halving would double the load when the service is slow. +- The descriptions of the model, which the service uses for statistics, are strings, as in the TypeScript port; the server types that the service knows are constants. +- The shape must exist in every target language and for every consumer of the .NET package: no `init`, `required` or record in public types, which a .NET Framework project on C# 7.3 can't use; no interface next to the client, whose methods are virtual; asynchronous methods only; no new dependency. The .NET package targets `netstandard2.0` and `net10.0`. + +### Consequences + +* Good, because a caller passes its objects and reads results: the header line, the match by index and the outcome check are no longer written in each tool. +* Good, because a call with thousands of texts no longer depends on one request ([sql-bi/DaxFormatter#40](https://github.com/sql-bi/DaxFormatter/issues/40)). +* Good, because the TypeScript and Python clients get a model to port, with test vectors that don't depend on a language. +* Bad, because every application on 1.x must change its code to move to 2.0; the package readme has a migration table. +* Bad, because the client now knows some DAX: where strings, names and comments start and end, and what a function body looks like. A change of the DAX syntax there reaches the client. +* Bad, because `Expression` depends on how the service writes its answer: the client sends a header line, expects it back, and removes it with the indentation that the service adds under a function header. A different answer is a failure, never a wrong text, and the live tests pin the answers. +* Bad, because the client can't work around three limits of the service, which it returns as syntax errors ([`client-api.md`](../design/client-api.md#limits-of-the-service)). +* Bad, because applications that formatted MDX with the single-text methods of 1.x lose it. + +### Confirmation + +- `PublicApiTests` compares the public surface with `PublicApi.approved.txt` on each target framework, and checks that every public type is in the `Dax.Formatter` namespace: a change of the surface shows up as a change of that file. +- The fixtures under `dotnet/tests/Dax.Formatter.Tests/Fixtures/` hold the request bodies, the recorded answers of the service and the expected results; the tests of every client run them. +- The live tests, run on request, check the recorded answers against the service. +- `ReadmeTests` keeps the code of the package readme equal to code that compiles and runs. + +## Pros and Cons of the Options + +### Keep the request and response of the REST contract as the public API, and add splitting and timeouts to it + +* Good, because no caller has to change its code. +* Bad, because a request object that the client splits no longer maps to one request, so the wire types would stop describing the wire. +* Bad, because a change of the contract stays a change of the public API, as when the metadata enums change form. +* Bad, because the header line, the match by index and the outcome check stay in every caller. + +### Keep the 1.x types and add a layer of helpers for expressions and batches + +* Good, because existing code keeps working and new code gets the helpers. +* Bad, because two ways to do everything stay in the package, and the old one keeps the failures the new one solves. +* Bad, because the helpers would return the 1.x response types, with their implicit outcome and nullable fields. + +### A new API on a model of its own: kinds of text, outcomes as values, splitting inside the client + +* Good, because the API is small: two operations, two option types, one result type. +* Good, because it follows the conventions that .NET developers know (see More Information). +* Bad, because it is a breaking change of a published package. + +## More Information + +- The model and its behavior: [`client-api.md`](../design/client-api.md); the contract it calls: [`rest-api.md`](../design/rest-api.md). +- Names and shapes: [Framework Design Guidelines, names of type members](https://learn.microsoft.com/dotnet/standard/design-guidelines/names-of-type-members) and [enum design](https://learn.microsoft.com/dotnet/standard/design-guidelines/enum), which says not to reserve enum values for future use; [Azure SDK general guidelines](https://azure.github.io/azure-sdk/general_design.html) for client, options and result types; [Task-based Asynchronous Pattern](https://learn.microsoft.com/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap#progress-reporting-optional) for progress; [`IdentityResult`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.identity.identityresult) for `Succeeded` with `Errors`. +- The arrow `=>` belongs to function definitions only: [FUNCTION statement](https://learn.microsoft.com/dax/function-statement-dax). +- The shared `HttpClient`: [Guidelines for using HttpClient](https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines). +- The version of the package: [ADR-0006](0006-write-the-dax-formatter-package-version-by-hand.md). +- Revisit if the service gets an endpoint that takes the kind of a text, which would make the header line unnecessary, or if users ask for MDX again. diff --git a/docs/decisions/0006-write-the-dax-formatter-package-version-by-hand.md b/docs/decisions/0006-write-the-dax-formatter-package-version-by-hand.md new file mode 100644 index 0000000..2425739 --- /dev/null +++ b/docs/decisions/0006-write-the-dax-formatter-package-version-by-hand.md @@ -0,0 +1,73 @@ +--- +status: accepted +date: 2026-11-22 +decision-makers: Alberto Spelta +--- + +# Write the Dax.Formatter package version by hand + +## Context and Problem Statement + +`dotnet/version.json` held the two-part version `1.2`, and Nerdbank.GitVersioning (NBGV) added the git height as the third number: every commit under `dotnet/src/Dax.Formatter` raised the version that the next release would publish, so 1.2.2 came after 1.2.1 whatever the commits changed ([ADR-0004](0004-version-tag-and-release-each-package-independently.md)). The number says how many commits a release holds, not whether an application can take it without changes. Version 2.0.0 is a breaking release ([ADR-0005](0005-decouple-the-client-api-from-the-rest-contract.md)) that may be published as a preview first, and after it a fix, a feature and a breaking change should each be recognizable from the number. Who decides the version of the `Dax.Formatter` package, and where is it written? + +## Considered Options + +* Keep the two-part version, with the git height as the patch number +* Write a three-part version by hand in `version.json`, and keep NBGV to stamp it +* Remove NBGV from the .NET toolchain and set the version in the project file + +## Decision Outcome + +Chosen option: "Write a three-part version by hand in `version.json`, and keep NBGV to stamp it", because the number then says what a release changes, as Semantic Versioning asks, while the build, the release workflow and the tags stay as they are. + +- `dotnet/version.json` holds a three-part version, such as `2.0.0`, or a preview such as `2.0.0-beta.1`. NBGV stamps it on the package and the assemblies. The git height becomes the fourth number of the file version, and appears nowhere in the package version; the path filter decides only that number. +- `master` holds the next version to publish. +- Right after a release, a one-line pull request raises the patch number: `2.0.0` becomes `2.0.1`. +- A pull request that adds a feature sets the minor number, `2.1.0`; one with a breaking change sets the major number. +- Previews are written out: `2.0.0-beta.1`, `2.0.0-beta.2`, then `2.0.0`. +- This holds for `Dax.Formatter`. The MCP server stays on `0.2-beta` with the height as its third number while it is in beta. +- The assembly version keeps only the major number, and a build outside `master` keeps its commit suffix: both settings of `version.json` are unchanged. + +### Consequences + +* Good, because a version says what it changes: a patch is a fix, a minor adds, a major breaks. +* Good, because a preview can be published and replaced by the final version with the same number. +* Good, because the file version still tells two builds of the same package version apart. +* Bad, because the version is now a manual step: a release from a `master` whose version was already published is stopped only by `dotnet nuget push`, after the build and the tests, as ADR-0004 already notes. The [backlog](../backlog.md) has an item for an earlier check. +* Bad, because a pull request that adds a feature and doesn't set the minor number publishes it as a patch: only a review catches it. +* Bad, because the two packages of the repository follow different schemes until the MCP server leaves its beta. + +### Confirmation + +- On an up-to-date `master`, the version command of [`dotnet/AGENTS.md`](../../dotnet/AGENTS.md) prints the version written in `dotnet/version.json`. +- Review: a pull request that changes the public API or the behavior of `Dax.Formatter` sets the version by the rules above, and the pull request after a release raises the patch number. +- Checked when this record was written, with NBGV 3.9.50: two commits in a row that change `dotnet/src/Dax.Formatter` give the same package version and file versions whose fourth numbers differ by one. + +## Pros and Cons of the Options + +### Keep the two-part version, with the git height as the patch number + +* Good, because no one sets a version, so no release can reuse one. +* Bad, because the patch number counts commits: a release with a new feature and one with a typo fix look the same. +* Bad, because a preview of 2.0 would need a `-beta` tag on every build until the final version, with the height in the number. + +### Write a three-part version by hand in `version.json`, and keep NBGV to stamp it + +* Good, because the build, the release workflow, the tags and the commit suffix outside `master` don't change. +* Good, because NBGV documents this form: with a third number in the version, the height is the fourth one. +* Bad, because the version must be raised by hand, in the right pull request. + +### Remove NBGV from the .NET toolchain and set the version in the project file + +* Good, because one tool less, and the version sits next to the other package properties. +* Bad, because the release workflow reads the version from NBGV, and a build outside `master` would lose its commit suffix, so a local package could pass for a released one. +* Bad, because it changes `Directory.Build.props` and a release workflow for a gain that the chosen option already gives. The backlog keeps it as an open decision. + +## More Information + +- This record replaces one rule of [ADR-0004](0004-version-tag-and-release-each-package-independently.md) for `Dax.Formatter`: "Each package has one NBGV `version.json` at its toolchain root, with path filters, so that only changes to the package raise its version height". The file and its path filter stay, but a change to the package no longer raises its version. The other rules of ADR-0004 stand: one `version.json` for each package, the tags, the draft releases. +- NBGV, [`version.json`](https://dotnet.github.io/Nerdbank.GitVersioning/docs/versionJson.html): "You may optionally supply a third integer in the version (i.e. x.y.z), in which case the git version height is specified as the fourth integer, which only appears in certain version representations." +- Microsoft, [Versioning and .NET libraries](https://learn.microsoft.com/dotnet/standard/library-guidance/versioning): consider Semantic Versioning 2.0.0 for the package version, include a prerelease suffix when releasing a nonstable package, consider only a major version in the assembly version, and consider a continuous integration build number as the revision of the file version. +- Azure SDK, [release policy](https://azure.github.io/azure-sdk/policies_releases.html#incrementing-after-release): the version in source control is raised right after a package ships, because "It's safer to have `N+1` in `main` than `N`"; previews are `X.Y.Z-beta.N`. Its .NET packages go from a stable version to the first beta of the next minor one; here the smaller step, the next patch, is the default, and a pull request with a feature raises it. +- [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html). +- Revisit when the MCP server leaves its beta, to give both packages one scheme, or if NBGV is removed from the .NET toolchain. From 60e0570eb6d7a0cdf3154ccc9466860274374b70 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:17:55 +0100 Subject: [PATCH 02/29] build(dotnet)!: remove the 1.x sources and retarget the projects - delete the 1.x client, its request and response models, its JSON converters and its tests: version 2.0 is written from scratch - delete dotnet/samples: the examples move to the package readme, where the tests check them - target netstandard2.0 and net10.0 in the library, net472 and net10.0 in the tests; net8.0 applications use the netstandard2.0 assembly - generate the XML documentation file, enable package validation and mark the net10.0 assembly as compatible with native AOT --- dotnet/samples/Directory.Build.props | 1 - dotnet/samples/Directory.Build.targets | 1 - .../GettingStarted/BasicFormatter.csproj | 12 - dotnet/samples/GettingStarted/Program.cs | 126 ---------- .../GettingStarted/getting-started.sln | 25 -- .../AnalysisServices/ServerEdition.cs | 65 ----- .../AnalysisServices/ServerLocation.cs | 17 -- .../AnalysisServices/ServerMode.cs | 28 --- .../AnalysisServices/ServerType.cs | 33 --- .../Client/Http/DaxFormatterHttpClient.cs | 84 ------- .../DaxFormatterHttpClientMessageHandler.cs | 13 - .../Client/Http/IDaxFormatterHttpClient.cs | 16 -- dotnet/src/Dax.Formatter/Dax.Formatter.csproj | 18 +- .../src/Dax.Formatter/DaxFormatterClient.cs | 73 ------ .../src/Dax.Formatter/GlobalSuppressions.cs | 8 - .../src/Dax.Formatter/IDaxFormatterClient.cs | 18 -- .../Dax.Formatter/Models/DaxFormatterError.cs | 11 - .../Models/DaxFormatterLineStyle.cs | 9 - .../Models/DaxFormatterMultipleRequest.cs | 20 -- .../Models/DaxFormatterRequest.cs | 73 ------ .../Models/DaxFormatterResponse.cs | 11 - .../Models/DaxFormatterSeparatorStyle.cs | 11 - .../Models/DaxFormatterSingleRequest.cs | 20 -- .../Models/DaxFormatterSpacingStyle.cs | 11 - .../Dax.Formatter/Security/SecurityHelpers.cs | 28 --- .../DictionaryLookupNamingPolicy.cs | 15 -- .../JsonDaxFormatterSpacingStyleConverter.cs | 35 --- .../Serialization/JsonEnumMemberConverter.cs | 49 ---- .../JsonNamingPolicyDecorator.cs | 13 - .../Dax.Formatter.Tests.csproj | 6 +- .../DaxFormatterClientTests.cs | 223 ------------------ .../DaxFormatterMultipleRequestTests.cs | 107 --------- .../Models/DaxFormatterSingleRequestTests.cs | 99 -------- .../Security/SecurityHelpersTests.cs | 20 -- 34 files changed, 10 insertions(+), 1289 deletions(-) delete mode 100644 dotnet/samples/Directory.Build.props delete mode 100644 dotnet/samples/Directory.Build.targets delete mode 100644 dotnet/samples/GettingStarted/BasicFormatter.csproj delete mode 100644 dotnet/samples/GettingStarted/Program.cs delete mode 100644 dotnet/samples/GettingStarted/getting-started.sln delete mode 100644 dotnet/src/Dax.Formatter/AnalysisServices/ServerEdition.cs delete mode 100644 dotnet/src/Dax.Formatter/AnalysisServices/ServerLocation.cs delete mode 100644 dotnet/src/Dax.Formatter/AnalysisServices/ServerMode.cs delete mode 100644 dotnet/src/Dax.Formatter/AnalysisServices/ServerType.cs delete mode 100644 dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClient.cs delete mode 100644 dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClientMessageHandler.cs delete mode 100644 dotnet/src/Dax.Formatter/Client/Http/IDaxFormatterHttpClient.cs delete mode 100644 dotnet/src/Dax.Formatter/DaxFormatterClient.cs delete mode 100644 dotnet/src/Dax.Formatter/GlobalSuppressions.cs delete mode 100644 dotnet/src/Dax.Formatter/IDaxFormatterClient.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterError.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterLineStyle.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterMultipleRequest.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterRequest.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterResponse.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterSeparatorStyle.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterSingleRequest.cs delete mode 100644 dotnet/src/Dax.Formatter/Models/DaxFormatterSpacingStyle.cs delete mode 100644 dotnet/src/Dax.Formatter/Security/SecurityHelpers.cs delete mode 100644 dotnet/src/Dax.Formatter/Serialization/DictionaryLookupNamingPolicy.cs delete mode 100644 dotnet/src/Dax.Formatter/Serialization/JsonDaxFormatterSpacingStyleConverter.cs delete mode 100644 dotnet/src/Dax.Formatter/Serialization/JsonEnumMemberConverter.cs delete mode 100644 dotnet/src/Dax.Formatter/Serialization/JsonNamingPolicyDecorator.cs delete mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs delete mode 100644 dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterMultipleRequestTests.cs delete mode 100644 dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterSingleRequestTests.cs delete mode 100644 dotnet/tests/Dax.Formatter.Tests/Security/SecurityHelpersTests.cs diff --git a/dotnet/samples/Directory.Build.props b/dotnet/samples/Directory.Build.props deleted file mode 100644 index 058246e..0000000 --- a/dotnet/samples/Directory.Build.props +++ /dev/null @@ -1 +0,0 @@ - diff --git a/dotnet/samples/Directory.Build.targets b/dotnet/samples/Directory.Build.targets deleted file mode 100644 index 058246e..0000000 --- a/dotnet/samples/Directory.Build.targets +++ /dev/null @@ -1 +0,0 @@ - diff --git a/dotnet/samples/GettingStarted/BasicFormatter.csproj b/dotnet/samples/GettingStarted/BasicFormatter.csproj deleted file mode 100644 index 1382696..0000000 --- a/dotnet/samples/GettingStarted/BasicFormatter.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - net8.0 - - - - - - - \ No newline at end of file diff --git a/dotnet/samples/GettingStarted/Program.cs b/dotnet/samples/GettingStarted/Program.cs deleted file mode 100644 index f7427ab..0000000 --- a/dotnet/samples/GettingStarted/Program.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Dax.Formatter; -using Dax.Formatter.Models; -using System; -using System.Threading.Tasks; - -namespace BasicFormatter -{ - public class Program - { - private static readonly string DaxSingleExpression = "[X] := CALCULATE(SUM(Sales[Amount]), USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))"; - - private static readonly string[] DaxMultipleExpressions = new[] - { - "evaluate('Table') order by 'Table'[Column]", - "[X] := CALCULATE(SUM(Sales[Amount]), USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))", - "EVALUATE FILTER(Customer, Customer[name] = \"TestUser\")", - }; - - public static async Task Main() - { - await FormatSingleExpression(); - - await FormatSingleRequest(); - - await FormatMultipleExpressions(); - - await FormatMultipleRequests(); - - await FormatInvalidExpression(); - } - - private static async Task FormatSingleExpression() - { - var formatter = new DaxFormatterClient(); - - var response = await formatter.FormatAsync(DaxSingleExpression); - - Console.WriteLine(response.Formatted); - } - - private static async Task FormatSingleRequest() - { - var formatter = new DaxFormatterClient(); - - var request = new DaxFormatterSingleRequest - { - Dax = DaxSingleExpression, - - DatabaseName = "MyDatabaseName", - ServerName = "MyServerName", - - ListSeparator = ',', - DecimalSeparator = '.', - MaxLineLength = DaxFormatterLineStyle.LongLine, - SkipSpaceAfterFunctionName = DaxFormatterSpacingStyle.BestPractice, - - ServerMode = Dax.Formatter.AnalysisServices.ServerMode.Tabular, - ServerType = Dax.Formatter.AnalysisServices.ServerType.AnalysisServices, - ServerEdition = Dax.Formatter.AnalysisServices.ServerEdition.Enterprise, - ServerLocation = Dax.Formatter.AnalysisServices.ServerLocation.OnPremise, - }; - - var response = await formatter.FormatAsync(request); - - Console.WriteLine(response.Formatted); - } - - private static async Task FormatMultipleExpressions() - { - var formatter = new DaxFormatterClient(); - - var responses = await formatter.FormatAsync(DaxMultipleExpressions); - - foreach (var response in responses) - { - Console.WriteLine(response.Formatted); - } - } - - private static async Task FormatMultipleRequests() - { - var formatter = new DaxFormatterClient(); - - var request = new DaxFormatterMultipleRequest - { - DatabaseName = "MyDatabaseName", - ServerName = "MyServerName", - - ListSeparator = ',', - DecimalSeparator = '.', - MaxLineLength = DaxFormatterLineStyle.LongLine, - SkipSpaceAfterFunctionName = DaxFormatterSpacingStyle.BestPractice, - - ServerMode = Dax.Formatter.AnalysisServices.ServerMode.Tabular, - ServerType = Dax.Formatter.AnalysisServices.ServerType.AnalysisServices, - ServerEdition = Dax.Formatter.AnalysisServices.ServerEdition.Enterprise, - ServerLocation = Dax.Formatter.AnalysisServices.ServerLocation.OnPremise, - }; - - request.Dax.AddRange(DaxMultipleExpressions); - - var responses = await formatter.FormatAsync(request); - - foreach (var response in responses) - { - Console.WriteLine(response.Formatted); - } - } - - private static async Task FormatInvalidExpression() - { - var formatter = new DaxFormatterClient(); - - var invalidExpression = "[X] := SUMX ( Sales[Amount] ), )"; - - var response = await formatter.FormatAsync(invalidExpression); - - Console.WriteLine($"Formatted '{ response.Formatted }' "); - - foreach (var error in response.Errors) - { - Console.WriteLine($"Line { error.Line }, Column { error.Column }, Message { error.Message }"); - } - } - } -} diff --git a/dotnet/samples/GettingStarted/getting-started.sln b/dotnet/samples/GettingStarted/getting-started.sln deleted file mode 100644 index b7e3856..0000000 --- a/dotnet/samples/GettingStarted/getting-started.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30907.101 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BasicFormatter", "BasicFormatter.csproj", "{DCB16BCF-E1E2-45FA-8998-1B09C90519EF}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DCB16BCF-E1E2-45FA-8998-1B09C90519EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DCB16BCF-E1E2-45FA-8998-1B09C90519EF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DCB16BCF-E1E2-45FA-8998-1B09C90519EF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DCB16BCF-E1E2-45FA-8998-1B09C90519EF}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {8FB67FFF-1D34-4986-B502-2ADAFD56C9EF} - EndGlobalSection -EndGlobal diff --git a/dotnet/src/Dax.Formatter/AnalysisServices/ServerEdition.cs b/dotnet/src/Dax.Formatter/AnalysisServices/ServerEdition.cs deleted file mode 100644 index 4f3160b..0000000 --- a/dotnet/src/Dax.Formatter/AnalysisServices/ServerEdition.cs +++ /dev/null @@ -1,65 +0,0 @@ -namespace Dax.Formatter.AnalysisServices -{ - // - // Summary: - // Specifies an enumeration of server edition. - public enum ServerEdition - { - // - // Summary: - // The Standard edition. - Standard, - // - // Summary: - // The Standard64 edition. - Standard64, - // - // Summary: - // The Enterprise edition. - Enterprise, - // - // Summary: - // The Enterprise64 edition. - Enterprise64, - // - // Summary: - // The Developer edition. - Developer, - // - // Summary: - // The Developer64 edition. - Developer64, - // - // Summary: - // The Evaluation edition. - Evaluation, - // - // Summary: - // The Evaluation64 edition. - Evaluation64, - // - // Summary: - // The LocalCube edition. - LocalCube, - // - // Summary: - // The LocalCube64 edition. - LocalCube64, - // - // Summary: - // The BusinessIntelligence edition. - BusinessIntelligence, - // - // Summary: - // The BusinessIntelligence64 edition. - BusinessIntelligence64, - // - // Summary: - // The EnterpriseCore edition. - EnterpriseCore, - // - // Summary: - // The EnterpriseCore64 edition. - EnterpriseCore64 - } -} diff --git a/dotnet/src/Dax.Formatter/AnalysisServices/ServerLocation.cs b/dotnet/src/Dax.Formatter/AnalysisServices/ServerLocation.cs deleted file mode 100644 index 8ab1196..0000000 --- a/dotnet/src/Dax.Formatter/AnalysisServices/ServerLocation.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Dax.Formatter.AnalysisServices -{ - /// - /// Location of the analysis server - /// - public enum ServerLocation - { - /// - /// Server is an on-premise server - /// - OnPremise, - /// - /// Server is an Azure server - /// - Azure - } -} diff --git a/dotnet/src/Dax.Formatter/AnalysisServices/ServerMode.cs b/dotnet/src/Dax.Formatter/AnalysisServices/ServerMode.cs deleted file mode 100644 index d105fe9..0000000 --- a/dotnet/src/Dax.Formatter/AnalysisServices/ServerMode.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Dax.Formatter.AnalysisServices -{ - /// - /// Specifies the server mode used. For more information about server modes and how to set the server deployment mode, see Enable a Standalone VertiPAq Engine Instance. - /// - public enum ServerMode - { - /// - /// Classic OLAP and Data Mining mode. - /// - /// - Multidimensional, - /// - /// SharePoint Integration mode. - /// - /// - SharePoint, - /// - /// Specifies that the storage mode is proprietary Analysis Services xVelocity in-memory analytics engine (VertiPaq). - /// - /// - Tabular, - /// - /// ??? - /// - Default - } -} diff --git a/dotnet/src/Dax.Formatter/AnalysisServices/ServerType.cs b/dotnet/src/Dax.Formatter/AnalysisServices/ServerType.cs deleted file mode 100644 index 0fa9c7e..0000000 --- a/dotnet/src/Dax.Formatter/AnalysisServices/ServerType.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace Dax.Formatter.AnalysisServices -{ - using System.Runtime.Serialization; - - [DataContract] - public enum ServerType - { - [EnumMember(Value = "SSAS")] - AnalysisServices, - - [EnumMember(Value = "PBI Desktop")] - PowerBIDesktop, - - [EnumMember(Value = "PBI Report Server")] - PowerBIReportServer, - - [EnumMember(Value = "PowerPivot")] - PowerPivot, - - [EnumMember(Value = "SSDT")] - SSDT, - - [EnumMember(Value = "AzureAS")] - AzureAnalysisServices, - - [EnumMember(Value = "PBI Service")] - PowerBIService, - - [EnumMember(Value = "Offline")] - Offline - - } -} diff --git a/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClient.cs b/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClient.cs deleted file mode 100644 index 0cf5566..0000000 --- a/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClient.cs +++ /dev/null @@ -1,84 +0,0 @@ -namespace Dax.Formatter.Client.Http -{ - using Dax.Formatter.Models; - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using System.Net.Http.Headers; - using System.Text; - using System.Text.Json; - using System.Text.Json.Serialization; - using System.Threading; - using System.Threading.Tasks; - - internal sealed class DaxFormatterHttpClient : IDaxFormatterHttpClient, IDisposable - { - private const string MediaTypeNamesApplicationJson = "application/json"; - private const int DaxFormatterTimeoutSeconds = 60; - - private readonly JsonSerializerOptions _serializerOptions; - private readonly HttpClient _httpClient; - private readonly string? _application; - private readonly string? _version; - - public DaxFormatterHttpClient(string? application, string? version) - { - _application = application; - _version = version; - - var handler = new DaxFormatterHttpClientMessageHandler(); - - _httpClient = new HttpClient(handler, disposeHandler: true); - _httpClient.Timeout = TimeSpan.FromSeconds(DaxFormatterTimeoutSeconds); - _httpClient.DefaultRequestHeaders.Clear(); - _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNamesApplicationJson)); - _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue(nameof(DecompressionMethods.GZip))); - - _serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web); - _serializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - } - - public async Task FormatAsync(DaxFormatterSingleRequest request, CancellationToken cancellationToken) - { - request.CallerApp = _application; - request.CallerVersion = _version; - - var message = await FormatImplAsync(request, cancellationToken).ConfigureAwait(false); - return JsonSerializer.Deserialize(message, _serializerOptions); - } - - public async Task> FormatAsync(DaxFormatterMultipleRequest request, CancellationToken cancellationToken) - { - request.CallerApp = _application; - request.CallerVersion = _version; - - var message = await FormatImplAsync(request, cancellationToken).ConfigureAwait(false); - var result = JsonSerializer.Deserialize>(message, _serializerOptions); - return result ?? Array.Empty(); - } - - private async Task FormatImplAsync(T request, CancellationToken cancellationToken) where T : DaxFormatterRequest - { - cancellationToken.ThrowIfCancellationRequested(); - - var json = JsonSerializer.Serialize(request, _serializerOptions); - var uri = request.DaxTextFormatUri; - - using var content = new StringContent(json, Encoding.UTF8, MediaTypeNamesApplicationJson); - using var response = await _httpClient.PostAsync(uri, content, cancellationToken).ConfigureAwait(false); - response.EnsureSuccessStatusCode(); - -#if NETSTANDARD - return await response.Content.ReadAsStringAsync().ConfigureAwait(false); -#elif NET6_0_OR_GREATER - return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); -#endif - } - - public void Dispose() - { - _httpClient.Dispose(); - } - } -} diff --git a/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClientMessageHandler.cs b/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClientMessageHandler.cs deleted file mode 100644 index 900c168..0000000 --- a/dotnet/src/Dax.Formatter/Client/Http/DaxFormatterHttpClientMessageHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Dax.Formatter.Client.Http -{ - using System.Net; - using System.Net.Http; - - internal class DaxFormatterHttpClientMessageHandler : HttpClientHandler - { - public DaxFormatterHttpClientMessageHandler() - { - AutomaticDecompression = DecompressionMethods.GZip; - } - } -} diff --git a/dotnet/src/Dax.Formatter/Client/Http/IDaxFormatterHttpClient.cs b/dotnet/src/Dax.Formatter/Client/Http/IDaxFormatterHttpClient.cs deleted file mode 100644 index 696f3a0..0000000 --- a/dotnet/src/Dax.Formatter/Client/Http/IDaxFormatterHttpClient.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Dax.Formatter.Client.Http -{ - using Dax.Formatter.Models; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - internal interface IDaxFormatterHttpClient - { - void Dispose(); - - Task FormatAsync(DaxFormatterSingleRequest request, CancellationToken cancellationToken); - - Task> FormatAsync(DaxFormatterMultipleRequest request, CancellationToken cancellationToken); - } -} \ No newline at end of file diff --git a/dotnet/src/Dax.Formatter/Dax.Formatter.csproj b/dotnet/src/Dax.Formatter/Dax.Formatter.csproj index a32b764..2658148 100644 --- a/dotnet/src/Dax.Formatter/Dax.Formatter.csproj +++ b/dotnet/src/Dax.Formatter/Dax.Formatter.csproj @@ -1,15 +1,18 @@ - netstandard2.0;net8.0;net10.0 + netstandard2.0;net10.0 en-US true + true + true + true Dax.Formatter SQLBI Alberto Spelta, Marco Russo Dax Formatter client libraries - This client library connects to daxformatter.com service to format DAX expressions. + Client library for the DAX Formatter service (daxformatter.com): formats DAX queries, measures, columns and functions, one or thousands in a call, and reports their syntax errors. Dax.Formatter DAX;FORMATTER;SQLBI;TABULAR;SSAS package-icon.png @@ -33,15 +36,4 @@ - - Dax.Formatter .NET Standard 2.0 - - - Dax.Formatter .NET 8.0 - - - Dax.Formatter .NET 10.0 - - - diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs deleted file mode 100644 index 54e18e9..0000000 --- a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace Dax.Formatter -{ - using Dax.Formatter.Client.Http; - using Dax.Formatter.Models; - using System; - using System.Collections.Generic; - using System.Reflection; - using System.Threading; - using System.Threading.Tasks; - - public sealed class DaxFormatterClient : IDaxFormatterClient, IDisposable - { - private readonly DaxFormatterHttpClient _formatter; - - public DaxFormatterClient(string? application = null, string? version = null) - { - if (application == null || version == null) - { - var assembly = Assembly.GetEntryAssembly(); - if (assembly != null) - { - var assemblyName = assembly.GetName(); - var assemblyAttribute = assembly.GetCustomAttribute(); - - if (version == null) - version = assemblyAttribute?.Version; - - if (application == null) - application = assemblyName.Name; - } - } - - _formatter = new DaxFormatterHttpClient(application, version); - } - - public async Task FormatAsync(string expression, CancellationToken cancellationToken = default) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - - return response; - } - - public async Task> FormatAsync(IEnumerable expressions, CancellationToken cancellationToken = default) - { - var request = DaxFormatterMultipleRequest.CreateFrom(expressions); - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - - return response; - } - - public async Task FormatAsync(DaxFormatterSingleRequest request, CancellationToken cancellationToken = default) - { - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - return response; - } - - public async Task> FormatAsync(DaxFormatterMultipleRequest request, CancellationToken cancellationToken = default) - { - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - return response; - } - - #region IDisposable - - public void Dispose() - { - _formatter.Dispose(); - } - - #endregion - } -} diff --git a/dotnet/src/Dax.Formatter/GlobalSuppressions.cs b/dotnet/src/Dax.Formatter/GlobalSuppressions.cs deleted file mode 100644 index ea59d95..0000000 --- a/dotnet/src/Dax.Formatter/GlobalSuppressions.cs +++ /dev/null @@ -1,8 +0,0 @@ -// This file is used by Code Analysis to maintain SuppressMessage -// attributes that are applied to this project. -// Project-level suppressions either have no target or are given -// a specific target and scoped to a namespace, type, member, etc. - -using System.Diagnostics.CodeAnalysis; - -[assembly: SuppressMessage("Style", "IDE0017:Simplify object initialization", Justification = "", Scope = "member", Target = "~M:Dax.Formatter.Client.Http.DaxFormatterHttpClient.#ctor(System.String,System.String)")] diff --git a/dotnet/src/Dax.Formatter/IDaxFormatterClient.cs b/dotnet/src/Dax.Formatter/IDaxFormatterClient.cs deleted file mode 100644 index 99fe99c..0000000 --- a/dotnet/src/Dax.Formatter/IDaxFormatterClient.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Dax.Formatter -{ - using Dax.Formatter.Models; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - public interface IDaxFormatterClient - { - Task FormatAsync(string expression, CancellationToken cancellationToken = default); - - Task> FormatAsync(IEnumerable expressions, CancellationToken cancellationToken = default); - - Task FormatAsync(DaxFormatterSingleRequest request, CancellationToken cancellationToken = default); - - Task> FormatAsync(DaxFormatterMultipleRequest request, CancellationToken cancellationToken = default); - } -} \ No newline at end of file diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterError.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterError.cs deleted file mode 100644 index d606d4e..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterError.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Dax.Formatter.Models -{ - public class DaxFormatterError - { - public int? Line { get; set; } - - public int? Column { get; set; } - - public string? Message { get; set; } - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterLineStyle.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterLineStyle.cs deleted file mode 100644 index 82dfd5b..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterLineStyle.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Dax.Formatter.Models -{ - public enum DaxFormatterLineStyle - { - LongLine = 0, - - ShortLine = 1, - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterMultipleRequest.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterMultipleRequest.cs deleted file mode 100644 index 3caca39..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterMultipleRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Dax.Formatter.Models -{ - using System; - using System.Collections.Generic; - - public class DaxFormatterMultipleRequest : DaxFormatterRequest - { - internal static DaxFormatterMultipleRequest CreateFrom(IEnumerable expressions) - { - var request = new DaxFormatterMultipleRequest(); - request.Dax.AddRange(expressions); - - return request; - } - - internal override Uri DaxTextFormatUri { get; } = new Uri("https://api.daxformatter.com/api/daxtextformatmulti"); - - public List Dax { get; set; } = new List(); - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterRequest.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterRequest.cs deleted file mode 100644 index 435b129..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterRequest.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace Dax.Formatter.Models -{ - using Dax.Formatter.AnalysisServices; - using Dax.Formatter.Security; - using Dax.Formatter.Serialization; - using System; - using System.Text.Json.Serialization; - - public abstract class DaxFormatterRequest - { - private string? _serverName; - private string? _databaseName; - - internal abstract Uri DaxTextFormatUri { get; } - - public DaxFormatterRequest() - { - } - - public string? ServerName - { - get => _serverName; - set => _serverName = value.ToHashSHA256(); - } - - /// - /// Values: null, "Enterprise64", "Developer64", "Standard64" - /// In DISCOVER_XML_METADATA it is in /d:Edition node - /// - public ServerEdition? ServerEdition { get; set; } - - [JsonConverter(typeof(JsonEnumMemberConverter))] - public ServerType? ServerType { get; set; } - - /// - /// Values: null, "SharePoint", "Tabular" - /// In DISCOVER_XML_METADATA it is in ServerMode item - /// - public ServerMode? ServerMode { get; set; } - - /// - /// Values: null, "OnPremise", "Azure" - /// In DISCOVER_XML_METADATA it is in /ddl400:ServerLocation node - /// - public ServerLocation? ServerLocation { get; set; } - - /// - /// Example: "14.0.800.192" - /// - public string? ServerVersion { get; set; } - - public string? DatabaseName - { - get => _databaseName; - set => _databaseName = value.ToHashSHA256(); - } - - public string? DatabaseCompatibilityLevel { get; set; } - - public DaxFormatterLineStyle? MaxLineLength { get; set; } = DaxFormatterLineStyle.LongLine; - - [JsonConverter(typeof(JsonDaxFormatterSpacingStyleConverter))] - public DaxFormatterSpacingStyle? SkipSpaceAfterFunctionName { get; set; } = DaxFormatterSpacingStyle.BestPractice; - - public char ListSeparator { get; set; } = ','; - - public char DecimalSeparator { get; set; } = '.'; - - public string? CallerApp { get; set; } - - public string? CallerVersion { get; set; } - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterResponse.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterResponse.cs deleted file mode 100644 index c9c6e48..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterResponse.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Dax.Formatter.Models -{ - using System.Collections.Generic; - - public class DaxFormatterResponse - { - public string? Formatted { get; set; } - - public List? Errors { get; set; } - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterSeparatorStyle.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterSeparatorStyle.cs deleted file mode 100644 index e8b6120..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterSeparatorStyle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Dax.Formatter.Models -{ - public enum DaxFormatterSeparatorStyle - { - US_UK = 0, - - Others = 1, - - Automatic = US_UK, - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterSingleRequest.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterSingleRequest.cs deleted file mode 100644 index 48dd939..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterSingleRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Dax.Formatter.Models -{ - using System; - - public class DaxFormatterSingleRequest : DaxFormatterRequest - { - internal static DaxFormatterSingleRequest CreateFrom(string expression) - { - var request = new DaxFormatterSingleRequest - { - Dax = expression - }; - return request; - } - - internal override Uri DaxTextFormatUri { get; } = new Uri("https://api.daxformatter.com/api/daxtextformat"); - - public string? Dax { get; set; } - } -} diff --git a/dotnet/src/Dax.Formatter/Models/DaxFormatterSpacingStyle.cs b/dotnet/src/Dax.Formatter/Models/DaxFormatterSpacingStyle.cs deleted file mode 100644 index f152ce7..0000000 --- a/dotnet/src/Dax.Formatter/Models/DaxFormatterSpacingStyle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Dax.Formatter.Models -{ - public enum DaxFormatterSpacingStyle - { - SpaceAfterFunction = 0, - - NoSpaceAfterFunction = 1, - - BestPractice = SpaceAfterFunction, - } -} diff --git a/dotnet/src/Dax.Formatter/Security/SecurityHelpers.cs b/dotnet/src/Dax.Formatter/Security/SecurityHelpers.cs deleted file mode 100644 index b1fd570..0000000 --- a/dotnet/src/Dax.Formatter/Security/SecurityHelpers.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Dax.Formatter.Security -{ - using System.Security.Cryptography; - using System.Text; - - internal static class SecurityHelpers - { - public static string? ToHashSHA256(this string? value) - { - if (value == null) - return null; - - var stringBuilder = new StringBuilder(); - var buffer = Encoding.UTF8.GetBytes(value); - var count = Encoding.UTF8.GetByteCount(value); - - using (var algorithm = SHA256.Create()) - { - var bytes = algorithm.ComputeHash(buffer, offset: 0, count); - - foreach (var @byte in bytes) - stringBuilder.Append(@byte.ToString("x2")); - } - - return stringBuilder.ToString(); - } - } -} diff --git a/dotnet/src/Dax.Formatter/Serialization/DictionaryLookupNamingPolicy.cs b/dotnet/src/Dax.Formatter/Serialization/DictionaryLookupNamingPolicy.cs deleted file mode 100644 index b9e8b42..0000000 --- a/dotnet/src/Dax.Formatter/Serialization/DictionaryLookupNamingPolicy.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Dax.Formatter.Serialization -{ - using System; - using System.Collections.Generic; - using System.Text.Json; - - internal class DictionaryLookupNamingPolicy : JsonNamingPolicyDecorator - { - private readonly Dictionary _dictionary; - - public DictionaryLookupNamingPolicy(Dictionary dictionary, JsonNamingPolicy? policy) : base(policy) => _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary)); - - public override string ConvertName(string name) => _dictionary.TryGetValue(name, out var value) ? value : base.ConvertName(name); - } -} diff --git a/dotnet/src/Dax.Formatter/Serialization/JsonDaxFormatterSpacingStyleConverter.cs b/dotnet/src/Dax.Formatter/Serialization/JsonDaxFormatterSpacingStyleConverter.cs deleted file mode 100644 index c5f9486..0000000 --- a/dotnet/src/Dax.Formatter/Serialization/JsonDaxFormatterSpacingStyleConverter.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace Dax.Formatter.Serialization -{ - using Dax.Formatter.Models; - using System; - using System.Text.Json; - using System.Text.Json.Serialization; - - internal class JsonDaxFormatterSpacingStyleConverter : JsonConverter - { - public override DaxFormatterSpacingStyle Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) - { - return reader.TokenType switch - { - JsonTokenType.True => DaxFormatterSpacingStyle.NoSpaceAfterFunction, - JsonTokenType.False => DaxFormatterSpacingStyle.SpaceAfterFunction, - _ => throw new JsonException($"Unsupperted { nameof(DaxFormatterSpacingStyle) } token type [{ reader.TokenType }]"), - }; - } - - public override void Write(Utf8JsonWriter writer, DaxFormatterSpacingStyle value, JsonSerializerOptions options) - { - switch (value) - { - case DaxFormatterSpacingStyle.SpaceAfterFunction: - writer.WriteBooleanValue(false); - break; - case DaxFormatterSpacingStyle.NoSpaceAfterFunction: - writer.WriteBooleanValue(true); - break; - default: - throw new JsonException($"Unsupperted DaxFormatterSpacingStyle [{ value }]"); - } - } - } -} diff --git a/dotnet/src/Dax.Formatter/Serialization/JsonEnumMemberConverter.cs b/dotnet/src/Dax.Formatter/Serialization/JsonEnumMemberConverter.cs deleted file mode 100644 index 48e8345..0000000 --- a/dotnet/src/Dax.Formatter/Serialization/JsonEnumMemberConverter.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace Dax.Formatter.Serialization -{ - using System; - using System.Linq; - using System.Reflection; - using System.Runtime.Serialization; - using System.Text.Json; - using System.Text.Json.Serialization; - - internal class JsonEnumMemberConverter : JsonConverterFactory - { - private readonly bool _allowIntegerValues; - private readonly JsonNamingPolicy? _namingPolicy; - private readonly JsonStringEnumConverter _baseConverter; - - public JsonEnumMemberConverter() - : this(namingPolicy: null, allowIntegerValues: true) - { - } - - public JsonEnumMemberConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true) - { - _namingPolicy = namingPolicy; - _allowIntegerValues = allowIntegerValues; - _baseConverter = new JsonStringEnumConverter(namingPolicy, allowIntegerValues); - } - - public override bool CanConvert(Type typeToConvert) => _baseConverter.CanConvert(typeToConvert); - - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) - { - var query = from field in typeToConvert.GetFields(BindingFlags.Public | BindingFlags.Static) - let attr = field.GetCustomAttribute() - where attr != null - select (field.Name, attr.Value); - - var dictionary = query.ToDictionary((p) => p.Name, (p) => p.Value); - if (dictionary.Count > 0) - { - var namingPolicy = new DictionaryLookupNamingPolicy(dictionary, _namingPolicy); - var converter = new JsonStringEnumConverter(namingPolicy, _allowIntegerValues).CreateConverter(typeToConvert, options); - - return converter; - } - - return _baseConverter.CreateConverter(typeToConvert, options); - } - } -} diff --git a/dotnet/src/Dax.Formatter/Serialization/JsonNamingPolicyDecorator.cs b/dotnet/src/Dax.Formatter/Serialization/JsonNamingPolicyDecorator.cs deleted file mode 100644 index 92d09ac..0000000 --- a/dotnet/src/Dax.Formatter/Serialization/JsonNamingPolicyDecorator.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Dax.Formatter.Serialization -{ - using System.Text.Json; - - internal class JsonNamingPolicyDecorator : JsonNamingPolicy - { - readonly JsonNamingPolicy? _policy; - - public JsonNamingPolicyDecorator(JsonNamingPolicy? policy) => _policy = policy; - - public override string ConvertName(string name) => _policy == null ? name : _policy.ConvertName(name); - } -} diff --git a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj index 356ae63..a99c8d2 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -1,7 +1,7 @@  - net472;net8.0;net10.0 + net472;net10.0 false $(NoWarn);CA1707;CA1515 @@ -23,4 +23,8 @@ + + + + diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs deleted file mode 100644 index a82fe5f..0000000 --- a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs +++ /dev/null @@ -1,223 +0,0 @@ -namespace Dax.Formatter.Tests -{ - using Dax.Formatter.Models; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Xunit; - - public class DaxFormatterClientFixture - { - public DaxFormatterClient Client { get; private set; } - - public DaxFormatterClientFixture() => Client = new DaxFormatterClient(application: "Dax.Formatter.Tests", version: "develop"); - } - - public class DaxFormatterClientTests : IClassFixture - { - private readonly DaxFormatterClientFixture _fixture; - - public DaxFormatterClientTests(DaxFormatterClientFixture formatter) - { - _fixture = formatter; - } - - [Theory] - [InlineData(DaxFormatterSpacingStyle.SpaceAfterFunction, "[X]=IF(1=1,TRUE(),FALSE())", "[X] =\r\nIF ( 1 = 1, TRUE (), FALSE () )\r\n")] - [InlineData(DaxFormatterSpacingStyle.NoSpaceAfterFunction, "[X]=IF(1=1,TRUE(),FALSE())", "[X] =\r\nIF( 1 = 1, TRUE(), FALSE() )\r\n")] - public async Task DaxFormatterClient_FormatAsync_SpacingStyleIsHonored(DaxFormatterSpacingStyle spacingStyle, string expression, string expectedExpression) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - request.SkipSpaceAfterFunctionName = spacingStyle; - - var response = await _fixture.Client.FormatAsync(request); - Assert.NotNull(response); - - var actualExpression = response.Formatted; - Assert.Equal(expectedExpression, actualExpression); - } - - [Theory] - [InlineData(DaxFormatterLineStyle.LongLine, "[X]:=IF(1=1,1,0)", "[X] :=\r\nIF ( 1 = 1, 1, 0 )\r\n")] - [InlineData(DaxFormatterLineStyle.ShortLine, "[X]:=IF(1=1,1,0)", "[X] :=\r\nIF (\r\n 1 = 1,\r\n 1,\r\n 0\r\n)\r\n")] - public async Task DaxFormatterClient_FormatAsync_LineStyleIsHonored(DaxFormatterLineStyle lineStyle, string expression, string expectedExpression) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - request.MaxLineLength = lineStyle; - - var response = await _fixture.Client.FormatAsync(request); - Assert.NotNull(response); - - var actualExpression = response.Formatted; - Assert.Equal(expectedExpression, actualExpression); - } - - [Theory] - [InlineData("evaluate('Table')", "EVALUATE\r\n( 'Table' )\r\n")] - [InlineData("evaluate('Table') order by 'Table'[Column]", "EVALUATE\r\n( 'Table' )\r\nORDER BY 'Table'[Column]\r\n")] - [InlineData("[X] := CALCULATE(SUM(Sales[Sales Amount]), USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))", "[X] :=\r\nCALCULATE (\r\n SUM ( Sales[Sales Amount] ),\r\n USERELATIONSHIP ( Sales[DueDateKey], 'Date'[DateKey] )\r\n)\r\n")] - public async Task DaxFormatterClient_FormatAsync_SingleExpressionSucceded(string expression, string expectedExpression) - { - var response = await _fixture.Client.FormatAsync(expression); - - AssertSingleSucceded(response, expectedExpression); - } - - [Theory] - [InlineData("EVALUATE( Ta ble )", 0, 13)] - [InlineData("EVALUATE( Table ) ORDER Table[Column]", 0, 24)] - public async Task DaxFormatterClient_FormatAsync_SingleExpressionFails(string expression, int expectedErrorLine, int expectedErrorColumn) - { - var response = await _fixture.Client.FormatAsync(expression); - - AssertSingleFails(response, expectedErrorLine, expectedErrorColumn); - } - - [Theory] - [InlineData("evaluate('Table')", "EVALUATE\r\n( 'Table' )\r\n")] - [InlineData("evaluate('Table') order by 'Table'[Column]", "EVALUATE\r\n( 'Table' )\r\nORDER BY 'Table'[Column]\r\n")] - [InlineData("[X] := CALCULATE(SUM(Sales[Sales Amount]), USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))", "[X] :=\r\nCALCULATE (\r\n SUM ( Sales[Sales Amount] ),\r\n USERELATIONSHIP ( Sales[DueDateKey], 'Date'[DateKey] )\r\n)\r\n")] - public async Task DaxFormatterClient_FormatAsync_SingleRequestSucceded(string expression, string expectedExpression) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - var response = await _fixture.Client.FormatAsync(request); - - AssertSingleSucceded(response, expectedExpression); - } - - [Theory] - [InlineData("EVALUATE( Ta ble )", 0, 13)] - [InlineData("EVALUATE( Table ) ORDER Table[Column]", 0, 24)] - public async Task DaxFormatterClient_FormatAsync_SingleRequestFails(string expression, int expectedErrorLine, int expectedErrorColumn) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - var response = await _fixture.Client.FormatAsync(request); - - AssertSingleFails(response, expectedErrorLine, expectedErrorColumn); - } - - [Theory] - [InlineData("evaluate('Table')", "EVALUATE\r\n( 'Table' )\r\n", 10)] - [InlineData("evaluate('Table') order by 'Table'[Column]", "EVALUATE\r\n( 'Table' )\r\nORDER BY 'Table'[Column]\r\n", 10)] - [InlineData("[X] := CALCULATE(SUM(Sales[Sales Amount]), USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))", "[X] :=\r\nCALCULATE (\r\n SUM ( Sales[Sales Amount] ),\r\n USERELATIONSHIP ( Sales[DueDateKey], 'Date'[DateKey] )\r\n)\r\n", 10)] - public async Task DaxFormatterClient_FormatAsync_MultipleRequestSucceded(string expression, string expectedExpression, int repeat) - { - var expressions = Enumerable.Repeat(expression, repeat); - var request = DaxFormatterMultipleRequest.CreateFrom(expressions); - var response = await _fixture.Client.FormatAsync(request); - - AssertMultipleSucceded(response, expectedExpression, repeat); - } - - [Theory] - [InlineData("EVALUATE( Ta ble )", 5, 0, 13)] - [InlineData("EVALUATE( Table ) ORDER Table[Column]", 5, 0, 24)] - public async Task DaxFormatterClient_FormatAsync_MultipleRequestFails(string expression, int repeat, int expectedErrorLine, int expectedErrorColumn) - { - var expressions = Enumerable.Repeat(expression, repeat); - var request = DaxFormatterMultipleRequest.CreateFrom(expressions); - var response = await _fixture.Client.FormatAsync(request); - - AssertMultipleFails(response, repeat, expectedErrorLine, expectedErrorColumn); - } - - [Theory] - [InlineData("evaluate('Table')", "EVALUATE\r\n( 'Table' )\r\n", 10)] - public async Task DaxFormatterClient_FormatAsync_ParallelSingleExpressionSucceded(string expression, string expectedExpression, int repeat) - { - var tasks = Enumerable.Repeat(expression, repeat).AsParallel().Select((e) => _fixture.Client.FormatAsync(e)); - var responses = await Task.WhenAll(tasks); - - AssertParallelSingleSucceded(responses, expectedExpression, repeat); - } - - [Theory] - [InlineData("evaluate('Table')", "EVALUATE\r\n( 'Table' )\r\n", 10)] - public async Task DaxFormatterClient_FormatAsync_ParallelSingleRequestSucceded(string expression, string expectedExpression, int repeat) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - var tasks = Enumerable.Repeat(request, repeat).AsParallel().Select((r) => _fixture.Client.FormatAsync(r)); - var responses = await Task.WhenAll(tasks); - - AssertParallelSingleSucceded(responses, expectedExpression, repeat); - } - - private static void AssertSingleSucceded(DaxFormatterResponse? response, string expectedExpression) - { - Assert.NotNull(response); - Assert.NotNull(response.Formatted); - Assert.NotNull(response.Errors); - Assert.NotEmpty(response.Formatted); - Assert.Empty(response.Errors); - - var actualExpression = response.Formatted; - Assert.Equal(expectedExpression, actualExpression); - } - - private static void AssertSingleFails(DaxFormatterResponse? response, int expectedErrorLine, int expectedErrorColumn) - { - Assert.NotNull(response); - Assert.NotNull(response.Formatted); - Assert.NotNull(response.Errors); - Assert.Empty(response.Formatted); - Assert.Single(response.Errors); - - var actualError = response.Errors.Single(); - Assert.Equal(expectedErrorLine, actualError.Line); - Assert.Equal(expectedErrorColumn, actualError.Column); - } - - private static void AssertMultipleSucceded(IReadOnlyList responses, string expectedExpression, int repeat) - { - Assert.NotNull(responses); - Assert.Equal(repeat, responses.Count); - Assert.DoesNotContain(responses, (r) => r.Errors is null); - - var errors = responses.SelectMany((r) => r.Errors!); - Assert.Empty(errors); - - var formattedExpressions = responses.Select((r) => r.Formatted).Distinct(); - Assert.Single(formattedExpressions); - - var actualExpression = formattedExpressions.Single(); - Assert.Equal(expectedExpression, actualExpression); - } - - private static void AssertMultipleFails(IReadOnlyList responses, int repeat, int expectedErrorLine, int expectedErrorColumn) - { - Assert.NotNull(responses); - Assert.Equal(repeat, responses.Count); - Assert.DoesNotContain(responses, (r) => r.Errors is null); - - var errors = responses.SelectMany((r) => r.Errors!).ToList(); - Assert.Equal(repeat, errors.Count); - - var errorLines = errors.Select((e) => e.Line).Distinct(); - Assert.Single(errorLines); - - var actualErrorLine = errorLines.Single(); - Assert.Equal(expectedErrorLine, actualErrorLine); - - var errorColumns = errors.Select((e) => e.Column).Distinct(); - Assert.Single(errorColumns); - - var actualErrorColumn = errorColumns.Single(); - Assert.Equal(expectedErrorColumn, actualErrorColumn); - - var formattedExpressions = responses.Select((r) => r.Formatted).Distinct(); - Assert.Single(formattedExpressions); - - var actualExpression = formattedExpressions.Single(); - Assert.Equal(string.Empty, actualExpression); - } - - private static void AssertParallelSingleSucceded(DaxFormatterResponse?[] responses, string expectedExpression, int repeat) - { - Assert.NotNull(responses); - Assert.Equal(repeat, responses.Length); - - foreach (var response in responses) - AssertSingleSucceded(response, expectedExpression); - } - } -} diff --git a/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterMultipleRequestTests.cs b/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterMultipleRequestTests.cs deleted file mode 100644 index 57847e1..0000000 --- a/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterMultipleRequestTests.cs +++ /dev/null @@ -1,107 +0,0 @@ -namespace Dax.Formatter.Tests.Models -{ - using Dax.Formatter.AnalysisServices; - using Dax.Formatter.Models; - using System.Text.Json; - using Xunit; - - public class DaxFormatterMultipleRequestTests - { - [Fact] - public void DaxFormatterMultipleRequest_DaxIsNotNull() - { - var request = new DaxFormatterMultipleRequest(); - - Assert.NotNull(request.Dax); - } - - [Fact] - public void DaxFormatterMultipleRequest_SensitiveServerNameIsProtected() - { - var expected = "f4139cb312e198bedebf0d71198c27db761f5c4cab73da7dd2faea2672d082af"; - - var request = new DaxFormatterMultipleRequest() - { - ServerName = "MyServerName1" - }; - - Assert.Equal(expected, request.ServerName); - } - - [Fact] - public void DaxFormatterMultipleRequest_SensitiveDatabaseNameIsProtected() - { - var expected = "6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863"; - - var request = new DaxFormatterMultipleRequest() - { - DatabaseName = "MyDatabaseName1" - }; - - Assert.Equal(expected, request.DatabaseName); - } - - [Theory] - [InlineData(ServerType.AnalysisServices, "SSAS")] - [InlineData(ServerType.PowerBIDesktop, "PBI Desktop")] - [InlineData(ServerType.PowerBIReportServer, "PBI Report Server")] - [InlineData(ServerType.PowerPivot, "PowerPivot")] - [InlineData(ServerType.SSDT, "SSDT")] - [InlineData(ServerType.AzureAnalysisServices, "AzureAS")] - [InlineData(ServerType.PowerBIService, "PBI Service")] - [InlineData(ServerType.Offline, "Offline")] - public void DaxFormatterMultipleRequest_ServerTypeSerialization(ServerType serverType, string expectedServerType) - { - var request = new DaxFormatterMultipleRequest - { - ServerType = serverType - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterMultipleRequest.ServerType)); - var currentServerType = property.GetString(); - - Assert.Equal(expectedServerType, currentServerType); - } - - [Theory] - [InlineData(DaxFormatterLineStyle.LongLine, 0)] - [InlineData(DaxFormatterLineStyle.ShortLine, 1)] - public void DaxFormatterMultipleRequest_MaxLineLengthSerialization(DaxFormatterLineStyle lineStyle, int expectedLineStyle) - { - var request = new DaxFormatterMultipleRequest - { - MaxLineLength = lineStyle - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterMultipleRequest.MaxLineLength)); - var currentLineStyle = property.GetInt32(); - - Assert.Equal(expectedLineStyle, currentLineStyle); - } - - [Theory] - [InlineData(DaxFormatterSpacingStyle.NoSpaceAfterFunction, true)] - [InlineData(DaxFormatterSpacingStyle.SpaceAfterFunction, false)] - public void DaxFormatterMultipleRequest_SkipSpaceAfterFunctionNameSerialization(DaxFormatterSpacingStyle spacingStyle, bool expectedSpacingStyle) - { - var request = new DaxFormatterMultipleRequest - { - SkipSpaceAfterFunctionName = spacingStyle - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterMultipleRequest.SkipSpaceAfterFunctionName)); - var currentSpacingStyle = property.GetBoolean(); - - Assert.Equal(expectedSpacingStyle, currentSpacingStyle); - } - - private static JsonElement GetJsonProperty(DaxFormatterMultipleRequest request, string propertyName) - { - var json = JsonSerializer.Serialize(request); - var document = JsonDocument.Parse(json); - var property = document.RootElement.GetProperty(propertyName); - - return property; - } - } -} diff --git a/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterSingleRequestTests.cs b/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterSingleRequestTests.cs deleted file mode 100644 index cc43f98..0000000 --- a/dotnet/tests/Dax.Formatter.Tests/Models/DaxFormatterSingleRequestTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -namespace Dax.Formatter.Tests.Models -{ - using Dax.Formatter.AnalysisServices; - using Dax.Formatter.Models; - using System.Text.Json; - using Xunit; - - public class DaxFormatterSingleRequestTests - { - [Fact] - public void DaxFormatterSingleRequest_SensitiveServerNameIsProtected() - { - var expected = "f4139cb312e198bedebf0d71198c27db761f5c4cab73da7dd2faea2672d082af"; - - var request = new DaxFormatterSingleRequest() - { - ServerName = "MyServerName1" - }; - - Assert.Equal(expected, request.ServerName); - } - - [Fact] - public void DaxFormatterSingleRequest_SensitiveDatabaseNameIsProtected() - { - var expected = "6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863"; - - var request = new DaxFormatterSingleRequest() - { - DatabaseName = "MyDatabaseName1" - }; - - Assert.Equal(expected, request.DatabaseName); - } - - [Theory] - [InlineData(ServerType.AnalysisServices, "SSAS")] - [InlineData(ServerType.PowerBIDesktop, "PBI Desktop")] - [InlineData(ServerType.PowerBIReportServer, "PBI Report Server")] - [InlineData(ServerType.PowerPivot, "PowerPivot")] - [InlineData(ServerType.SSDT, "SSDT")] - [InlineData(ServerType.AzureAnalysisServices, "AzureAS")] - [InlineData(ServerType.PowerBIService, "PBI Service")] - [InlineData(ServerType.Offline, "Offline")] - public void DaxFormatterSingleRequest_ServerTypeSerialization(ServerType serverType, string expectedServerType) - { - var request = new DaxFormatterSingleRequest - { - ServerType = serverType - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterSingleRequest.ServerType)); - var currentServerType = property.GetString(); - - Assert.Equal(expectedServerType, currentServerType); - } - - [Theory] - [InlineData(DaxFormatterLineStyle.LongLine, 0)] - [InlineData(DaxFormatterLineStyle.ShortLine, 1)] - public void DaxFormatterSingleRequest_MaxLineLengthSerialization(DaxFormatterLineStyle lineStyle, int expectedLineStyle) - { - var request = new DaxFormatterSingleRequest - { - MaxLineLength = lineStyle - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterSingleRequest.MaxLineLength)); - var currentLineStyle = property.GetInt32(); - - Assert.Equal(expectedLineStyle, currentLineStyle); - } - - [Theory] - [InlineData(DaxFormatterSpacingStyle.NoSpaceAfterFunction, true)] - [InlineData(DaxFormatterSpacingStyle.SpaceAfterFunction, false)] - public void DaxFormatterSingleRequest_SkipSpaceAfterFunctionNameSerialization(DaxFormatterSpacingStyle spacingStyle, bool expectedSpacingStyle) - { - var request = new DaxFormatterSingleRequest - { - SkipSpaceAfterFunctionName = spacingStyle - }; - - var property = GetJsonProperty(request, nameof(DaxFormatterSingleRequest.SkipSpaceAfterFunctionName)); - var currentSpacingStyle = property.GetBoolean(); - - Assert.Equal(expectedSpacingStyle, currentSpacingStyle); - } - - private static JsonElement GetJsonProperty(DaxFormatterSingleRequest request, string propertyName) - { - var json = JsonSerializer.Serialize(request); - var document = JsonDocument.Parse(json); - var property = document.RootElement.GetProperty(propertyName); - - return property; - } - } -} diff --git a/dotnet/tests/Dax.Formatter.Tests/Security/SecurityHelpersTests.cs b/dotnet/tests/Dax.Formatter.Tests/Security/SecurityHelpersTests.cs deleted file mode 100644 index 21c2778..0000000 --- a/dotnet/tests/Dax.Formatter.Tests/Security/SecurityHelpersTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Dax.Formatter.Tests.Security -{ - using Dax.Formatter.Security; - using Xunit; - - public class SecurityHelpersTests - { - [Theory] - [InlineData("MyValue123456789$", "5f45bfb8ab5c9ea6fe0762974f7bbbe3602155c66d1139496fc2246c360a874b")] - [InlineData("1234567890??=", "cb0f4399a2850ee589414b82de85b736ced269035c48e4275be850a3162ba284")] - [InlineData("abcdefghiABCDEFGHI??=", "1bca6736f96f84e35fa921938f45ba981a6e3f6aa02bcf46763009d3614cf89d")] - [InlineData("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] - [InlineData(null, null)] - public void SecurityHelpers_ToHashSHA256_ComputeCorrectResult(string? value, string? expected) - { - var actual = value.ToHashSHA256(); - Assert.Equal(expected, actual); - } - } -} From 89f6d4a8d2cff49103580c7d800ba0a1ebe66b32 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:17:55 +0100 Subject: [PATCH 03/29] feat(dotnet)!: add the public model of the 2.0 client - add the options of the client and of a call, the kinds of text, the line, spacing and separator styles, and the optional description of the model with the known server types - add the result of a text, with the caller's item in its generic form, the syntax error with value equality, the progress value and the one exception of the client with its failure reason - add the polyfills that netstandard2.0 needs for nullable attributes and for the argument guards of .NET --- dotnet/src/Dax.Formatter/DaxFormatOptions.cs | 35 ++++++++ .../Dax.Formatter/DaxFormatProgressInfo.cs | 31 +++++++ dotnet/src/Dax.Formatter/DaxFormatResult.cs | 80 ++++++++++++++++++ .../Dax.Formatter/DaxFormatResult{TItem}.cs | 30 +++++++ .../DaxFormatterClientOptions.cs | 42 ++++++++++ .../Dax.Formatter/DaxFormatterException.cs | 84 +++++++++++++++++++ .../DaxFormatterFailureReason.cs | 32 +++++++ dotnet/src/Dax.Formatter/DaxKind.cs | 19 +++++ dotnet/src/Dax.Formatter/DaxLineStyle.cs | 17 ++++ dotnet/src/Dax.Formatter/DaxModelInfo.cs | 48 +++++++++++ dotnet/src/Dax.Formatter/DaxSeparatorStyle.cs | 17 ++++ dotnet/src/Dax.Formatter/DaxServerTypes.cs | 31 +++++++ dotnet/src/Dax.Formatter/DaxSpacingStyle.cs | 17 ++++ dotnet/src/Dax.Formatter/DaxSyntaxError.cs | 70 ++++++++++++++++ .../Dax.Formatter/Polyfills/ArgumentGuards.cs | 36 ++++++++ .../CallerArgumentExpressionAttribute.cs | 14 ++++ .../Polyfills/NullableAttributes.cs | 33 ++++++++ .../DaxFormatProgressInfoTests.cs | 21 +++++ .../DaxFormatResultTests.cs | 84 +++++++++++++++++++ .../DaxFormatterExceptionTests.cs | 47 +++++++++++ .../DaxSyntaxErrorTests.cs | 58 +++++++++++++ 21 files changed, 846 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/DaxFormatOptions.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatProgressInfo.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatResult.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatResult{TItem}.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatterClientOptions.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatterException.cs create mode 100644 dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs create mode 100644 dotnet/src/Dax.Formatter/DaxKind.cs create mode 100644 dotnet/src/Dax.Formatter/DaxLineStyle.cs create mode 100644 dotnet/src/Dax.Formatter/DaxModelInfo.cs create mode 100644 dotnet/src/Dax.Formatter/DaxSeparatorStyle.cs create mode 100644 dotnet/src/Dax.Formatter/DaxServerTypes.cs create mode 100644 dotnet/src/Dax.Formatter/DaxSpacingStyle.cs create mode 100644 dotnet/src/Dax.Formatter/DaxSyntaxError.cs create mode 100644 dotnet/src/Dax.Formatter/Polyfills/ArgumentGuards.cs create mode 100644 dotnet/src/Dax.Formatter/Polyfills/CallerArgumentExpressionAttribute.cs create mode 100644 dotnet/src/Dax.Formatter/Polyfills/NullableAttributes.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxFormatProgressInfoTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxFormatResultTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxSyntaxErrorTests.cs diff --git a/dotnet/src/Dax.Formatter/DaxFormatOptions.cs b/dotnet/src/Dax.Formatter/DaxFormatOptions.cs new file mode 100644 index 0000000..02d7ef0 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatOptions.cs @@ -0,0 +1,35 @@ +namespace Dax.Formatter; + +/// +/// The options of one formatting call. Every property has a default, so an instance is needed only to change one. +/// +public sealed class DaxFormatOptions +{ + /// + /// Gets or sets what the texts are. The default is . + /// + public DaxKind Kind { get; set; } + + /// + /// Gets or sets the length of the lines. The default is . + /// + public DaxLineStyle LineStyle { get; set; } + + /// + /// Gets or sets the spacing after a function name. The default is + /// . + /// + public DaxSpacingStyle SpacingStyle { get; set; } + + /// + /// Gets or sets the list and decimal separators that the texts use. The default is + /// . + /// + public DaxSeparatorStyle SeparatorStyle { get; set; } + + /// + /// Gets or sets the description of the model the texts come from. It is optional and does not change the + /// formatting: the service uses it for anonymous usage statistics. + /// + public DaxModelInfo? ModelInfo { get; set; } +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatProgressInfo.cs b/dotnet/src/Dax.Formatter/DaxFormatProgressInfo.cs new file mode 100644 index 0000000..7523e69 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatProgressInfo.cs @@ -0,0 +1,31 @@ +namespace Dax.Formatter; + +/// +/// The progress of a call that formats several texts. +/// +public sealed class DaxFormatProgressInfo +{ + /// + /// Initializes a new instance of the class. + /// + /// The number of texts whose result is ready. + /// The number of texts in the call. + public DaxFormatProgressInfo(int completed, int total) + { + ArgumentOutOfRangeException.ThrowIfNegative(completed); + ArgumentOutOfRangeException.ThrowIfNegative(total); + + Completed = completed; + Total = total; + } + + /// + /// Gets the number of texts whose result is ready. It never decreases during a call. + /// + public int Completed { get; } + + /// + /// Gets the number of texts in the call. + /// + public int Total { get; } +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatResult.cs b/dotnet/src/Dax.Formatter/DaxFormatResult.cs new file mode 100644 index 0000000..b343243 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatResult.cs @@ -0,0 +1,80 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Dax.Formatter; + +/// +/// The result of formatting one DAX text: the formatted text, or the syntax errors that the service found. +/// +public class DaxFormatResult +{ + private static readonly IReadOnlyList s_noErrors = []; + + private protected DaxFormatResult(string originalText, string? formattedText, IReadOnlyList errors) + { + OriginalText = originalText; + FormattedText = formattedText; + Errors = errors; + } + + /// + /// Gets the text that was given to the client. + /// + public string OriginalText { get; } + + /// + /// Gets a value indicating whether the text was formatted, which means that it has no syntax errors. + /// + [MemberNotNullWhen(true, nameof(FormattedText))] + public bool Succeeded => FormattedText is not null; + + /// + /// Gets the formatted text, without a final line break, or when + /// is . + /// + public string? FormattedText { get; } + + /// + /// Gets the syntax errors of the text. The list is empty when is + /// . + /// + public IReadOnlyList Errors { get; } + + /// + /// Creates the result of a text that was formatted. + /// + /// The text that was given to the client. + /// The formatted text. + /// A result whose is . + public static DaxFormatResult Success(string originalText, string formattedText) + { + ArgumentNullException.ThrowIfNull(originalText); + ArgumentNullException.ThrowIfNull(formattedText); + + return new DaxFormatResult(originalText, formattedText, s_noErrors); + } + + /// + /// Creates the result of a text that has syntax errors. + /// + /// The text that was given to the client. + /// The syntax errors of the text: at least one. + /// A result whose is . + public static DaxFormatResult Failure(string originalText, IEnumerable errors) + { + ArgumentNullException.ThrowIfNull(originalText); + ArgumentNullException.ThrowIfNull(errors); + + DaxSyntaxError[] copy = [.. errors]; + if (copy.Length == 0) + { + throw new ArgumentException("A failure needs at least one syntax error.", nameof(errors)); + } + + if (Array.IndexOf(copy, null) >= 0) + { + throw new ArgumentException("A syntax error is null.", nameof(errors)); + } + + return new DaxFormatResult(originalText, formattedText: null, Array.AsReadOnly(copy)); + } +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatResult{TItem}.cs b/dotnet/src/Dax.Formatter/DaxFormatResult{TItem}.cs new file mode 100644 index 0000000..1f5ef89 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatResult{TItem}.cs @@ -0,0 +1,30 @@ +namespace Dax.Formatter; + +/// +/// The result of formatting the DAX text of an item, with the item it belongs to. +/// +/// The type of the item, such as a measure of a model. +public sealed class DaxFormatResult : DaxFormatResult +{ + /// + /// Initializes a new instance of the class. + /// + /// The item the text belongs to. + /// The result of formatting the text of the item. + public DaxFormatResult(TItem item, DaxFormatResult result) + : base(GetOriginalText(result), result.FormattedText, result.Errors) + { + Item = item; + } + + /// + /// Gets the item the text belongs to. + /// + public TItem Item { get; } + + private static string GetOriginalText(DaxFormatResult result) + { + ArgumentNullException.ThrowIfNull(result); + return result.OriginalText; + } +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClientOptions.cs b/dotnet/src/Dax.Formatter/DaxFormatterClientOptions.cs new file mode 100644 index 0000000..ad80c0f --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterClientOptions.cs @@ -0,0 +1,42 @@ +namespace Dax.Formatter; + +/// +/// The options of a . The client copies them when it is created: a later change +/// to this object has no effect on it. +/// +public sealed class DaxFormatterClientOptions +{ + /// + /// Gets or sets the name of the calling application, which the service uses for usage statistics. The default + /// is the name of the entry assembly. + /// + public string? ApplicationName { get; set; } + + /// + /// Gets or sets the version of the calling application. The default is the file version of the entry assembly. + /// + public string? ApplicationVersion { get; set; } + + /// + /// Gets or sets the base address of the service. The default is https://api.daxformatter.com/. + /// + public Uri Endpoint { get; set; } = new Uri("https://api.daxformatter.com/"); + + /// + /// Gets or sets how long the client waits for the answer to one request, before it retries or gives up. The + /// default is 60 seconds. A call that needs several requests or retries can last longer. + /// + public TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(60); + + /// + /// Gets or sets how many times the client sends a request again after a failure that can be temporary. The + /// default is 2; 0 turns retries off. + /// + public int MaxRetries { get; set; } = 2; + + /// + /// Gets or sets how many requests one call can have in progress at the same time, when it has more texts than + /// one request carries. The default is 2. + /// + public int MaxConcurrentRequests { get; set; } = 2; +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatterException.cs b/dotnet/src/Dax.Formatter/DaxFormatterException.cs new file mode 100644 index 0000000..61ca7b5 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterException.cs @@ -0,0 +1,84 @@ +using System.Net; + +namespace Dax.Formatter; + +/// +/// The exception thrown when a call to the DAX Formatter service fails. A syntax error in a DAX text is not a +/// failure: it is part of the of that text. +/// +public sealed class DaxFormatterException : Exception +{ + /// + /// Initializes a new instance of the class. + /// + public DaxFormatterException() + { + } + + /// + /// Initializes a new instance of the class with a message. + /// + /// The message that describes the failure. + public DaxFormatterException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a message and the + /// exception that caused the failure. + /// + /// The message that describes the failure. + /// The exception that caused the failure. + public DaxFormatterException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with every detail of the + /// failure. The client uses it; it is public so that the tests of an application can create the exception. + /// + /// The message that describes the failure. + /// Why the call failed. + /// The HTTP status of the answer, when one arrived. + /// The identifier that the client gave to the request. + /// The identifier that the service gave to the request. + /// The exception that caused the failure, if any. + public DaxFormatterException( + string message, + DaxFormatterFailureReason reason, + HttpStatusCode? statusCode, + string? requestId, + string? serviceRequestId, + Exception? innerException) + : base(message, innerException) + { + Reason = reason; + StatusCode = statusCode; + RequestId = requestId; + ServiceRequestId = serviceRequestId; + } + + /// + /// Gets why the call failed. + /// + public DaxFormatterFailureReason Reason { get; } + + /// + /// Gets the HTTP status of the answer, or when no answer arrived. + /// + public HttpStatusCode? StatusCode { get; } + + /// + /// Gets the identifier that the client gave to the failed request and sent in the + /// DaxFormatter-Request-Id header. It is set also when no answer arrived. + /// + public string? RequestId { get; } + + /// + /// Gets the identifier that the service gave to the failed request, from the x-azure-ref header of the + /// answer, or when no answer arrived. + /// + public string? ServiceRequestId { get; } +} diff --git a/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs new file mode 100644 index 0000000..dd0e6e7 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs @@ -0,0 +1,32 @@ +namespace Dax.Formatter; + +/// +/// Why a call to the DAX Formatter service failed. +/// +public enum DaxFormatterFailureReason +{ + /// + /// The reason is not known. + /// + Unknown, + + /// + /// The service did not answer within the timeout of a request. + /// + Timeout, + + /// + /// The request did not reach the service, or its answer did not arrive. + /// + NetworkError, + + /// + /// The service answered with an HTTP status that is not a success. + /// + HttpError, + + /// + /// The service answered with something the client cannot use as the results of the request. + /// + InvalidResponse, +} diff --git a/dotnet/src/Dax.Formatter/DaxKind.cs b/dotnet/src/Dax.Formatter/DaxKind.cs new file mode 100644 index 0000000..72061e7 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxKind.cs @@ -0,0 +1,19 @@ +namespace Dax.Formatter; + +/// +/// Says what a DAX text is, so that the client knows how to send it to the service. +/// +public enum DaxKind +{ + /// + /// The text is sent as it is. Use it for a query, such as EVALUATE Sales, and for a text that + /// carries its own name, such as [Margin] := [Sales] - [Cost]. + /// + Auto, + + /// + /// The text is the DAX of one model object, without its name: a measure, a calculated column, a calculated + /// table, a calculation item or the body of a user-defined function. + /// + Expression, +} diff --git a/dotnet/src/Dax.Formatter/DaxLineStyle.cs b/dotnet/src/Dax.Formatter/DaxLineStyle.cs new file mode 100644 index 0000000..8f6b1b5 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxLineStyle.cs @@ -0,0 +1,17 @@ +namespace Dax.Formatter; + +/// +/// The length of the lines in the formatted text. +/// +public enum DaxLineStyle +{ + /// + /// Long lines: an expression stays on one line while it fits. + /// + LongLine, + + /// + /// Short lines: each argument of a function goes on a line of its own. + /// + ShortLine, +} diff --git a/dotnet/src/Dax.Formatter/DaxModelInfo.cs b/dotnet/src/Dax.Formatter/DaxModelInfo.cs new file mode 100644 index 0000000..56af669 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxModelInfo.cs @@ -0,0 +1,48 @@ +namespace Dax.Formatter; + +/// +/// The description of the model the DAX texts come from, for the anonymous usage statistics of the service. +/// Every property is optional, and none changes the formatting. +/// +public sealed class DaxModelInfo +{ + /// + /// Gets or sets the name of the server. The client sends only its SHA-256 hash, never the name. + /// + public string? ServerName { get; set; } + + /// + /// Gets or sets the name of the database. The client sends only its SHA-256 hash, never the name. + /// + public string? DatabaseName { get; set; } + + /// + /// Gets or sets the kind of server. has the values the service knows. + /// + public string? ServerType { get; set; } + + /// + /// Gets or sets the mode of the Analysis Services server, such as Tabular. + /// + public string? ServerMode { get; set; } + + /// + /// Gets or sets the edition of the Analysis Services server, such as Enterprise64. + /// + public string? ServerEdition { get; set; } + + /// + /// Gets or sets where the server runs, such as OnPremise or Azure. + /// + public string? ServerLocation { get; set; } + + /// + /// Gets or sets the version of the server, such as 16.0.143.21. + /// + public string? ServerVersion { get; set; } + + /// + /// Gets or sets the compatibility level of the database, such as 1600. + /// + public int? CompatibilityLevel { get; set; } +} diff --git a/dotnet/src/Dax.Formatter/DaxSeparatorStyle.cs b/dotnet/src/Dax.Formatter/DaxSeparatorStyle.cs new file mode 100644 index 0000000..5448368 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxSeparatorStyle.cs @@ -0,0 +1,17 @@ +namespace Dax.Formatter; + +/// +/// The list separator and the decimal separator that the DAX text uses, and that the formatted text keeps. +/// +public enum DaxSeparatorStyle +{ + /// + /// A comma between arguments and a point in decimal numbers: DIVIDE ( 1.5, 2 ). + /// + CommaAndPoint, + + /// + /// A semicolon between arguments and a comma in decimal numbers: DIVIDE ( 1,5; 2 ). + /// + SemicolonAndComma, +} diff --git a/dotnet/src/Dax.Formatter/DaxServerTypes.cs b/dotnet/src/Dax.Formatter/DaxServerTypes.cs new file mode 100644 index 0000000..a00e68a --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxServerTypes.cs @@ -0,0 +1,31 @@ +namespace Dax.Formatter; + +/// +/// The values of that the service knows. +/// +public static class DaxServerTypes +{ + /// SQL Server Analysis Services. + public const string AnalysisServices = "SSAS"; + + /// Power BI Desktop. + public const string PowerBIDesktop = "PBI Desktop"; + + /// Power BI Report Server. + public const string PowerBIReportServer = "PBI Report Server"; + + /// Power Pivot for Excel. + public const string PowerPivot = "PowerPivot"; + + /// The integrated workspace of SQL Server Data Tools. + public const string Ssdt = "SSDT"; + + /// Azure Analysis Services. + public const string AzureAnalysisServices = "AzureAS"; + + /// The Power BI service. + public const string PowerBIService = "PBI Service"; + + /// A model that is not on a server, such as a file. + public const string Offline = "Offline"; +} diff --git a/dotnet/src/Dax.Formatter/DaxSpacingStyle.cs b/dotnet/src/Dax.Formatter/DaxSpacingStyle.cs new file mode 100644 index 0000000..727eaaf --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxSpacingStyle.cs @@ -0,0 +1,17 @@ +namespace Dax.Formatter; + +/// +/// The spacing between a function name and its opening parenthesis in the formatted text. +/// +public enum DaxSpacingStyle +{ + /// + /// A space after the function name: SUM ( Sales[Amount] ). + /// + SpaceAfterFunction, + + /// + /// No space after the function name: SUM( Sales[Amount] ). + /// + NoSpaceAfterFunction, +} diff --git a/dotnet/src/Dax.Formatter/DaxSyntaxError.cs b/dotnet/src/Dax.Formatter/DaxSyntaxError.cs new file mode 100644 index 0000000..1a1092c --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxSyntaxError.cs @@ -0,0 +1,70 @@ +namespace Dax.Formatter; + +/// +/// A syntax error that the service found in a DAX text, with its position in that text. +/// +public sealed class DaxSyntaxError : IEquatable +{ + /// + /// Initializes a new instance of the class. + /// + /// The zero-based line of the error. + /// The zero-based column of the error. + /// The description of the error. + public DaxSyntaxError(int line, int column, string message) + { + ArgumentOutOfRangeException.ThrowIfNegative(line); + ArgumentOutOfRangeException.ThrowIfNegative(column); + ArgumentNullException.ThrowIfNull(message); + + Line = line; + Column = column; + Message = message; + } + + /// + /// Gets the zero-based line of the error in , where lines are + /// separated by a line feed. + /// + public int Line { get; } + + /// + /// Gets the zero-based column of the error: an index into the UTF-16 characters of the line. It equals the + /// length of the line when the error is at its end. + /// + public int Column { get; } + + /// + /// Gets the description of the error, as the service wrote it. + /// + public string Message { get; } + + /// + public bool Equals(DaxSyntaxError? other) + { + if (other is null) + { + return false; + } + + return Line == other.Line + && Column == other.Column + && string.Equals(Message, other.Message, StringComparison.Ordinal); + } + + /// + public override bool Equals(object? obj) + { + return Equals(obj as DaxSyntaxError); + } + + /// + public override int GetHashCode() + { + unchecked + { + var hash = (Line * 397) ^ Column; + return (hash * 397) ^ StringComparer.Ordinal.GetHashCode(Message); + } + } +} diff --git a/dotnet/src/Dax.Formatter/Polyfills/ArgumentGuards.cs b/dotnet/src/Dax.Formatter/Polyfills/ArgumentGuards.cs new file mode 100644 index 0000000..3dc5272 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Polyfills/ArgumentGuards.cs @@ -0,0 +1,36 @@ +#if !NET +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace System; + +// The guard methods of .NET, for the target that does not have them: the shared code calls them by their .NET names. +internal static class ArgumentGuards +{ + extension(ArgumentNullException) + { + public static void ThrowIfNull( + [NotNull] object? argument, + [CallerArgumentExpression(nameof(argument))] string? paramName = null) + { + if (argument is null) + { + throw new ArgumentNullException(paramName); + } + } + } + + extension(ArgumentOutOfRangeException) + { + public static void ThrowIfNegative( + int value, + [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException(paramName, value, "The value must not be negative."); + } + } + } +} +#endif diff --git a/dotnet/src/Dax.Formatter/Polyfills/CallerArgumentExpressionAttribute.cs b/dotnet/src/Dax.Formatter/Polyfills/CallerArgumentExpressionAttribute.cs new file mode 100644 index 0000000..613638b --- /dev/null +++ b/dotnet/src/Dax.Formatter/Polyfills/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,14 @@ +#if !NET +namespace System.Runtime.CompilerServices; + +[AttributeUsage(AttributeTargets.Parameter)] +internal sealed class CallerArgumentExpressionAttribute : Attribute +{ + public CallerArgumentExpressionAttribute(string parameterName) + { + ParameterName = parameterName; + } + + public string ParameterName { get; } +} +#endif diff --git a/dotnet/src/Dax.Formatter/Polyfills/NullableAttributes.cs b/dotnet/src/Dax.Formatter/Polyfills/NullableAttributes.cs new file mode 100644 index 0000000..dee02bb --- /dev/null +++ b/dotnet/src/Dax.Formatter/Polyfills/NullableAttributes.cs @@ -0,0 +1,33 @@ +#if !NET +namespace System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.ReturnValue)] +internal sealed class NotNullAttribute : Attribute +{ +} + +[AttributeUsage(AttributeTargets.Parameter)] +internal sealed class NotNullWhenAttribute : Attribute +{ + public NotNullWhenAttribute(bool returnValue) + { + ReturnValue = returnValue; + } + + public bool ReturnValue { get; } +} + +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] +internal sealed class MemberNotNullWhenAttribute : Attribute +{ + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Member = member; + } + + public bool ReturnValue { get; } + + public string Member { get; } +} +#endif diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatProgressInfoTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatProgressInfoTests.cs new file mode 100644 index 0000000..d523251 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatProgressInfoTests.cs @@ -0,0 +1,21 @@ +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxFormatProgressInfoTests +{ + [Fact] + public void Constructor_Counts_KeepsThem() + { + var progress = new DaxFormatProgressInfo(250, 1000); + + Assert.Equal((250, 1000), (progress.Completed, progress.Total)); + } + + [Fact] + public void Constructor_NegativeCount_Throws() + { + Assert.Throws("completed", () => new DaxFormatProgressInfo(-1, 10)); + Assert.Throws("total", () => new DaxFormatProgressInfo(0, -1)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatResultTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatResultTests.cs new file mode 100644 index 0000000..f0739df --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatResultTests.cs @@ -0,0 +1,84 @@ +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxFormatResultTests +{ + private static readonly DaxSyntaxError s_error = new(0, 3, "Syntax error"); + + [Fact] + public void Success_Texts_CreatesAResultWithoutErrors() + { + var result = DaxFormatResult.Success("evaluate Sales", "EVALUATE\r\nSales"); + + Assert.True(result.Succeeded); + Assert.Equal(("evaluate Sales", "EVALUATE\r\nSales"), (result.OriginalText, result.FormattedText)); + Assert.Empty(result.Errors); + } + + [Fact] + public void Success_EmptyFormattedText_StillSucceeds() + { + var result = DaxFormatResult.Success(" ", string.Empty); + + Assert.True(result.Succeeded); + } + + [Fact] + public void Failure_Errors_CreatesAResultWithoutFormattedText() + { + var result = DaxFormatResult.Failure("1 +* 2", [s_error]); + + Assert.False(result.Succeeded); + Assert.Null(result.FormattedText); + Assert.Equal([s_error], result.Errors); + } + + [Fact] + public void Failure_Errors_CopiesThem() + { + var errors = new List { s_error }; + var result = DaxFormatResult.Failure("1 +* 2", errors); + + errors.Clear(); + + Assert.Single(result.Errors); + } + + [Fact] + public void Failure_NoErrors_Throws() + { + Assert.Throws("errors", () => DaxFormatResult.Failure("1 +* 2", [])); + } + + [Fact] + public void Failure_NullError_Throws() + { + Assert.Throws("errors", () => DaxFormatResult.Failure("1 +* 2", [null!])); + } + + [Fact] + public void Success_NullText_Throws() + { + Assert.Throws("originalText", () => DaxFormatResult.Success(null!, "a")); + Assert.Throws("formattedText", () => DaxFormatResult.Success("a", null!)); + } + + [Fact] + public void Constructor_ItemAndResult_CopiesTheResultAndKeepsTheItem() + { + var failure = DaxFormatResult.Failure("1 +* 2", [s_error]); + + var result = new DaxFormatResult(42, failure); + + Assert.Equal(42, result.Item); + Assert.Equal(("1 +* 2", false), (result.OriginalText, result.Succeeded)); + Assert.Equal([s_error], result.Errors); + } + + [Fact] + public void Constructor_NullResult_Throws() + { + Assert.Throws("result", () => new DaxFormatResult(42, null!)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs new file mode 100644 index 0000000..0b94635 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs @@ -0,0 +1,47 @@ +using System.Net; +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxFormatterExceptionTests +{ + [Fact] + public void Constructor_EveryDetail_KeepsThem() + { + var inner = new InvalidOperationException("inner"); + + var exception = new DaxFormatterException( + "message", DaxFormatterFailureReason.HttpError, HttpStatusCode.BadGateway, "request", "service", inner); + + Assert.Equal(("message", inner), (exception.Message, exception.InnerException)); + Assert.Equal((DaxFormatterFailureReason.HttpError, HttpStatusCode.BadGateway), (exception.Reason, exception.StatusCode)); + Assert.Equal(("request", "service"), (exception.RequestId, exception.ServiceRequestId)); + } + + [Fact] + public void Constructor_MessageOnly_HasNoDetails() + { + var exception = new DaxFormatterException("message"); + + Assert.Equal(DaxFormatterFailureReason.Unknown, exception.Reason); + Assert.Equal((null, null, null), (exception.StatusCode, exception.RequestId, exception.ServiceRequestId)); + } + + [Fact] + public void Constructor_MessageAndInnerException_KeepsThem() + { + var inner = new InvalidOperationException("inner"); + + var exception = new DaxFormatterException("message", inner); + + Assert.Equal(("message", inner), (exception.Message, exception.InnerException)); + } + + [Fact] + public void Constructor_NoArguments_HasADefaultMessage() + { + var exception = new DaxFormatterException(); + + Assert.False(string.IsNullOrEmpty(exception.Message)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxSyntaxErrorTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxSyntaxErrorTests.cs new file mode 100644 index 0000000..e6f092f --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxSyntaxErrorTests.cs @@ -0,0 +1,58 @@ +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxSyntaxErrorTests +{ + [Fact] + public void Constructor_Values_KeepsThem() + { + var error = new DaxSyntaxError(2, 7, "Syntax error"); + + Assert.Equal((2, 7, "Syntax error"), (error.Line, error.Column, error.Message)); + } + + [Fact] + public void Equals_SameValues_IsTrueWithTheSameHashCode() + { + var first = new DaxSyntaxError(2, 7, "Syntax error"); + var second = new DaxSyntaxError(2, 7, "Syntax error"); + + Assert.True(first.Equals(second)); + Assert.True(first.Equals((object)second)); + Assert.Equal(first.GetHashCode(), second.GetHashCode()); + } + + [Theory] + [InlineData(3, 7, "Syntax error")] + [InlineData(2, 8, "Syntax error")] + [InlineData(2, 7, "syntax error")] + public void Equals_DifferentValue_IsFalse(int line, int column, string message) + { + var first = new DaxSyntaxError(2, 7, "Syntax error"); + var second = new DaxSyntaxError(line, column, message); + + Assert.False(first.Equals(second)); + } + + [Fact] + public void Equals_OtherType_IsFalse() + { + var error = new DaxSyntaxError(2, 7, "Syntax error"); + + Assert.False(error.Equals("Syntax error")); + } + + [Fact] + public void Constructor_NegativePosition_Throws() + { + Assert.Throws("line", () => new DaxSyntaxError(-1, 0, "m")); + Assert.Throws("column", () => new DaxSyntaxError(0, -1, "m")); + } + + [Fact] + public void Constructor_NullMessage_Throws() + { + Assert.Throws("message", () => new DaxSyntaxError(0, 0, null!)); + } +} From ccda54e8b1d3bd36f38effc7221d196533243908 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:17:56 +0100 Subject: [PATCH 04/29] feat(dotnet): add the settings and the wire format of the client - copy and check the options of the client and of a call into immutable settings; the names of the server and of the database are kept only as SHA-256 hashes - resolve the caller identity from the options or the entry assembly, and build the User-Agent value from HTTP tokens - add the request and response bodies with source-generated JSON, so that the net10.0 assembly needs no reflection - send serverMode, serverEdition and serverLocation as strings, as the TypeScript port does - embed the fixtures of the wire format in the tests, starting with the name hashes --- .../Configuration/BatchLimits.cs | 19 +++ .../Configuration/CallerIdentity.cs | 126 ++++++++++++++++++ .../Configuration/ClientSettings.cs | 78 +++++++++++ .../Configuration/FormatSettings.cs | 90 +++++++++++++ .../Dax.Formatter/Wire/FormatRequestBody.cs | 37 +++++ .../Dax.Formatter/Wire/FormatResponseError.cs | 13 ++ .../Dax.Formatter/Wire/FormatResponseItem.cs | 11 ++ dotnet/src/Dax.Formatter/Wire/NameHash.cs | 37 +++++ .../Dax.Formatter/Wire/RequestBodyWriter.cs | 41 ++++++ .../src/Dax.Formatter/Wire/WireJsonContext.cs | 16 +++ .../Configuration/CallerIdentityTests.cs | 71 ++++++++++ .../Configuration/ClientSettingsTests.cs | 79 +++++++++++ .../Configuration/FormatSettingsTests.cs | 60 +++++++++ .../Dax.Formatter.Tests.csproj | 4 + .../Fixtures/FixtureFile.cs | 54 ++++++++ .../Fixtures/name-hashes.json | 37 +++++ .../Dax.Formatter.Tests/Wire/NameHashTests.cs | 23 ++++ 17 files changed, 796 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/Configuration/BatchLimits.cs create mode 100644 dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs create mode 100644 dotnet/src/Dax.Formatter/Configuration/ClientSettings.cs create mode 100644 dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/FormatRequestBody.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/FormatResponseError.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/FormatResponseItem.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/NameHash.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/RequestBodyWriter.cs create mode 100644 dotnet/src/Dax.Formatter/Wire/WireJsonContext.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Configuration/ClientSettingsTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/name-hashes.json create mode 100644 dotnet/tests/Dax.Formatter.Tests/Wire/NameHashTests.cs diff --git a/dotnet/src/Dax.Formatter/Configuration/BatchLimits.cs b/dotnet/src/Dax.Formatter/Configuration/BatchLimits.cs new file mode 100644 index 0000000..a651c8d --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/BatchLimits.cs @@ -0,0 +1,19 @@ +namespace Dax.Formatter.Configuration; + +/// +/// How much one request to the service carries. +/// +internal sealed class BatchLimits +{ + public static readonly BatchLimits Default = new(maxTexts: 250, maxCharacters: 250_000); + + public BatchLimits(int maxTexts, int maxCharacters) + { + MaxTexts = maxTexts; + MaxCharacters = maxCharacters; + } + + public int MaxTexts { get; } + + public int MaxCharacters { get; } +} diff --git a/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs new file mode 100644 index 0000000..d1c47b0 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs @@ -0,0 +1,126 @@ +using System.Net.Http.Headers; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; + +namespace Dax.Formatter.Configuration; + +/// +/// The application that calls the service: the name and the version that go into the request body, and the +/// value of the User-Agent header. +/// +internal sealed class CallerIdentity +{ + private const string LibraryName = "Dax.Formatter"; + + private CallerIdentity(string? applicationName, string? applicationVersion) + { + ApplicationName = applicationName; + ApplicationVersion = applicationVersion; + UserAgent = CreateUserAgent(applicationName, applicationVersion); + } + + public string? ApplicationName { get; } + + public string? ApplicationVersion { get; } + + public IReadOnlyList UserAgent { get; } + + public static CallerIdentity Create(string? applicationName, string? applicationVersion) + { + return Create(applicationName, applicationVersion, Assembly.GetEntryAssembly()); + } + + public static CallerIdentity Create(string? applicationName, string? applicationVersion, Assembly? entryAssembly) + { + var name = NullIfBlank(applicationName) ?? NullIfBlank(entryAssembly?.GetName().Name); + var fileVersion = entryAssembly?.GetCustomAttribute()?.Version; + var version = NullIfBlank(applicationVersion) ?? NullIfBlank(fileVersion); + + return new CallerIdentity(name, version); + } + + private static List CreateUserAgent(string? applicationName, string? applicationVersion) + { + var products = new List(); + + var application = ToToken(applicationName); + if (application is not null) + { + products.Add(new ProductInfoHeaderValue(application, ToToken(applicationVersion))); + } + + products.Add(new ProductInfoHeaderValue(LibraryName, ToToken(GetLibraryVersion()))); + products.Add(new ProductInfoHeaderValue(ToComment(RuntimeInformation.FrameworkDescription))); + + return products; + } + + private static string? GetLibraryVersion() + { + var assembly = typeof(CallerIdentity).Assembly; + var version = assembly.GetCustomAttribute()?.InformationalVersion; + if (version is null) + { + return assembly.GetName().Version?.ToString(); + } + + // The informational version ends with the commit id as build metadata, which says nothing to the service. + return version.Split('+')[0]; + } + + private static string? NullIfBlank(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value; + } + + // A product name or version is an HTTP token: "DAX Studio" becomes "DAX-Studio". + private static string? ToToken(string? value) + { + if (value is null) + { + return null; + } + + var token = new StringBuilder(value.Length); + foreach (var character in value) + { + if (IsTokenCharacter(character)) + { + token.Append(character); + } + else if (token.Length > 0 && token[token.Length - 1] != '-') + { + token.Append('-'); + } + } + + var result = token.ToString().TrimEnd('-'); + return result.Length == 0 ? null : result; + } + + private static bool IsTokenCharacter(char character) + { + if (character is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or (>= '0' and <= '9')) + { + return true; + } + + return character is '!' or '#' or '$' or '%' or '&' or '\'' or '*' or '+' or '-' or '.' or '^' or '_' or '`' + or '|' or '~'; + } + + private static string ToComment(string value) + { + var comment = new StringBuilder(value.Length + 2); + comment.Append('('); + foreach (var character in value) + { + var allowed = character is >= ' ' and <= '~' and not ('(' or ')' or '\\'); + comment.Append(allowed ? character : ' '); + } + + comment.Append(')'); + return comment.ToString(); + } +} diff --git a/dotnet/src/Dax.Formatter/Configuration/ClientSettings.cs b/dotnet/src/Dax.Formatter/Configuration/ClientSettings.cs new file mode 100644 index 0000000..66fb312 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/ClientSettings.cs @@ -0,0 +1,78 @@ +namespace Dax.Formatter.Configuration; + +/// +/// The validated, immutable copy of a . +/// +internal sealed class ClientSettings +{ + private const string FormatPath = "api/daxtextformatmulti"; + + private ClientSettings(DaxFormatterClientOptions options, Uri formatUri) + { + ApplicationName = options.ApplicationName; + ApplicationVersion = options.ApplicationVersion; + FormatUri = formatUri; + RequestTimeout = options.RequestTimeout; + MaxRetries = options.MaxRetries; + MaxConcurrentRequests = options.MaxConcurrentRequests; + } + + public string? ApplicationName { get; } + + public string? ApplicationVersion { get; } + + public Uri FormatUri { get; } + + public TimeSpan RequestTimeout { get; } + + public int MaxRetries { get; } + + public int MaxConcurrentRequests { get; } + + public static ClientSettings From(DaxFormatterClientOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + // A timer accepts at most this many milliseconds on every target. + var longestTimeout = TimeSpan.FromMilliseconds(int.MaxValue); + if (options.RequestTimeout <= TimeSpan.Zero || options.RequestTimeout > longestTimeout) + { + throw new ArgumentException("RequestTimeout must be positive and at most 24 days.", nameof(options)); + } + + if (options.MaxRetries < 0) + { + throw new ArgumentException("MaxRetries must not be negative.", nameof(options)); + } + + if (options.MaxConcurrentRequests < 1) + { + throw new ArgumentException("MaxConcurrentRequests must be at least 1.", nameof(options)); + } + + return new ClientSettings(options, CreateFormatUri(options)); + } + + private static Uri CreateFormatUri(DaxFormatterClientOptions options) + { + var endpoint = options.Endpoint; + if (endpoint is null || !endpoint.IsAbsoluteUri) + { + throw new ArgumentException("Endpoint must be an absolute URI.", nameof(options)); + } + + if (endpoint.Scheme != Uri.UriSchemeHttps && endpoint.Scheme != Uri.UriSchemeHttp) + { + throw new ArgumentException("Endpoint must be an http or https URI.", nameof(options)); + } + + // A relative URI replaces the last segment of a base that has no final slash. + var basePath = endpoint.GetLeftPart(UriPartial.Path); + if (basePath[basePath.Length - 1] != '/') + { + basePath += "/"; + } + + return new Uri(new Uri(basePath), FormatPath); + } +} diff --git a/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs b/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs new file mode 100644 index 0000000..e900c97 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Configuration; + +/// +/// The validated, immutable copy of a , with its values in the form the service +/// takes. The names of the server and of the database are kept only as hashes. +/// +internal sealed class FormatSettings +{ + private const string NotDefined = " is not a value of its enumeration."; + + private FormatSettings(DaxFormatOptions options) + { + Kind = options.Kind switch + { + DaxKind.Auto or DaxKind.Expression => options.Kind, + _ => throw new ArgumentException(nameof(options.Kind) + NotDefined, nameof(options)), + }; + + MaxLineLength = options.LineStyle switch + { + DaxLineStyle.LongLine => 0, + DaxLineStyle.ShortLine => 1, + _ => throw new ArgumentException(nameof(options.LineStyle) + NotDefined, nameof(options)), + }; + + SkipSpaceAfterFunctionName = options.SpacingStyle switch + { + DaxSpacingStyle.SpaceAfterFunction => false, + DaxSpacingStyle.NoSpaceAfterFunction => true, + _ => throw new ArgumentException(nameof(options.SpacingStyle) + NotDefined, nameof(options)), + }; + + (ListSeparator, DecimalSeparator) = options.SeparatorStyle switch + { + DaxSeparatorStyle.CommaAndPoint => (",", "."), + DaxSeparatorStyle.SemicolonAndComma => (";", ","), + _ => throw new ArgumentException(nameof(options.SeparatorStyle) + NotDefined, nameof(options)), + }; + + var model = options.ModelInfo; + if (model is null) + { + return; + } + + ServerNameHash = model.ServerName is null ? null : NameHash.Compute(model.ServerName); + DatabaseNameHash = model.DatabaseName is null ? null : NameHash.Compute(model.DatabaseName); + ServerType = model.ServerType; + ServerMode = model.ServerMode; + ServerEdition = model.ServerEdition; + ServerLocation = model.ServerLocation; + ServerVersion = model.ServerVersion; + DatabaseCompatibilityLevel = model.CompatibilityLevel?.ToString(CultureInfo.InvariantCulture); + } + + public DaxKind Kind { get; } + + public int MaxLineLength { get; } + + public bool SkipSpaceAfterFunctionName { get; } + + public string ListSeparator { get; } + + public string DecimalSeparator { get; } + + public string? ServerNameHash { get; } + + public string? DatabaseNameHash { get; } + + public string? ServerType { get; } + + public string? ServerMode { get; } + + public string? ServerEdition { get; } + + public string? ServerLocation { get; } + + public string? ServerVersion { get; } + + public string? DatabaseCompatibilityLevel { get; } + + /// An option is not a value of its enumeration. + public static FormatSettings From(DaxFormatOptions? options) + { + return new FormatSettings(options ?? new DaxFormatOptions()); + } +} diff --git a/dotnet/src/Dax.Formatter/Wire/FormatRequestBody.cs b/dotnet/src/Dax.Formatter/Wire/FormatRequestBody.cs new file mode 100644 index 0000000..eb68353 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/FormatRequestBody.cs @@ -0,0 +1,37 @@ +namespace Dax.Formatter.Wire; + +/// +/// The JSON body of a request to the endpoint that formats several texts. +/// +internal sealed class FormatRequestBody +{ + public IReadOnlyList Dax { get; set; } = []; + + public int MaxLineLength { get; set; } + + public bool SkipSpaceAfterFunctionName { get; set; } + + public string ListSeparator { get; set; } = ","; + + public string DecimalSeparator { get; set; } = "."; + + public string? ServerName { get; set; } + + public string? DatabaseName { get; set; } + + public string? ServerType { get; set; } + + public string? ServerMode { get; set; } + + public string? ServerEdition { get; set; } + + public string? ServerLocation { get; set; } + + public string? ServerVersion { get; set; } + + public string? DatabaseCompatibilityLevel { get; set; } + + public string? CallerApp { get; set; } + + public string? CallerVersion { get; set; } +} diff --git a/dotnet/src/Dax.Formatter/Wire/FormatResponseError.cs b/dotnet/src/Dax.Formatter/Wire/FormatResponseError.cs new file mode 100644 index 0000000..de37003 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/FormatResponseError.cs @@ -0,0 +1,13 @@ +namespace Dax.Formatter.Wire; + +/// +/// A syntax error in the JSON body of a response, with the position that the service reports. +/// +internal sealed class FormatResponseError +{ + public int? Line { get; set; } + + public int? Column { get; set; } + + public string? Message { get; set; } +} diff --git a/dotnet/src/Dax.Formatter/Wire/FormatResponseItem.cs b/dotnet/src/Dax.Formatter/Wire/FormatResponseItem.cs new file mode 100644 index 0000000..f40fcf0 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/FormatResponseItem.cs @@ -0,0 +1,11 @@ +namespace Dax.Formatter.Wire; + +/// +/// The result of one text in the JSON body of a response. The service can leave any field out or null. +/// +internal sealed class FormatResponseItem +{ + public string? Formatted { get; set; } + + public List? Errors { get; set; } +} diff --git a/dotnet/src/Dax.Formatter/Wire/NameHash.cs b/dotnet/src/Dax.Formatter/Wire/NameHash.cs new file mode 100644 index 0000000..fd8af96 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/NameHash.cs @@ -0,0 +1,37 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Dax.Formatter.Wire; + +/// +/// The hash that replaces the name of a server or of a database in a request, so that the service can count +/// distinct names without learning them. +/// +internal static class NameHash +{ + private const string HexDigits = "0123456789abcdef"; + + public static string Compute(string name) + { + var hash = ComputeSha256(Encoding.UTF8.GetBytes(name)); + + var hex = new char[hash.Length * 2]; + for (var i = 0; i < hash.Length; i++) + { + hex[i * 2] = HexDigits[hash[i] >> 4]; + hex[(i * 2) + 1] = HexDigits[hash[i] & 0xF]; + } + + return new string(hex); + } + + private static byte[] ComputeSha256(byte[] bytes) + { +#if NET + return SHA256.HashData(bytes); +#else + using var algorithm = SHA256.Create(); + return algorithm.ComputeHash(bytes); +#endif + } +} diff --git a/dotnet/src/Dax.Formatter/Wire/RequestBodyWriter.cs b/dotnet/src/Dax.Formatter/Wire/RequestBodyWriter.cs new file mode 100644 index 0000000..d19778c --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/RequestBodyWriter.cs @@ -0,0 +1,41 @@ +using System.Text.Json; +using Dax.Formatter.Configuration; + +namespace Dax.Formatter.Wire; + +/// +/// Writes the JSON body of a request as UTF-8 bytes, which every attempt of the request sends again. +/// +internal sealed class RequestBodyWriter +{ + private readonly CallerIdentity _caller; + + public RequestBodyWriter(CallerIdentity caller) + { + _caller = caller; + } + + public byte[] Write(IReadOnlyList dax, FormatSettings settings) + { + var body = new FormatRequestBody + { + Dax = dax, + MaxLineLength = settings.MaxLineLength, + SkipSpaceAfterFunctionName = settings.SkipSpaceAfterFunctionName, + ListSeparator = settings.ListSeparator, + DecimalSeparator = settings.DecimalSeparator, + ServerName = settings.ServerNameHash, + DatabaseName = settings.DatabaseNameHash, + ServerType = settings.ServerType, + ServerMode = settings.ServerMode, + ServerEdition = settings.ServerEdition, + ServerLocation = settings.ServerLocation, + ServerVersion = settings.ServerVersion, + DatabaseCompatibilityLevel = settings.DatabaseCompatibilityLevel, + CallerApp = _caller.ApplicationName, + CallerVersion = _caller.ApplicationVersion, + }; + + return JsonSerializer.SerializeToUtf8Bytes(body, WireJsonContext.Default.FormatRequestBody); + } +} diff --git a/dotnet/src/Dax.Formatter/Wire/WireJsonContext.cs b/dotnet/src/Dax.Formatter/Wire/WireJsonContext.cs new file mode 100644 index 0000000..d4ef7b1 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Wire/WireJsonContext.cs @@ -0,0 +1,16 @@ +using System.Text.Json.Serialization; + +namespace Dax.Formatter.Wire; + +/// +/// The generated JSON serialization of the request and response bodies, which needs no reflection. +/// +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(FormatRequestBody))] +[JsonSerializable(typeof(List))] +internal sealed partial class WireJsonContext : JsonSerializerContext +{ +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs b/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs new file mode 100644 index 0000000..b551b0b --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs @@ -0,0 +1,71 @@ +using System.Text.RegularExpressions; +using Dax.Formatter.Configuration; +using Xunit; + +namespace Dax.Formatter.Tests.Configuration; + +public class CallerIdentityTests +{ + [Fact] + public void Create_NameAndVersion_BuildsTheUserAgent() + { + var identity = CallerIdentity.Create("Contoso", "1.2.3", entryAssembly: null); + + var userAgent = string.Join(" ", identity.UserAgent); + + Assert.Matches(new Regex(@"^Contoso/1\.2\.3 Dax\.Formatter/[0-9]+\.[0-9]+\.[0-9]+\S* \([^()]+\)$"), userAgent); + } + + [Fact] + public void Create_NameWithSpace_KeepsItInTheBodyAndCleansItInTheUserAgent() + { + var identity = CallerIdentity.Create("DAX Studio", "3.0.11", entryAssembly: null); + + Assert.Equal("DAX Studio", identity.ApplicationName); + Assert.StartsWith("DAX-Studio/3.0.11 ", string.Join(" ", identity.UserAgent), StringComparison.Ordinal); + } + + [Theory] + [InlineData("a/b c", "1.0 (beta)", "a-b-c/1.0-beta ")] + [InlineData("Größe", "1", "Gr-e/1 ")] + [InlineData("App", "(1)", "App/1 ")] + [InlineData("App", "()", "App ")] + [InlineData("App", null, "App ")] + public void Create_CharactersOutsideHttpTokens_ReplacesThem(string name, string? version, string expectedStart) + { + var identity = CallerIdentity.Create(name, version, entryAssembly: null); + + Assert.StartsWith(expectedStart + "Dax.Formatter/", string.Join(" ", identity.UserAgent), StringComparison.Ordinal); + } + + [Theory] + [InlineData(null)] + [InlineData(" ")] + [InlineData("()")] + public void Create_NoUsableNameAndNoEntryAssembly_LeavesTheApplicationOutOfTheUserAgent(string? name) + { + var identity = CallerIdentity.Create(name, "1.0", entryAssembly: null); + + Assert.StartsWith("Dax.Formatter/", string.Join(" ", identity.UserAgent), StringComparison.Ordinal); + } + + [Fact] + public void Create_NoName_UsesTheEntryAssembly() + { + var assembly = typeof(CallerIdentityTests).Assembly; + + var identity = CallerIdentity.Create(applicationName: null, applicationVersion: null, assembly); + + Assert.Equal("Dax.Formatter.Tests", identity.ApplicationName); + Assert.False(string.IsNullOrEmpty(identity.ApplicationVersion)); + } + + [Fact] + public void Create_NoNameAndNoEntryAssembly_HasNoApplication() + { + var identity = CallerIdentity.Create(applicationName: null, applicationVersion: null, entryAssembly: null); + + Assert.Null(identity.ApplicationName); + Assert.Null(identity.ApplicationVersion); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Configuration/ClientSettingsTests.cs b/dotnet/tests/Dax.Formatter.Tests/Configuration/ClientSettingsTests.cs new file mode 100644 index 0000000..91f776d --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/ClientSettingsTests.cs @@ -0,0 +1,79 @@ +using Dax.Formatter.Configuration; +using Xunit; + +namespace Dax.Formatter.Tests.Configuration; + +public class ClientSettingsTests +{ + [Fact] + public void From_DefaultOptions_UsesTheDefaults() + { + var settings = ClientSettings.From(new DaxFormatterClientOptions()); + + Assert.Equal(new Uri("https://api.daxformatter.com/api/daxtextformatmulti"), settings.FormatUri); + Assert.Equal(TimeSpan.FromSeconds(60), settings.RequestTimeout); + Assert.Equal((2, 2), (settings.MaxRetries, settings.MaxConcurrentRequests)); + } + + [Theory] + [InlineData("https://example.test", "https://example.test/api/daxtextformatmulti")] + [InlineData("https://example.test/", "https://example.test/api/daxtextformatmulti")] + [InlineData("https://example.test/base", "https://example.test/base/api/daxtextformatmulti")] + [InlineData("http://localhost:7071/base/?x=1#y", "http://localhost:7071/base/api/daxtextformatmulti")] + public void From_Endpoint_AppendsTheFormatPath(string endpoint, string expected) + { + var options = new DaxFormatterClientOptions { Endpoint = new Uri(endpoint) }; + + var settings = ClientSettings.From(options); + + Assert.Equal(new Uri(expected), settings.FormatUri); + } + + [Fact] + public void From_Options_CopiesTheValues() + { + var options = new DaxFormatterClientOptions { MaxRetries = 5 }; + var settings = ClientSettings.From(options); + + options.MaxRetries = 7; + + Assert.Equal(5, settings.MaxRetries); + } + + [Fact] + public void From_Null_Throws() + { + Assert.Throws("options", () => ClientSettings.From(null!)); + } + + [Theory] + [InlineData(0, 2, 2)] + [InlineData(-1, 2, 2)] + [InlineData(60, -1, 2)] + [InlineData(60, 2, 0)] + public void From_ValueOutOfRange_Throws(int timeoutSeconds, int maxRetries, int maxConcurrentRequests) + { + var options = new DaxFormatterClientOptions + { + RequestTimeout = TimeSpan.FromSeconds(timeoutSeconds), + MaxRetries = maxRetries, + MaxConcurrentRequests = maxConcurrentRequests, + }; + + Assert.Throws("options", () => ClientSettings.From(options)); + } + + [Theory] + [InlineData(null)] + [InlineData("api/format")] + [InlineData("ftp://example.test/")] + public void From_EndpointNotAbsoluteHttp_Throws(string? endpoint) + { + var options = new DaxFormatterClientOptions + { + Endpoint = endpoint is null ? null! : new Uri(endpoint, UriKind.RelativeOrAbsolute), + }; + + Assert.Throws("options", () => ClientSettings.From(options)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs b/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs new file mode 100644 index 0000000..565ad63 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs @@ -0,0 +1,60 @@ +using Dax.Formatter.Configuration; +using Xunit; + +namespace Dax.Formatter.Tests.Configuration; + +public class FormatSettingsTests +{ + [Fact] + public void From_Null_UsesTheDefaults() + { + var settings = FormatSettings.From(null); + + Assert.Equal(DaxKind.Auto, settings.Kind); + Assert.Equal((0, false), (settings.MaxLineLength, settings.SkipSpaceAfterFunctionName)); + Assert.Equal((",", "."), (settings.ListSeparator, settings.DecimalSeparator)); + } + + [Fact] + public void From_ModelInfo_KeepsOnlyTheHashesOfTheNames() + { + var options = new DaxFormatOptions + { + ModelInfo = new DaxModelInfo { ServerName = "MyServerName1", DatabaseName = "MyDatabaseName1" }, + }; + + var settings = FormatSettings.From(options); + + Assert.Equal("f4139cb312e198bedebf0d71198c27db761f5c4cab73da7dd2faea2672d082af", settings.ServerNameHash); + Assert.Equal("6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863", settings.DatabaseNameHash); + } + + [Fact] + public void From_Options_CopiesTheValues() + { + var options = new DaxFormatOptions { LineStyle = DaxLineStyle.ShortLine }; + var settings = FormatSettings.From(options); + + options.LineStyle = DaxLineStyle.LongLine; + + Assert.Equal(1, settings.MaxLineLength); + } + + [Theory] + [InlineData(2, 0, 0, 0)] + [InlineData(0, 2, 0, 0)] + [InlineData(0, 0, -1, 0)] + [InlineData(0, 0, 0, 2)] + public void From_ValueOutsideItsEnumeration_Throws(int kind, int lineStyle, int spacingStyle, int separatorStyle) + { + var options = new DaxFormatOptions + { + Kind = (DaxKind)kind, + LineStyle = (DaxLineStyle)lineStyle, + SpacingStyle = (DaxSpacingStyle)spacingStyle, + SeparatorStyle = (DaxSeparatorStyle)separatorStyle, + }; + + Assert.Throws("options", () => FormatSettings.From(options)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj index a99c8d2..b5cf10f 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -27,4 +27,8 @@ + + + + diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs new file mode 100644 index 0000000..dcabe10 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs @@ -0,0 +1,54 @@ +using System.Text.Json; + +namespace Dax.Formatter.Tests.Fixtures; + +/// +/// Reads the JSON files of this folder, which are embedded in the test assembly. They hold the cases of the +/// wire format in a form that the clients of other languages can share. +/// +internal static class FixtureFile +{ + public static JsonElement Load(string fileName) + { + using var stream = OpenResource("Fixtures/" + fileName); + using var document = JsonDocument.Parse(stream); + return document.RootElement.Clone(); + } + + /// Gets the names of the cases of a file, which a theory takes as its data. + public static IEnumerable CaseNames(string fileName) + { + return Cases(fileName).Select(testCase => new object[] { testCase.GetProperty("name").GetString()! }); + } + + public static JsonElement Case(string fileName, string name) + { + return Cases(fileName).Single(testCase => testCase.GetProperty("name").GetString() == name); + } + + public static Stream OpenResource(string name) + { + var stream = typeof(FixtureFile).Assembly.GetManifestResourceStream(name); + return stream ?? throw new InvalidOperationException($"The embedded resource '{name}' is missing."); + } + + /// Reads an embedded text file with line feeds as its line breaks, whatever the checkout wrote. + public static string ReadText(string name) + { + using var stream = OpenResource(name); + using var reader = new StreamReader(stream); + + var lines = new List(); + while (reader.ReadLine() is string line) + { + lines.Add(line); + } + + return string.Join("\n", lines); + } + + private static JsonElement.ArrayEnumerator Cases(string fileName) + { + return Load(fileName).GetProperty("cases").EnumerateArray(); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/name-hashes.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/name-hashes.json new file mode 100644 index 0000000..29ef2bd --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/name-hashes.json @@ -0,0 +1,37 @@ +{ + "description": "Names of servers and databases with the value a client sends in their place: the SHA-256 hash of the UTF-8 bytes of the name, as 64 lowercase hexadecimal characters.", + "cases": [ + { + "name": "MyValue123456789$", + "hash": "5f45bfb8ab5c9ea6fe0762974f7bbbe3602155c66d1139496fc2246c360a874b" + }, + { + "name": "1234567890??=", + "hash": "cb0f4399a2850ee589414b82de85b736ced269035c48e4275be850a3162ba284" + }, + { + "name": "abcdefghiABCDEFGHI??=", + "hash": "1bca6736f96f84e35fa921938f45ba981a6e3f6aa02bcf46763009d3614cf89d" + }, + { + "name": "", + "hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "name": "città", + "hash": "74486d610c94568c13bdf76de467bf3fb915a5f6023979874dcd4cca877c0649" + }, + { + "name": "MyServer", + "hash": "5e3e900585e7834b034d4f17187e521b3c7b7de0d1637f79de4b63717d4f0783" + }, + { + "name": "MyServerName1", + "hash": "f4139cb312e198bedebf0d71198c27db761f5c4cab73da7dd2faea2672d082af" + }, + { + "name": "MyDatabaseName1", + "hash": "6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863" + } + ] +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Wire/NameHashTests.cs b/dotnet/tests/Dax.Formatter.Tests/Wire/NameHashTests.cs new file mode 100644 index 0000000..6376385 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Wire/NameHashTests.cs @@ -0,0 +1,23 @@ +using Dax.Formatter.Tests.Fixtures; +using Dax.Formatter.Wire; +using Xunit; + +namespace Dax.Formatter.Tests.Wire; + +public class NameHashTests +{ + private const string Fixture = "name-hashes.json"; + + public static IEnumerable Cases => FixtureFile.CaseNames(Fixture); + + [Theory] + [MemberData(nameof(Cases))] + public void Compute_FixtureName_ReturnsItsHash(string name) + { + var expected = FixtureFile.Case(Fixture, name).GetProperty("hash").GetString(); + + var hash = NameHash.Compute(name); + + Assert.Equal(expected, hash); + } +} From 81471fa972afd1eda11b4f8625436e0805b4be26 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:17:56 +0100 Subject: [PATCH 05/29] feat(dotnet): format the DAX of model objects, functions included - recognize the body of a user-defined function by its parameter list followed by the arrow, with a scanner that knows where strings, names and comments start and end - send an expression under a header line, FUNCTION x = for a function body and [x] := for anything else, and remove the header from the answer with the indentation that the service adds under a function - leave alone the lines that start inside a string or a block comment, which the service returns as they were sent - turn the position of a syntax error into a line and a UTF-16 index in the text of the caller: tab stops of 8, carriage returns without width, end of input at the end of the last line - add fixtures with the answers recorded from the service --- .../Expressions/DaxTextScanner.cs | 108 +++ .../Dax.Formatter/Expressions/DaxTokenKind.cs | 31 + .../Dax.Formatter/Expressions/ErrorLocator.cs | 89 +++ .../Expressions/ExpressionHeader.cs | 36 + .../Expressions/FunctionBodyRecognizer.cs | 67 ++ .../Expressions/HeaderRemover.cs | 93 +++ .../src/Dax.Formatter/Results/ResultMapper.cs | 78 ++ .../Expressions/DaxTextScannerTests.cs | 62 ++ .../Expressions/ErrorLocatorTests.cs | 94 +++ .../Expressions/ExpressionHeaderTests.cs | 41 + .../FunctionBodyRecognizerTests.cs | 24 + .../Expressions/HeaderRemoverTests.cs | 82 ++ .../Fixtures/FixtureOptions.cs | 61 ++ .../Fixtures/format-results.json | 726 ++++++++++++++++++ .../Fixtures/function-bodies.json | 33 + .../Results/ResultMapperTests.cs | 119 +++ 16 files changed, 1744 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/Expressions/DaxTextScanner.cs create mode 100644 dotnet/src/Dax.Formatter/Expressions/DaxTokenKind.cs create mode 100644 dotnet/src/Dax.Formatter/Expressions/ErrorLocator.cs create mode 100644 dotnet/src/Dax.Formatter/Expressions/ExpressionHeader.cs create mode 100644 dotnet/src/Dax.Formatter/Expressions/FunctionBodyRecognizer.cs create mode 100644 dotnet/src/Dax.Formatter/Expressions/HeaderRemover.cs create mode 100644 dotnet/src/Dax.Formatter/Results/ResultMapper.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Expressions/DaxTextScannerTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Expressions/ErrorLocatorTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Expressions/ExpressionHeaderTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Expressions/FunctionBodyRecognizerTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Expressions/HeaderRemoverTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/format-results.json create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/function-bodies.json create mode 100644 dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs diff --git a/dotnet/src/Dax.Formatter/Expressions/DaxTextScanner.cs b/dotnet/src/Dax.Formatter/Expressions/DaxTextScanner.cs new file mode 100644 index 0000000..548d47b --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/DaxTextScanner.cs @@ -0,0 +1,108 @@ +namespace Dax.Formatter.Expressions; + +/// +/// Reads a DAX text one piece at a time, only as far as needed to know where strings, names and comments start +/// and end. It never fails: a piece that is not closed lasts until the end of the text. +/// +internal sealed class DaxTextScanner +{ + private readonly string _text; + + public DaxTextScanner(string text, int position) + { + _text = text; + Position = position; + TokenStart = position; + } + + /// Gets the index of the first character that was not read yet. + public int Position { get; private set; } + + /// Gets the index of the first character of the piece that returned last. + public int TokenStart { get; private set; } + + /// Gets the first character of the piece that returned last. + public char TokenCharacter => _text[TokenStart]; + + public DaxTokenKind Read() + { + TokenStart = Position; + if (Position >= _text.Length) + { + return DaxTokenKind.End; + } + + var character = _text[Position]; + switch (character) + { + case '\n': + Position++; + return DaxTokenKind.LineBreak; + case '"': + Position = FindEndOfDelimited('"'); + return DaxTokenKind.String; + case '\'': + Position = FindEndOfDelimited('\''); + return DaxTokenKind.QuotedName; + case '[': + Position = FindEndOfDelimited(']'); + return DaxTokenKind.BracketName; + case '/' when NextIs('/'): + case '-' when NextIs('-'): + Position = FindEndOfLine(); + return DaxTokenKind.LineComment; + case '/' when NextIs('*'): + Position = FindEndOfBlockComment(); + return DaxTokenKind.BlockComment; + default: + Position++; + return DaxTokenKind.Other; + } + } + + /// Moves past characters that the caller has already examined. + public void Skip(int count) + { + Position += count; + } + + private bool NextIs(char character) + { + return Position + 1 < _text.Length && _text[Position + 1] == character; + } + + // The closing character written twice stands for itself and does not close the piece. + private int FindEndOfDelimited(char closing) + { + var index = Position + 1; + while (index < _text.Length) + { + if (_text[index] != closing) + { + index++; + } + else if (index + 1 < _text.Length && _text[index + 1] == closing) + { + index += 2; + } + else + { + return index + 1; + } + } + + return _text.Length; + } + + private int FindEndOfLine() + { + var lineFeed = _text.IndexOf('\n', Position); + return lineFeed < 0 ? _text.Length : lineFeed; + } + + private int FindEndOfBlockComment() + { + var end = _text.IndexOf("*/", Position + 2, StringComparison.Ordinal); + return end < 0 ? _text.Length : end + 2; + } +} diff --git a/dotnet/src/Dax.Formatter/Expressions/DaxTokenKind.cs b/dotnet/src/Dax.Formatter/Expressions/DaxTokenKind.cs new file mode 100644 index 0000000..5b23acb --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/DaxTokenKind.cs @@ -0,0 +1,31 @@ +namespace Dax.Formatter.Expressions; + +/// +/// The pieces of a DAX text that tells apart. +/// +internal enum DaxTokenKind +{ + /// The end of the text. + End, + + /// A line feed outside strings, names and comments. + LineBreak, + + /// A comment that starts with // or --, without the line feed that ends it. + LineComment, + + /// A comment between /* and */, which can span lines. + BlockComment, + + /// A string between double quotes, which can span lines. + String, + + /// A table name between single quotes. + QuotedName, + + /// A column or measure name between square brackets. + BracketName, + + /// Any other single character. + Other, +} diff --git a/dotnet/src/Dax.Formatter/Expressions/ErrorLocator.cs b/dotnet/src/Dax.Formatter/Expressions/ErrorLocator.cs new file mode 100644 index 0000000..5c2ecbe --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/ErrorLocator.cs @@ -0,0 +1,89 @@ +namespace Dax.Formatter.Expressions; + +/// +/// Turns the position of a syntax error, as the service reports it for the text it received, into a position in +/// the text that the caller gave. +/// +internal static class ErrorLocator +{ + private const int TabStop = 8; + + /// The text that the caller gave. + /// Whether the client sent the text under a header line. + /// The zero-based line that the service reports. + /// The column that the service reports: tabs count up to the next tab stop. + /// The zero-based line and the UTF-16 index in that line. + public static (int Line, int Column) Locate(string originalText, bool hasHeader, int line, int column) + { + var targetLine = Math.Max(line, 0); + if (hasHeader) + { + // The header is not part of the text of the caller: an error there can only point to its start. + if (targetLine == 0) + { + return (0, 0); + } + + targetLine--; + } + + var currentLine = 0; + var lineStart = 0; + while (currentLine < targetLine) + { + var lineFeed = originalText.IndexOf('\n', lineStart); + if (lineFeed < 0) + { + break; + } + + lineStart = lineFeed + 1; + currentLine++; + } + + var lineEnd = FindLineEnd(originalText, lineStart); + if (currentLine < targetLine) + { + // The service reports the end of the input as the line after the last one. + return (currentLine, lineEnd - lineStart); + } + + return (currentLine, ToIndex(originalText, lineStart, lineEnd, Math.Max(column, 0)) - lineStart); + } + + // The end of the line, before its line feed and the carriage return that can precede it. + private static int FindLineEnd(string text, int lineStart) + { + var lineFeed = text.IndexOf('\n', lineStart); + var end = lineFeed < 0 ? text.Length : lineFeed; + if (end > lineStart && text[end - 1] == '\r') + { + end--; + } + + return end; + } + + // The service counts a tab as a jump to the next tab stop and gives a carriage return no width. + private static int ToIndex(string text, int lineStart, int lineEnd, int targetColumn) + { + var column = 0; + for (var index = lineStart; index < lineEnd; index++) + { + var character = text[index]; + if (character == '\r') + { + continue; + } + + if (column >= targetColumn) + { + return index; + } + + column = character == '\t' ? ((column / TabStop) + 1) * TabStop : column + 1; + } + + return lineEnd; + } +} diff --git a/dotnet/src/Dax.Formatter/Expressions/ExpressionHeader.cs b/dotnet/src/Dax.Formatter/Expressions/ExpressionHeader.cs new file mode 100644 index 0000000..61a3651 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/ExpressionHeader.cs @@ -0,0 +1,36 @@ +namespace Dax.Formatter.Expressions; + +/// +/// The line that the client writes before the DAX of a model object, which has no name of its own, so that the +/// service reads it as a definition. takes it away from the formatted text. +/// +internal sealed class ExpressionHeader +{ + /// The header of every expression that is not the body of a function. + public static readonly ExpressionHeader Measure = new("[x] :=", indentsBody: false); + + /// The header of the body of a user-defined function. + public static readonly ExpressionHeader Function = new("FUNCTION x =", indentsBody: true); + + private ExpressionHeader(string text, bool indentsBody) + { + Text = text; + IndentsBody = indentsBody; + } + + public string Text { get; } + + /// Gets a value indicating whether the service indents the lines that follow this header. + public bool IndentsBody { get; } + + public static ExpressionHeader For(string text) + { + return FunctionBodyRecognizer.IsFunctionBody(text) ? Function : Measure; + } + + // The header takes a line of its own, so that the lines of the text keep their columns. + public string AddTo(string text) + { + return string.Concat(Text, "\n", text); + } +} diff --git a/dotnet/src/Dax.Formatter/Expressions/FunctionBodyRecognizer.cs b/dotnet/src/Dax.Formatter/Expressions/FunctionBodyRecognizer.cs new file mode 100644 index 0000000..b30d4ba --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/FunctionBodyRecognizer.cs @@ -0,0 +1,67 @@ +namespace Dax.Formatter.Expressions; + +/// +/// Tells the body of a user-defined function from any other expression: after spaces and comments, a parameter +/// list in balanced parentheses followed by =>, an arrow that DAX has only in function definitions. +/// +internal static class FunctionBodyRecognizer +{ + public static bool IsFunctionBody(string text) + { + var scanner = new DaxTextScanner(text, 0); + if (!ReadSignificant(scanner, '(')) + { + return false; + } + + // A default value of a parameter can hold nested parentheses, strings and names. + var depth = 1; + while (depth > 0) + { + var kind = scanner.Read(); + if (kind == DaxTokenKind.End) + { + return false; + } + + if (kind == DaxTokenKind.Other && scanner.TokenCharacter == '(') + { + depth++; + } + else if (kind == DaxTokenKind.Other && scanner.TokenCharacter == ')') + { + depth--; + } + } + + if (!ReadSignificant(scanner, '=')) + { + return false; + } + + return scanner.Read() == DaxTokenKind.Other && scanner.TokenCharacter == '>'; + } + + // Reads past spaces, line breaks and comments, then says whether the next character is the expected one. + private static bool ReadSignificant(DaxTextScanner scanner, char expected) + { + while (true) + { + var kind = scanner.Read(); + if (kind is DaxTokenKind.LineBreak or DaxTokenKind.LineComment or DaxTokenKind.BlockComment) + { + continue; + } + + if (kind != DaxTokenKind.Other) + { + return false; + } + + if (!char.IsWhiteSpace(scanner.TokenCharacter)) + { + return scanner.TokenCharacter == expected; + } + } + } +} diff --git a/dotnet/src/Dax.Formatter/Expressions/HeaderRemover.cs b/dotnet/src/Dax.Formatter/Expressions/HeaderRemover.cs new file mode 100644 index 0000000..afece56 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Expressions/HeaderRemover.cs @@ -0,0 +1,93 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace Dax.Formatter.Expressions; + +/// +/// Takes the header that the client added away from a formatted text, with the indentation that the service adds +/// under the header of a function. +/// +internal static class HeaderRemover +{ + private const string Indentation = " "; + + /// + /// Removes the header, or returns when the formatted text does not start with it: such + /// a text is not what the client asked for and must not reach the caller. + /// + public static bool TryRemove(string formatted, ExpressionHeader header, [NotNullWhen(true)] out string? body) + { + body = null; + if (!formatted.StartsWith(header.Text, StringComparison.Ordinal)) + { + return false; + } + + var position = header.Text.Length; + while (position < formatted.Length && formatted[position] == ' ') + { + position++; + } + + // The service writes the body either on the line of the header or on the next one. + var lineBreakLength = GetLineBreakLength(formatted, position); + position += lineBreakLength; + + if (header.IndentsBody) + { + body = RemoveIndentation(formatted, position, startsLine: lineBreakLength > 0); + } + else + { + body = formatted.Substring(position); + } + + return true; + } + + private static int GetLineBreakLength(string text, int position) + { + if (position < text.Length && text[position] == '\n') + { + return 1; + } + + if (position + 1 < text.Length && text[position] == '\r' && text[position + 1] == '\n') + { + return 2; + } + + return 0; + } + + // A line that starts inside a string, a name or a block comment is content: the service returns it as it + // was sent, without indentation, so it is left as it is. + private static string RemoveIndentation(string text, int start, bool startsLine) + { + var result = new StringBuilder(text.Length - start); + var scanner = new DaxTextScanner(text, start); + var copiedUpTo = start; + var atLineStart = startsLine; + + while (true) + { + if (atLineStart && string.CompareOrdinal(text, scanner.Position, Indentation, 0, Indentation.Length) == 0) + { + result.Append(text, copiedUpTo, scanner.Position - copiedUpTo); + scanner.Skip(Indentation.Length); + copiedUpTo = scanner.Position; + } + + var kind = scanner.Read(); + if (kind == DaxTokenKind.End) + { + break; + } + + atLineStart = kind == DaxTokenKind.LineBreak; + } + + result.Append(text, copiedUpTo, text.Length - copiedUpTo); + return result.ToString(); + } +} diff --git a/dotnet/src/Dax.Formatter/Results/ResultMapper.cs b/dotnet/src/Dax.Formatter/Results/ResultMapper.cs new file mode 100644 index 0000000..bf7715f --- /dev/null +++ b/dotnet/src/Dax.Formatter/Results/ResultMapper.cs @@ -0,0 +1,78 @@ +using System.Diagnostics.CodeAnalysis; +using Dax.Formatter.Expressions; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Results; + +/// +/// Builds the result of one text from the text that the caller gave and from what the service answered for it. +/// +internal static class ResultMapper +{ + /// The text that the caller gave. + /// The header that the client sent the text under, if any. + /// What the service answered for the text. + /// The result, when the answer can be used. + /// when the formatted text lacks the header that the client added. + public static bool TryMap( + string originalText, + ExpressionHeader? header, + FormatResponseItem item, + [NotNullWhen(true)] out DaxFormatResult? result) + { + // With errors the service has nothing formatted to return, so the formatted text is not read. + if (item.Errors is { Count: > 0 } errors) + { + result = DaxFormatResult.Failure(originalText, MapErrors(originalText, header, errors)); + return true; + } + + var formatted = item.Formatted ?? string.Empty; + if (header is not null) + { + if (!HeaderRemover.TryRemove(formatted, header, out var body)) + { + result = null; + return false; + } + + formatted = body; + } + + result = DaxFormatResult.Success(originalText, RemoveFinalLineBreak(formatted)); + return true; + } + + private static List MapErrors( + string originalText, + ExpressionHeader? header, + List errors) + { + var mapped = new List(errors.Count); + foreach (var error in errors) + { + var reportedLine = error?.Line ?? 0; + var reportedColumn = error?.Column ?? 0; + var (line, column) = ErrorLocator.Locate(originalText, header is not null, reportedLine, reportedColumn); + mapped.Add(new DaxSyntaxError(line, column, error?.Message ?? string.Empty)); + } + + return mapped; + } + + private static string RemoveFinalLineBreak(string text) + { + if (text.Length == 0 || text[text.Length - 1] != '\n') + { + return text; + } + + var end = text.Length - 1; + if (end > 0 && text[end - 1] == '\r') + { + end--; + } + + return text.Substring(0, end); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Expressions/DaxTextScannerTests.cs b/dotnet/tests/Dax.Formatter.Tests/Expressions/DaxTextScannerTests.cs new file mode 100644 index 0000000..b0dbcc1 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Expressions/DaxTextScannerTests.cs @@ -0,0 +1,62 @@ +using Dax.Formatter.Expressions; +using Xunit; + +namespace Dax.Formatter.Tests.Expressions; + +public class DaxTextScannerTests +{ + [Theory] + [InlineData("\"a\"", "String:\"a\"")] + [InlineData("\"a\"\"b\" ", "String:\"a\"\"b\"|Other: ")] + [InlineData("\"a\nb\"", "String:\"a\nb\"")] + [InlineData("'My ''T'[c]", "QuotedName:'My ''T'|BracketName:[c]")] + [InlineData("[a]]b]+", "BracketName:[a]]b]|Other:+")] + [InlineData("// c\nx", "LineComment:// c|LineBreak:\n|Other:x")] + [InlineData("-- c\r\nx", "LineComment:-- c\r|LineBreak:\n|Other:x")] + [InlineData("/* a\n b */x", "BlockComment:/* a\n b */|Other:x")] + [InlineData("1-2/3", "Other:1|Other:-|Other:2|Other:/|Other:3")] + [InlineData("\"//\" /* ' */ '--'", "String:\"//\"|Other: |BlockComment:/* ' */|Other: |QuotedName:'--'")] + public void Read_Text_ReturnsItsPieces(string text, string expected) + { + var pieces = ReadAll(text); + + Assert.Equal(expected, string.Join("|", pieces)); + } + + [Theory] + [InlineData("\"abc", "String")] + [InlineData("'abc", "QuotedName")] + [InlineData("[abc", "BracketName")] + [InlineData("/* abc", "BlockComment")] + [InlineData("// abc", "LineComment")] + public void Read_PieceNotClosed_LastsUntilTheEnd(string text, string expectedKind) + { + var pieces = ReadAll(text); + + Assert.Equal(expectedKind + ":" + text, Assert.Single(pieces)); + } + + [Fact] + public void Read_EmptyText_ReturnsEnd() + { + var scanner = new DaxTextScanner(string.Empty, 0); + + Assert.Equal(DaxTokenKind.End, scanner.Read()); + } + + private static List ReadAll(string text) + { + var scanner = new DaxTextScanner(text, 0); + var pieces = new List(); + while (true) + { + var kind = scanner.Read(); + if (kind == DaxTokenKind.End) + { + return pieces; + } + + pieces.Add(kind + ":" + text.AsSpan(scanner.TokenStart, scanner.Position - scanner.TokenStart).ToString()); + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Expressions/ErrorLocatorTests.cs b/dotnet/tests/Dax.Formatter.Tests/Expressions/ErrorLocatorTests.cs new file mode 100644 index 0000000..1cf5d7d --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Expressions/ErrorLocatorTests.cs @@ -0,0 +1,94 @@ +using Dax.Formatter.Expressions; +using Xunit; + +namespace Dax.Formatter.Tests.Expressions; + +public class ErrorLocatorTests +{ + [Theory] + [InlineData("1 +* 2", 1, 3, 0, 3)] + [InlineData("1 +\n2 +* 3", 2, 3, 1, 3)] + [InlineData("1 +\r\n2 +* 3", 2, 3, 1, 3)] + public void Locate_TextUnderAHeader_MovesTheLineUpByOne( + string text, int line, int column, int expectedLine, int expectedColumn) + { + var position = ErrorLocator.Locate(text, hasHeader: true, line, column); + + Assert.Equal((expectedLine, expectedColumn), position); + } + + [Theory] + [InlineData("\"a => b\"", 9)] + [InlineData("1 + 2", 0)] + public void Locate_ErrorOnTheHeaderLine_PointsToTheStartOfTheText(string text, int column) + { + var position = ErrorLocator.Locate(text, hasHeader: true, line: 0, column); + + Assert.Equal((0, 0), position); + } + + [Theory] + [InlineData("EVALUATE Sa les", 0, 12, 0, 12)] + [InlineData("EVALUATE\nSa les", 1, 3, 1, 3)] + public void Locate_TextSentAsItIs_KeepsThePosition( + string text, int line, int column, int expectedLine, int expectedColumn) + { + var position = ErrorLocator.Locate(text, hasHeader: false, line, column); + + Assert.Equal((expectedLine, expectedColumn), position); + } + + [Theory] + [InlineData("1\t+\t* 2", 16, 4)] + [InlineData("12345678\t+* 2", 17, 10)] + [InlineData("1234567\t+* 2", 9, 9)] + [InlineData("\t\t* 2", 16, 2)] + [InlineData("\t* 2", 5, 1)] + public void Locate_LineWithTabs_CountsEachTabUpToTheNextTabStop(string text, int column, int expectedColumn) + { + var position = ErrorLocator.Locate(text, hasHeader: true, line: 1, column); + + Assert.Equal((0, expectedColumn), position); + } + + [Theory] + [InlineData("1 +\r2 +* 3", 6, 7)] + [InlineData("1 +\r\n2", 3, 3)] + [InlineData("1 +\r\n2", 50, 3)] + public void Locate_LineWithCarriageReturns_GivesThemNoWidth(string text, int column, int expectedColumn) + { + var position = ErrorLocator.Locate(text, hasHeader: true, line: 1, column); + + Assert.Equal((0, expectedColumn), position); + } + + [Theory] + [InlineData("1 +", 2, 0, 3)] + [InlineData("1 +\n", 3, 1, 0)] + [InlineData("1 +\r\n", 3, 1, 0)] + [InlineData("1 +\n 2 +", 9, 1, 5)] + [InlineData("", 2, 0, 0)] + public void Locate_LineAfterTheLastOne_PointsToTheEndOfTheText( + string text, int line, int expectedLine, int expectedColumn) + { + var position = ErrorLocator.Locate(text, hasHeader: true, line, column: 0); + + Assert.Equal((expectedLine, expectedColumn), position); + } + + [Fact] + public void Locate_CharacterOutsideTheBasicPlane_CountsItsTwoUtf16Units() + { + var position = ErrorLocator.Locate("\"\U0001F600\" +* 2", hasHeader: true, line: 1, column: 6); + + Assert.Equal((0, 6), position); + } + + [Fact] + public void Locate_NegativePosition_PointsToTheStart() + { + var position = ErrorLocator.Locate("1 + 2", hasHeader: false, line: -1, column: -1); + + Assert.Equal((0, 0), position); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Expressions/ExpressionHeaderTests.cs b/dotnet/tests/Dax.Formatter.Tests/Expressions/ExpressionHeaderTests.cs new file mode 100644 index 0000000..d995b9b --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Expressions/ExpressionHeaderTests.cs @@ -0,0 +1,41 @@ +using Dax.Formatter.Expressions; +using Xunit; + +namespace Dax.Formatter.Tests.Expressions; + +public class ExpressionHeaderTests +{ + [Fact] + public void For_FunctionBody_ReturnsTheFunctionHeader() + { + var header = ExpressionHeader.For("(a, b) => a + b"); + + Assert.Same(ExpressionHeader.Function, header); + } + + [Theory] + [InlineData("SUM(Sales[Amount])")] + [InlineData("(1 + 2) * 3")] + public void For_OtherExpression_ReturnsTheMeasureHeader(string text) + { + var header = ExpressionHeader.For(text); + + Assert.Same(ExpressionHeader.Measure, header); + } + + [Fact] + public void AddTo_Measure_PutsTheHeaderOnALineOfItsOwn() + { + var sent = ExpressionHeader.Measure.AddTo("1 +\r\n2"); + + Assert.Equal("[x] :=\n1 +\r\n2", sent); + } + + [Fact] + public void AddTo_Function_PutsTheHeaderOnALineOfItsOwn() + { + var sent = ExpressionHeader.Function.AddTo("(a) => a"); + + Assert.Equal("FUNCTION x =\n(a) => a", sent); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Expressions/FunctionBodyRecognizerTests.cs b/dotnet/tests/Dax.Formatter.Tests/Expressions/FunctionBodyRecognizerTests.cs new file mode 100644 index 0000000..0bbec61 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Expressions/FunctionBodyRecognizerTests.cs @@ -0,0 +1,24 @@ +using Dax.Formatter.Expressions; +using Dax.Formatter.Tests.Fixtures; +using Xunit; + +namespace Dax.Formatter.Tests.Expressions; + +public class FunctionBodyRecognizerTests +{ + private const string Fixture = "function-bodies.json"; + + public static IEnumerable Cases => FixtureFile.CaseNames(Fixture); + + [Theory] + [MemberData(nameof(Cases))] + public void IsFunctionBody_FixtureText_ReturnsTheExpectedAnswer(string name) + { + var testCase = FixtureFile.Case(Fixture, name); + var text = testCase.GetProperty("text").GetString()!; + + var isFunction = FunctionBodyRecognizer.IsFunctionBody(text); + + Assert.Equal(testCase.GetProperty("isFunction").GetBoolean(), isFunction); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Expressions/HeaderRemoverTests.cs b/dotnet/tests/Dax.Formatter.Tests/Expressions/HeaderRemoverTests.cs new file mode 100644 index 0000000..624421b --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Expressions/HeaderRemoverTests.cs @@ -0,0 +1,82 @@ +using Dax.Formatter.Expressions; +using Xunit; + +namespace Dax.Formatter.Tests.Expressions; + +public class HeaderRemoverTests +{ + [Theory] + [InlineData("[x] :=\r\n1 + 2\r\n", "1 + 2\r\n")] + [InlineData("[x] :=\n1 + 2\n", "1 + 2\n")] + [InlineData("[x] := 1 + 2\r\n", "1 + 2\r\n")] + [InlineData("[x] :=\r\n\r\n1 + 2", "\r\n1 + 2")] + [InlineData("[x] :=\r\n IF (\r\n 1\r\n )", " IF (\r\n 1\r\n )")] + [InlineData("[x] :=", "")] + public void TryRemove_MeasureHeader_ReturnsWhatFollowsIt(string formatted, string expected) + { + var removed = HeaderRemover.TryRemove(formatted, ExpressionHeader.Measure, out var body); + + Assert.True(removed); + Assert.Equal(expected, body); + } + + [Theory] + [InlineData( + "FUNCTION x = (\r\n a,\r\n b\r\n ) =>\r\n a + b\r\n", + "(\r\n a,\r\n b\r\n) =>\r\na + b\r\n")] + [InlineData( + "FUNCTION x =\r\n // c\r\n (\r\n a\r\n ) =>\r\n a\r\n", + "// c\r\n(\r\n a\r\n) =>\r\na\r\n")] + [InlineData("FUNCTION x = (\n a\n ) =>\n a", "(\n a\n) =>\na")] + public void TryRemove_FunctionHeader_RemovesTheIndentationToo(string formatted, string expected) + { + var removed = HeaderRemover.TryRemove(formatted, ExpressionHeader.Function, out var body); + + Assert.True(removed); + Assert.Equal(expected, body); + } + + [Theory] + [InlineData( + "FUNCTION x = (\r\n a\r\n ) =>\r\n \"x\n y\" & a\r\n", + "(\r\n a\r\n) =>\r\n\"x\n y\" & a\r\n")] + [InlineData( + "FUNCTION x =\r\n /* c1\n c2 */\r\n (\r\n a\r\n ) =>\r\n a\r\n", + "/* c1\n c2 */\r\n(\r\n a\r\n) =>\r\na\r\n")] + [InlineData( + "FUNCTION x = (\r\n a\r\n ) =>\r\n 'T\n 1'[c\n d] & a\r\n", + "(\r\n a\r\n) =>\r\n'T\n 1'[c\n d] & a\r\n")] + [InlineData( + "FUNCTION x = (\r\n a\r\n ) =>\r\n a // \"\r\n + 1 -- /*\r\n + 2\r\n", + "(\r\n a\r\n) =>\r\na // \"\r\n+ 1 -- /*\r\n+ 2\r\n")] + public void TryRemove_LineThatStartsInsideAStringOrComment_KeepsItsSpaces(string formatted, string expected) + { + var removed = HeaderRemover.TryRemove(formatted, ExpressionHeader.Function, out var body); + + Assert.True(removed); + Assert.Equal(expected, body); + } + + [Fact] + public void TryRemove_LineWithLessIndentation_LeavesItAsItIs() + { + var removed = HeaderRemover.TryRemove("FUNCTION x = (\r\n a\r\n\r\n) => a", ExpressionHeader.Function, out var body); + + Assert.True(removed); + Assert.Equal("(\r\n a\r\n\r\n) => a", body); + } + + [Theory] + [InlineData("")] + [InlineData("1 + 2\r\n")] + [InlineData(" [x] :=\r\n1 + 2")] + [InlineData("[X] :=\r\n1 + 2")] + [InlineData("FUNCTION x = (\r\n a\r\n ) =>\r\n a\r\n")] + public void TryRemove_HeaderMissing_ReturnsFalse(string formatted) + { + var removed = HeaderRemover.TryRemove(formatted, ExpressionHeader.Measure, out var body); + + Assert.False(removed); + Assert.Null(body); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs new file mode 100644 index 0000000..6bf6762 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs @@ -0,0 +1,61 @@ +using System.Text.Json; + +namespace Dax.Formatter.Tests.Fixtures; + +/// +/// Reads the options of a fixture case, which are written with the names that every client language shares. +/// +internal static class FixtureOptions +{ + public static DaxFormatOptions Read(JsonElement options) + { + var result = new DaxFormatOptions + { + Kind = ReadEnum(options, "kind"), + LineStyle = ReadEnum(options, "lineStyle"), + SpacingStyle = ReadEnum(options, "spacingStyle"), + SeparatorStyle = ReadEnum(options, "separatorStyle"), + }; + + if (options.TryGetProperty("modelInfo", out var model)) + { + result.ModelInfo = new DaxModelInfo + { + ServerName = ReadString(model, "serverName"), + DatabaseName = ReadString(model, "databaseName"), + ServerType = ReadString(model, "serverType"), + ServerMode = ReadString(model, "serverMode"), + ServerEdition = ReadString(model, "serverEdition"), + ServerLocation = ReadString(model, "serverLocation"), + ServerVersion = ReadString(model, "serverVersion"), + CompatibilityLevel = model.TryGetProperty("compatibilityLevel", out var level) ? level.GetInt32() : null, + }; + } + + return result; + } + + public static DaxKind ReadKind(JsonElement testCase) + { + return ReadEnum(testCase, "kind"); + } + + private static TEnum ReadEnum(JsonElement element, string name) + where TEnum : struct, Enum + { + var value = ReadString(element, name); + if (value is null) + { + return default; + } + + return Enum.TryParse(value, ignoreCase: true, out var result) + ? result + : throw new InvalidOperationException("The fixture has the unknown value '" + value + "'."); + } + + private static string? ReadString(JsonElement element, string name) + { + return element.TryGetProperty(name, out var value) ? value.GetString() : null; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/format-results.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/format-results.json new file mode 100644 index 0000000..1b55c6a --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/format-results.json @@ -0,0 +1,726 @@ +{ + "description": "Texts sent to the DAX Formatter service with what it answered on 2026-11-22, and the result that a client returns for each. 'sent' is 'text' under the header that a client adds for kind 'expression'. Error messages are cut after 'expected:'. Line breaks appear only as escapes.", + "cases": [ + { + "name": "query sent as it is", + "kind": "auto", + "text": "EVALUATE Sales", + "sent": "EVALUATE Sales", + "response": { + "formatted": "EVALUATE\r\nSales\r\n", + "errors": [] + }, + "result": { + "formattedText": "EVALUATE\r\nSales" + } + }, + { + "name": "query with an error that the service reports past the end of the text", + "kind": "auto", + "text": "EVALUATE\t\tSa les x", + "sent": "EVALUATE\t\tSa les x", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 18, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "text sent as it is with an error on its only line", + "kind": "auto", + "text": "SUM(Sales[Amount]) +* 1", + "sent": "SUM(Sales[Amount]) +* 1", + "response": { + "formatted": "", + "errors": [ + { + "line": 0, + "column": 20, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 20, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "text sent as it is with an error after a tab on its second line", + "kind": "auto", + "text": "Sales[Amount] = 1 +\n\t2 ** 3", + "sent": "Sales[Amount] = 1 +\n\t2 ** 3", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 11, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 1, + "column": 4, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with a leading line comment", + "kind": "expression", + "text": "// c\nSUM(Sales[Amount])", + "sent": "[x] :=\n// c\nSUM(Sales[Amount])", + "response": { + "formatted": "[x] :=\r\n// c\r\nSUM ( Sales[Amount] )\r\n", + "errors": [] + }, + "result": { + "formattedText": "// c\r\nSUM ( Sales[Amount] )" + } + }, + { + "name": "expression with a leading block comment", + "kind": "expression", + "text": "/* block */ 1 + 2", + "sent": "[x] :=\n/* block */ 1 + 2", + "response": { + "formatted": "[x] :=\r\n/* block */\r\n1 + 2\r\n", + "errors": [] + }, + "result": { + "formattedText": "/* block */\r\n1 + 2" + } + }, + { + "name": "expression with a string that spans lines", + "kind": "expression", + "text": "\"a\nb\" & \"c\"", + "sent": "[x] :=\n\"a\nb\" & \"c\"", + "response": { + "formatted": "[x] :=\r\n\"a\nb\" & \"c\"\r\n", + "errors": [] + }, + "result": { + "formattedText": "\"a\nb\" & \"c\"" + } + }, + { + "name": "expression with a block comment and a string that span lines", + "kind": "expression", + "text": "IF(1=1,\n/* a\n b */\n\"s1\n s2\", 0)", + "sent": "[x] :=\nIF(1=1,\n/* a\n b */\n\"s1\n s2\", 0)", + "response": { + "formatted": "[x] :=\r\nIF ( 1 = 1, /* a\n b */\r\n \"s1\n s2\", 0 )\r\n", + "errors": [] + }, + "result": { + "formattedText": "IF ( 1 = 1, /* a\n b */\r\n \"s1\n s2\", 0 )" + } + }, + { + "name": "expression with final line breaks", + "kind": "expression", + "text": "1 + 2\n\n\n", + "sent": "[x] :=\n1 + 2\n\n\n", + "response": { + "formatted": "[x] :=\r\n1 + 2\r\n", + "errors": [] + }, + "result": { + "formattedText": "1 + 2" + } + }, + { + "name": "expression that starts with a parenthesis and is not a function", + "kind": "expression", + "text": "(1 + 2) * 3", + "sent": "[x] :=\n(1 + 2) * 3", + "response": { + "formatted": "[x] :=\r\n( 1 + 2 ) * 3\r\n", + "errors": [] + }, + "result": { + "formattedText": "( 1 + 2 ) * 3" + } + }, + { + "name": "expression with an error on its first line", + "kind": "expression", + "text": "1 +* 2", + "sent": "[x] :=\n1 +* 2", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 3, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 3, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after two tabs", + "kind": "expression", + "text": "1\t+\t* 2", + "sent": "[x] :=\n1\t+\t* 2", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 16, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 4, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after a tab at a tab stop", + "kind": "expression", + "text": "12345678\t+* 2", + "sent": "[x] :=\n12345678\t+* 2", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 17, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 10, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after a tab before a tab stop", + "kind": "expression", + "text": "1234567\t+* 2", + "sent": "[x] :=\n1234567\t+* 2", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 9, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 9, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after tabs, one of them inside a string", + "kind": "expression", + "text": "\tIF(\t1=1,\"a\tb\",\t+* 2)", + "sent": "[x] :=\n\tIF(\t1=1,\"a\tb\",\t+* 2)", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 33, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 17, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after a character outside the basic plane", + "kind": "expression", + "text": "\"😀\" +* 2", + "sent": "[x] :=\n\"😀\" +* 2", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 6, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 6, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an error after a carriage return without a line feed", + "kind": "expression", + "text": "1 +\r2 +* 3", + "sent": "[x] :=\n1 +\r2 +* 3", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 6, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 7, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "definition with its own name and carriage returns, with an error on its third line", + "kind": "auto", + "text": "[x] :=\r\n1 +\r\n\t2 +* 3", + "sent": "[x] :=\r\n1 +\r\n\t2 +* 3", + "response": { + "formatted": "", + "errors": [ + { + "line": 2, + "column": 11, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 2, + "column": 4, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with carriage returns and an error on its second line", + "kind": "expression", + "text": "1 +\r\n\t2 +* 3", + "sent": "[x] :=\n1 +\r\n\t2 +* 3", + "response": { + "formatted": "", + "errors": [ + { + "line": 2, + "column": 11, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 1, + "column": 4, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression that ends too early, with a final carriage return and line feed", + "kind": "expression", + "text": "1 +\r\n", + "sent": "[x] :=\n1 +\r\n", + "response": { + "formatted": "", + "errors": [ + { + "line": 3, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 1, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression that ends too early", + "kind": "expression", + "text": "1 +", + "sent": "[x] :=\n1 +", + "response": { + "formatted": "", + "errors": [ + { + "line": 2, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 3, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression that ends too early, with a final line break", + "kind": "expression", + "text": "1 +\n", + "sent": "[x] :=\n1 +\n", + "response": { + "formatted": "", + "errors": [ + { + "line": 3, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 1, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with only a comment", + "kind": "expression", + "text": "// only a comment", + "sent": "[x] :=\n// only a comment", + "response": { + "formatted": "", + "errors": [ + { + "line": 2, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 17, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "expression with an arrow inside a string, which the service rejects on the header line", + "kind": "expression", + "text": "\"a => b\"", + "sent": "[x] :=\n\"a => b\"", + "response": { + "formatted": "", + "errors": [ + { + "line": 0, + "column": 9, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 0, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "function", + "kind": "expression", + "text": "(a, b) => a + b", + "sent": "FUNCTION x =\n(a, b) => a + b", + "response": { + "formatted": "FUNCTION x = (\r\n a,\r\n b\r\n ) =>\r\n a + b\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a,\r\n b\r\n) =>\r\na + b" + } + }, + { + "name": "function with typed parameters and a long body", + "kind": "expression", + "text": "(a : NUMERIC, b : SCALAR INT64 VAL) => CALCULATE(SUM(Sales[Amount]), FILTER(ALL(Sales), Sales[Quantity] > a && Sales[Price] > b), Sales[Color] = \"Red\", Sales[Brand] = \"Contoso\")", + "sent": "FUNCTION x =\n(a : NUMERIC, b : SCALAR INT64 VAL) => CALCULATE(SUM(Sales[Amount]), FILTER(ALL(Sales), Sales[Quantity] > a && Sales[Price] > b), Sales[Color] = \"Red\", Sales[Brand] = \"Contoso\")", + "response": { + "formatted": "FUNCTION x = (\r\n a : NUMERIC,\r\n b : SCALAR INT64 VAL\r\n ) =>\r\n CALCULATE (\r\n SUM ( Sales[Amount] ),\r\n FILTER ( ALL ( Sales ), Sales[Quantity] > a && Sales[Price] > b ),\r\n Sales[Color] = \"Red\",\r\n Sales[Brand] = \"Contoso\"\r\n )\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a : NUMERIC,\r\n b : SCALAR INT64 VAL\r\n) =>\r\nCALCULATE (\r\n SUM ( Sales[Amount] ),\r\n FILTER ( ALL ( Sales ), Sales[Quantity] > a && Sales[Price] > b ),\r\n Sales[Color] = \"Red\",\r\n Sales[Brand] = \"Contoso\"\r\n)" + } + }, + { + "name": "function with a leading line comment", + "kind": "expression", + "text": "// c\n(a) => a", + "sent": "FUNCTION x =\n// c\n(a) => a", + "response": { + "formatted": "FUNCTION x =\r\n // c\r\n (\r\n a\r\n ) =>\r\n a\r\n", + "errors": [] + }, + "result": { + "formattedText": "// c\r\n(\r\n a\r\n) =>\r\na" + } + }, + { + "name": "function with a leading block comment that spans lines", + "kind": "expression", + "text": "/* c1\n c2 */\n(a) => a", + "sent": "FUNCTION x =\n/* c1\n c2 */\n(a) => a", + "response": { + "formatted": "FUNCTION x =\r\n /* c1\n c2 */\r\n (\r\n a\r\n ) =>\r\n a\r\n", + "errors": [] + }, + "result": { + "formattedText": "/* c1\n c2 */\r\n(\r\n a\r\n) =>\r\na" + } + }, + { + "name": "function with comments and blank lines in its body", + "kind": "expression", + "text": "(a) =>\n\n// c1\n\nVAR y = a\n\n-- c2\nRETURN y /* tail */", + "sent": "FUNCTION x =\n(a) =>\n\n// c1\n\nVAR y = a\n\n-- c2\nRETURN y /* tail */", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n // c1\r\n VAR y = a -- c2\r\n RETURN y /* tail */\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\n// c1\r\nVAR y = a -- c2\r\nRETURN y /* tail */" + } + }, + { + "name": "function with a string that spans lines", + "kind": "expression", + "text": "(a) => \"line1\nline2\" & a", + "sent": "FUNCTION x =\n(a) => \"line1\nline2\" & a", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n \"line1\nline2\" & a\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\n\"line1\nline2\" & a" + } + }, + { + "name": "function with a block comment that spans lines", + "kind": "expression", + "text": "(a) => /* c1\nc2 */ a", + "sent": "FUNCTION x =\n(a) => /* c1\nc2 */ a", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n /* c1\nc2 */\r\n a\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\n/* c1\nc2 */\r\na" + } + }, + { + "name": "function with a string whose second line starts with spaces", + "kind": "expression", + "text": "(a) => \"x\n y\" & a", + "sent": "FUNCTION x =\n(a) => \"x\n y\" & a", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n \"x\n y\" & a\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\n\"x\n y\" & a" + } + }, + { + "name": "function with a block comment whose second line starts with spaces, and names in quotes and brackets", + "kind": "expression", + "text": "(a) => IF(a > 0, /* keep\n this */ \"p\", 'My Table'[Col ]] x] & \"q\")", + "sent": "FUNCTION x =\n(a) => IF(a > 0, /* keep\n this */ \"p\", 'My Table'[Col ]] x] & \"q\")", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n IF ( a > 0, /* keep\n this */\r\n \"p\", 'My Table'[Col ]] x] & \"q\" )\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\nIF ( a > 0, /* keep\n this */\r\n \"p\", 'My Table'[Col ]] x] & \"q\" )" + } + }, + { + "name": "function after blank lines", + "kind": "expression", + "text": "\n (a) => a", + "sent": "FUNCTION x =\n\n (a) => a", + "response": { + "formatted": "FUNCTION x = (\r\n a\r\n ) =>\r\n a\r\n", + "errors": [] + }, + "result": { + "formattedText": "(\r\n a\r\n) =>\r\na" + } + }, + { + "name": "function with an error in its body", + "kind": "expression", + "text": "(a) => a +* 1", + "sent": "FUNCTION x =\n(a) => a +* 1", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 10, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 10, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "function without parameters, which the service rejects", + "kind": "expression", + "text": "() => 1", + "sent": "FUNCTION x =\n() => 1", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 1, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 1, + "message": "Syntax error, expected: ..." + } + ] + } + }, + { + "name": "function with a default value of a parameter, which the service rejects", + "kind": "expression", + "text": "(a, b = 1) => a + b", + "sent": "FUNCTION x =\n(a, b = 1) => a + b", + "response": { + "formatted": "", + "errors": [ + { + "line": 1, + "column": 6, + "message": "Syntax error, expected: ..." + } + ] + }, + "result": { + "errors": [ + { + "line": 0, + "column": 6, + "message": "Syntax error, expected: ..." + } + ] + } + } + ] +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/function-bodies.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/function-bodies.json new file mode 100644 index 0000000..353a44e --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/function-bodies.json @@ -0,0 +1,33 @@ +{ + "description": "Texts of kind 'expression' with whether a client takes them for the body of a user-defined function: after spaces and comments, a parameter list in balanced parentheses followed by '=>'. Line breaks appear only as escapes.", + "cases": [ + { "name": "two parameters", "text": "(a, b) => a + b", "isFunction": true }, + { "name": "no parameters", "text": "() => 1", "isFunction": true }, + { "name": "typed parameters", "text": "(a : NUMERIC, b : SCALAR INT64 VAL) => a + b", "isFunction": true }, + { "name": "semicolon as the list separator", "text": "(a; b) => a + b", "isFunction": true }, + { "name": "spaces and line breaks first", "text": " \r\n\t(a) => a", "isFunction": true }, + { "name": "line comment with slashes first", "text": "// c\n(a) => a", "isFunction": true }, + { "name": "line comment with dashes first", "text": "-- c\n(a) => a", "isFunction": true }, + { "name": "block comment first", "text": "/* c1\n c2 */ (a) => a", "isFunction": true }, + { "name": "comment that looks like code first", "text": "// 1 + (2\n(a) => a", "isFunction": true }, + { "name": "default value with nested parentheses", "text": "(a, b = (1 + (2 * 3))) => a + b", "isFunction": true }, + { "name": "default value with a parenthesis in a string", "text": "(a, b = \")\") => a", "isFunction": true }, + { "name": "default value with a parenthesis in a quoted name", "text": "(a, b = COUNTROWS('Sales (old)')) => a", "isFunction": true }, + { "name": "default value with a parenthesis in a bracket name", "text": "(a, b = [Amount (net)]]]) => a", "isFunction": true }, + { "name": "comment between the parameters and the arrow", "text": "(a) /* c */ => a", "isFunction": true }, + { "name": "line break between the parameters and the arrow", "text": "(a)\n=> a", "isFunction": true }, + { "name": "expression that starts with a parenthesis", "text": "(1 + 2) * 3", "isFunction": false }, + { "name": "expression in parentheses compared with greater or equal", "text": "(1 + 2) >= 3", "isFunction": false }, + { "name": "expression in parentheses followed by an equal sign", "text": "(Sales[Quantity]) = 1", "isFunction": false }, + { "name": "function call", "text": "SUM(Sales[Amount])", "isFunction": false }, + { "name": "arrow inside a string", "text": "\"(a) => a\"", "isFunction": false }, + { "name": "arrow inside a comment", "text": "// (a) => a\n1", "isFunction": false }, + { "name": "arrow with a space inside", "text": "(a) = > a", "isFunction": false }, + { "name": "parenthesis that is not closed", "text": "(a => a", "isFunction": false }, + { "name": "string that is not closed in the parameters", "text": "(a = \") => a", "isFunction": false }, + { "name": "definition with its own name", "text": "[x] := (a) => a", "isFunction": false }, + { "name": "empty text", "text": "", "isFunction": false }, + { "name": "blank text", "text": " \n ", "isFunction": false }, + { "name": "only a comment", "text": "/* (a) => a */", "isFunction": false } + ] +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs b/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs new file mode 100644 index 0000000..f73d256 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs @@ -0,0 +1,119 @@ +using System.Text.Json; +using Dax.Formatter.Expressions; +using Dax.Formatter.Results; +using Dax.Formatter.Tests.Fixtures; +using Dax.Formatter.Wire; +using Xunit; + +namespace Dax.Formatter.Tests.Results; + +public class ResultMapperTests +{ + private const string Fixture = "format-results.json"; + + public static IEnumerable Cases => FixtureFile.CaseNames(Fixture); + + [Theory] + [MemberData(nameof(Cases))] + public void TryMap_FixtureAnswer_ReturnsTheExpectedResult(string name) + { + var testCase = FixtureFile.Case(Fixture, name); + var text = testCase.GetProperty("text").GetString()!; + var header = FixtureOptions.ReadKind(testCase) == DaxKind.Expression ? ExpressionHeader.For(text) : null; + var item = ReadItem(testCase.GetProperty("response").GetRawText()); + + var mapped = ResultMapper.TryMap(text, header, item, out var result); + + Assert.True(mapped); + AssertMatches(testCase.GetProperty("result"), result!); + } + + [Theory] + [MemberData(nameof(Cases))] + public void AddTo_FixtureText_GivesTheTextThatWasSent(string name) + { + var testCase = FixtureFile.Case(Fixture, name); + var text = testCase.GetProperty("text").GetString()!; + var isExpression = FixtureOptions.ReadKind(testCase) == DaxKind.Expression; + + var sent = isExpression ? ExpressionHeader.For(text).AddTo(text) : text; + + Assert.Equal(testCase.GetProperty("sent").GetString(), sent); + } + + [Theory] + [InlineData("{\"formatted\":\"EVALUATE\\r\\nSales\\r\\n\",\"errors\":null}", "EVALUATE\r\nSales")] + [InlineData("{\"formatted\":\"EVALUATE\\r\\nSales\\r\\n\"}", "EVALUATE\r\nSales")] + [InlineData("{\"formatted\":null,\"errors\":[]}", "")] + [InlineData("{}", "")] + [InlineData("{\"Formatted\":\"a\\n\",\"Errors\":[]}", "a")] + [InlineData("{\"formatted\":\"a\\r\\n\\r\\n\",\"errors\":[]}", "a\r\n")] + public void TryMap_FieldsMissingOrNull_TreatsThemAsEmpty(string json, string expectedText) + { + var mapped = ResultMapper.TryMap("EVALUATE Sales", header: null, ReadItem(json), out var result); + + Assert.True(mapped); + Assert.Equal(expectedText, result!.FormattedText); + Assert.Empty(result.Errors); + } + + [Fact] + public void TryMap_ErrorsWithFormattedText_IgnoresTheFormattedText() + { + var item = ReadItem("{\"formatted\":\"not a header\",\"errors\":[{\"line\":1,\"column\":2,\"message\":\"m\"}]}"); + + var mapped = ResultMapper.TryMap("1 +* 2", ExpressionHeader.Measure, item, out var result); + + Assert.True(mapped); + Assert.Null(result!.FormattedText); + Assert.Equal(new DaxSyntaxError(0, 2, "m"), Assert.Single(result.Errors)); + } + + [Theory] + [InlineData("{\"errors\":[null]}")] + [InlineData("{\"errors\":[{}]}")] + [InlineData("{\"errors\":[{\"line\":null,\"column\":null,\"message\":null}]}")] + public void TryMap_ErrorWithoutFields_PointsToTheStartWithAnEmptyMessage(string json) + { + var mapped = ResultMapper.TryMap("1 + 2", header: null, ReadItem(json), out var result); + + Assert.True(mapped); + Assert.Equal(new DaxSyntaxError(0, 0, string.Empty), Assert.Single(result!.Errors)); + } + + [Theory] + [InlineData("{\"formatted\":\"1 + 2\\r\\n\",\"errors\":[]}")] + [InlineData("{\"formatted\":\"\",\"errors\":[]}")] + [InlineData("{\"formatted\":null}")] + public void TryMap_FormattedTextWithoutTheHeader_ReturnsFalse(string json) + { + var mapped = ResultMapper.TryMap("1 + 2", ExpressionHeader.Measure, ReadItem(json), out var result); + + Assert.False(mapped); + Assert.Null(result); + } + + private static FormatResponseItem ReadItem(string json) + { + var items = JsonSerializer.Deserialize("[" + json + "]", WireJsonContext.Default.ListFormatResponseItem); + return items![0]!; + } + + private static void AssertMatches(JsonElement expected, DaxFormatResult result) + { + if (expected.TryGetProperty("formattedText", out var formattedText)) + { + Assert.Equal(formattedText.GetString(), result.FormattedText); + Assert.Empty(result.Errors); + return; + } + + var errors = expected.GetProperty("errors").EnumerateArray().Select(error => new DaxSyntaxError( + error.GetProperty("line").GetInt32(), + error.GetProperty("column").GetInt32(), + error.GetProperty("message").GetString()!)); + + Assert.False(result.Succeeded); + Assert.Equal(errors, result.Errors); + } +} From f7767c8d00d4046385facafbc54c12fe41dd9526 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:15 +0100 Subject: [PATCH 06/29] feat(dotnet): add the transport with timeouts and retries - send one attempt with the headers User-Agent, DaxFormatter-Request-Id and DaxFormatter-Operation-Id, without Accept-Encoding, to the endpoint that takes several texts - end an attempt after the request timeout, and tell a timeout from a cancellation by the caller - treat status 204, a body that is not the documented JSON and a wrong number of results as an invalid response - retry timeouts, network errors and the statuses 408, 429, 500, 502, 503 and 504 with a growing wait, honor Retry-After, and reuse the body and the request id in every attempt - share one HttpClient among the clients that are not given one --- .../Dax.Formatter/Transport/AttemptResult.cs | 72 +++++++++ .../Dax.Formatter/Transport/FormatRequest.cs | 57 +++++++ .../Transport/FormatterTransport.cs | 86 +++++++++++ dotnet/src/Dax.Formatter/Transport/IDelay.cs | 9 ++ .../Transport/ResponseHeaders.cs | 44 ++++++ .../Dax.Formatter/Transport/ResponseReader.cs | 77 ++++++++++ .../Dax.Formatter/Transport/RetryPolicy.cs | 82 ++++++++++ .../Dax.Formatter/Transport/RetryingSender.cs | 60 ++++++++ .../Transport/SharedHttpClient.cs | 48 ++++++ .../src/Dax.Formatter/Transport/TaskDelay.cs | 18 +++ .../Transport/ResponseHeadersTests.cs | 75 +++++++++ .../Transport/ResponseReaderTests.cs | 102 +++++++++++++ .../Transport/RetryPolicyTests.cs | 143 ++++++++++++++++++ .../Transport/SharedHttpClientTests.cs | 17 +++ 14 files changed, 890 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/Transport/AttemptResult.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/FormatRequest.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/IDelay.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/ResponseHeaders.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/ResponseReader.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/RetryPolicy.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/RetryingSender.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs create mode 100644 dotnet/src/Dax.Formatter/Transport/TaskDelay.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/ResponseHeadersTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/SharedHttpClientTests.cs diff --git a/dotnet/src/Dax.Formatter/Transport/AttemptResult.cs b/dotnet/src/Dax.Formatter/Transport/AttemptResult.cs new file mode 100644 index 0000000..a5ab322 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/AttemptResult.cs @@ -0,0 +1,72 @@ +using System.Diagnostics.CodeAnalysis; +using System.Net; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Transport; + +/// +/// The outcome of one attempt to send a request: the results of its texts, or the failure with what is needed +/// to decide whether to try again. +/// +internal sealed class AttemptResult +{ + private AttemptResult(List? items, DaxFormatterFailureReason reason, string? detail) + { + Items = items; + Reason = reason; + Detail = detail; + } + + public List? Items { get; } + + [MemberNotNullWhen(true, nameof(Items))] + [MemberNotNullWhen(false, nameof(Detail))] + public bool Succeeded => Items is not null; + + public DaxFormatterFailureReason Reason { get; } + + /// Gets the part of the exception message that says what went wrong. + public string? Detail { get; } + + public HttpStatusCode? StatusCode { get; private set; } + + /// Gets the identifier that the service gave to the request, when an answer arrived. + public string? ServiceRequestId { get; private set; } + + /// Gets how long the service asked to wait before the next attempt. + public TimeSpan? RetryAfter { get; private set; } + + public Exception? Error { get; private set; } + + public static AttemptResult Success(List items, HttpResponseMessage response) + { + return new AttemptResult(items, DaxFormatterFailureReason.Unknown, detail: null) + { + StatusCode = response.StatusCode, + ServiceRequestId = ResponseHeaders.GetServiceRequestId(response), + }; + } + + public static AttemptResult NoResponse(DaxFormatterFailureReason reason, string detail, Exception? error) + { + return new AttemptResult(items: null, reason, detail) + { + Error = error, + }; + } + + public static AttemptResult Rejected( + DaxFormatterFailureReason reason, + string detail, + HttpResponseMessage response, + Exception? error = null) + { + return new AttemptResult(items: null, reason, detail) + { + StatusCode = response.StatusCode, + ServiceRequestId = ResponseHeaders.GetServiceRequestId(response), + RetryAfter = ResponseHeaders.GetRetryAfter(response), + Error = error, + }; + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs b/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs new file mode 100644 index 0000000..cb101a6 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs @@ -0,0 +1,57 @@ +using System.Net; + +namespace Dax.Formatter.Transport; + +/// +/// One request to the service: its body, which every attempt sends again, the identifiers it travels with, and +/// which texts of the call it carries. +/// +internal sealed class FormatRequest +{ + public FormatRequest(byte[] body, int textCount, int firstIndex, int lastIndex, Guid operationId) + { + Body = body; + TextCount = textCount; + FirstIndex = firstIndex; + LastIndex = lastIndex; + OperationId = operationId; + RequestId = Guid.NewGuid(); + } + + public byte[] Body { get; } + + public int TextCount { get; } + + /// Gets the index, in the texts of the call, of the first text of the request. + public int FirstIndex { get; } + + /// Gets the index, in the texts of the call, of the last text of the request. + public int LastIndex { get; } + + /// Gets the identifier of the call, which its requests share. + public Guid OperationId { get; } + + /// Gets the identifier of the request, which its attempts share. + public Guid RequestId { get; } + + public DaxFormatterException CreateException( + DaxFormatterFailureReason reason, + string detail, + HttpStatusCode? statusCode, + string? serviceRequestId, + Exception? innerException) + { + var texts = FirstIndex == LastIndex + ? FormattableString.Invariant($"the text at index {FirstIndex}") + : FormattableString.Invariant($"the texts at indexes {FirstIndex} to {LastIndex}"); + var message = $"The DAX Formatter request for {texts} failed: {detail}."; + + return new DaxFormatterException( + message, + reason, + statusCode, + RequestId.ToString(), + serviceRequestId, + innerException); + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs new file mode 100644 index 0000000..30cf28b --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs @@ -0,0 +1,86 @@ +using System.Globalization; +using System.Net.Http.Headers; +using Dax.Formatter.Configuration; + +namespace Dax.Formatter.Transport; + +/// +/// Makes one attempt to send a request: headers, timeout, and the reading of the response. +/// +internal sealed class FormatterTransport +{ + private const string RequestIdHeader = "DaxFormatter-Request-Id"; + private const string OperationIdHeader = "DaxFormatter-Operation-Id"; + + private static readonly MediaTypeWithQualityHeaderValue s_json = new("application/json"); + + private readonly HttpClient _httpClient; + private readonly Uri _formatUri; + private readonly TimeSpan _requestTimeout; + private readonly CallerIdentity _caller; + + public FormatterTransport(HttpClient httpClient, ClientSettings settings, CallerIdentity caller) + { + _httpClient = httpClient; + _formatUri = settings.FormatUri; + _requestTimeout = settings.RequestTimeout; + _caller = caller; + } + + /// + /// Sends the request once. A failure of the service or of the network comes back as a result; the only + /// exception is , when is + /// cancelled. + /// + public async Task SendAsync(FormatRequest request, CancellationToken cancellationToken) + { + using var message = CreateMessage(request); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_requestTimeout); + + try + { + using var response = await _httpClient + .SendAsync(message, HttpCompletionOption.ResponseContentRead, timeout.Token) + .ConfigureAwait(false); + + return await ResponseReader.ReadAsync(response, request.TextCount, timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException exception) + { + // Without a cancellation from the caller, what ended the wait is a timer: the one of this attempt + // or the Timeout of an HttpClient that the caller supplied. + cancellationToken.ThrowIfCancellationRequested(); + + var seconds = _requestTimeout.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture); + var detail = $"the service did not answer within {seconds} seconds"; + return AttemptResult.NoResponse(DaxFormatterFailureReason.Timeout, detail, exception); + } + catch (HttpRequestException exception) + { + cancellationToken.ThrowIfCancellationRequested(); + + var detail = $"the service could not be reached ({exception.Message})"; + return AttemptResult.NoResponse(DaxFormatterFailureReason.NetworkError, detail, exception); + } + } + + private HttpRequestMessage CreateMessage(FormatRequest request) + { + // The URI is absolute, so the BaseAddress of an HttpClient that the caller supplied plays no part. + var message = new HttpRequestMessage(HttpMethod.Post, _formatUri); + message.Headers.Accept.Add(s_json); + message.Headers.ExpectContinue = false; + message.Headers.Add(RequestIdHeader, request.RequestId.ToString()); + message.Headers.Add(OperationIdHeader, request.OperationId.ToString()); + foreach (var product in _caller.UserAgent) + { + message.Headers.UserAgent.Add(product); + } + + message.Content = new ByteArrayContent(request.Body); + message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; + + return message; + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/IDelay.cs b/dotnet/src/Dax.Formatter/Transport/IDelay.cs new file mode 100644 index 0000000..fe52bc0 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/IDelay.cs @@ -0,0 +1,9 @@ +namespace Dax.Formatter.Transport; + +/// +/// The wait between two attempts of a request, which the tests replace so that they do not wait. +/// +internal interface IDelay +{ + Task WaitAsync(TimeSpan delay, CancellationToken cancellationToken); +} diff --git a/dotnet/src/Dax.Formatter/Transport/ResponseHeaders.cs b/dotnet/src/Dax.Formatter/Transport/ResponseHeaders.cs new file mode 100644 index 0000000..dde3b9c --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/ResponseHeaders.cs @@ -0,0 +1,44 @@ +namespace Dax.Formatter.Transport; + +/// +/// Reads the response headers that the client uses. +/// +internal static class ResponseHeaders +{ + private const string ServiceRequestIdHeader = "x-azure-ref"; + + public static string? GetServiceRequestId(HttpResponseMessage response) + { + if (!response.Headers.TryGetValues(ServiceRequestIdHeader, out var values)) + { + return null; + } + + return values.FirstOrDefault(); + } + + /// + /// Gets the wait that Retry-After asks for, as seconds or as a date. A date is measured from the + /// Date header of the same response, so that the clock of this machine does not matter. + /// + public static TimeSpan? GetRetryAfter(HttpResponseMessage response) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter is null) + { + return null; + } + + if (retryAfter.Delta is TimeSpan delta) + { + return delta < TimeSpan.Zero ? TimeSpan.Zero : delta; + } + + if (retryAfter.Date is DateTimeOffset date && response.Headers.Date is DateTimeOffset now) + { + return date > now ? date - now : TimeSpan.Zero; + } + + return null; + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs b/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs new file mode 100644 index 0000000..a92518f --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs @@ -0,0 +1,77 @@ +using System.Net; +using System.Text.Json; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Transport; + +/// +/// Reads the response to a request and checks that it holds one result for each text sent. +/// +internal static class ResponseReader +{ + public static async Task ReadAsync( + HttpResponseMessage response, + int expectedCount, + CancellationToken cancellationToken) + { + var status = (int)response.StatusCode; + if (!response.IsSuccessStatusCode) + { + var detail = FormattableString.Invariant($"the service answered {status} ({response.ReasonPhrase})"); + return AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, detail, response); + } + + // The service answers 204 to a request without texts, which the client never sends. + if (response.StatusCode == HttpStatusCode.NoContent) + { + return Invalid("the service answered 204 without results", response); + } + + var content = await ReadContentAsync(response, cancellationToken).ConfigureAwait(false); + + List? items; + try + { + items = JsonSerializer.Deserialize(content, WireJsonContext.Default.ListFormatResponseItem); + } + catch (JsonException exception) + { + return Invalid("the response is not the JSON that the service documents", response, exception); + } + + if (items is null) + { + return Invalid("the response has no results", response); + } + + if (items.Count != expectedCount) + { + var detail = FormattableString.Invariant( + $"the response has {items.Count} results for {expectedCount} texts"); + return Invalid(detail, response); + } + + if (items.Contains(null)) + { + return Invalid("the response has an empty result", response); + } + + return AttemptResult.Success(items!, response); + } + + private static AttemptResult Invalid(string detail, HttpResponseMessage response, Exception? error = null) + { + return AttemptResult.Rejected(DaxFormatterFailureReason.InvalidResponse, detail, response, error); + } + + private static Task ReadContentAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { +#if NET + return response.Content.ReadAsByteArrayAsync(cancellationToken); +#else + // The content is already in memory here, so a read that cannot be cancelled does not wait. + cancellationToken.ThrowIfCancellationRequested(); + return response.Content.ReadAsByteArrayAsync(); +#endif + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/RetryPolicy.cs b/dotnet/src/Dax.Formatter/Transport/RetryPolicy.cs new file mode 100644 index 0000000..412cc0b --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/RetryPolicy.cs @@ -0,0 +1,82 @@ +using System.Net; + +namespace Dax.Formatter.Transport; + +/// +/// Decides whether a failed attempt is worth another one, and how long to wait before it. +/// +internal sealed class RetryPolicy +{ + private static readonly TimeSpan s_firstDelay = TimeSpan.FromSeconds(0.8); + private static readonly TimeSpan s_longestDelay = TimeSpan.FromSeconds(60); + + private readonly int _maxRetries; + private readonly TimeSpan _requestTimeout; + + public RetryPolicy(int maxRetries, TimeSpan requestTimeout) + { + _maxRetries = maxRetries; + _requestTimeout = requestTimeout; + } + + /// The failed attempt. + /// The number of the failed attempt, from 1. + /// The identifier of the request, which spreads the waits of different requests. + /// How long to wait before the next attempt. + /// when the request must fail now. + public bool TryGetDelay(AttemptResult failure, int attempt, Guid requestId, out TimeSpan delay) + { + delay = TimeSpan.Zero; + if (attempt > _maxRetries || !IsTransient(failure.Reason, failure.StatusCode)) + { + return false; + } + + delay = GetBackoff(attempt, requestId); + if (failure.RetryAfter is not TimeSpan retryAfter) + { + return true; + } + + // A service that asks to wait longer than a whole request may last is not coming back soon. + if (retryAfter > _requestTimeout) + { + return false; + } + + if (retryAfter > delay) + { + delay = retryAfter; + } + + return true; + } + + public static bool IsTransient(DaxFormatterFailureReason reason, HttpStatusCode? statusCode) + { + if (reason is DaxFormatterFailureReason.Timeout or DaxFormatterFailureReason.NetworkError) + { + return true; + } + + if (reason != DaxFormatterFailureReason.HttpError || statusCode is null) + { + return false; + } + + return (int)statusCode.Value is 408 or 429 or 500 or 502 or 503 or 504; + } + + // Each wait doubles the one before, and varies by a quarter either way so that requests which failed + // together do not come back together. The variation comes from the request identifier, which is random. + private static TimeSpan GetBackoff(int attempt, Guid requestId) + { + var doublings = Math.Min(attempt - 1, 16); + var milliseconds = Math.Min(s_firstDelay.TotalMilliseconds * (1 << doublings), s_longestDelay.TotalMilliseconds); + + var bytes = requestId.ToByteArray(); + var fraction = bytes[attempt % bytes.Length] / 255.0; + + return TimeSpan.FromMilliseconds(milliseconds * (0.75 + (0.5 * fraction))); + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs b/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs new file mode 100644 index 0000000..8e5b954 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs @@ -0,0 +1,60 @@ +namespace Dax.Formatter.Transport; + +/// +/// Sends a request until an attempt succeeds or the retry policy gives up, then throws the failure of the last +/// attempt. +/// +internal sealed class RetryingSender +{ + private readonly FormatterTransport _transport; + private readonly RetryPolicy _policy; + private readonly IDelay _delay; + + public RetryingSender(FormatterTransport transport, RetryPolicy policy, IDelay delay) + { + _transport = transport; + _policy = policy; + _delay = delay; + } + + /// The request failed and is not tried again. + /// The token was cancelled. + public async Task SendAsync(FormatRequest request, CancellationToken cancellationToken) + { + var attempt = 1; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + var result = await _transport.SendAsync(request, cancellationToken).ConfigureAwait(false); + if (result.Succeeded) + { + return result; + } + + if (!_policy.TryGetDelay(result, attempt, request.RequestId, out var delay)) + { + throw CreateException(request, result, attempt); + } + + await _delay.WaitAsync(delay, cancellationToken).ConfigureAwait(false); + attempt++; + } + } + + private static DaxFormatterException CreateException(FormatRequest request, AttemptResult failure, int attempts) + { + var detail = failure.Detail ?? "the reason is not known"; + if (attempts > 1) + { + detail = FormattableString.Invariant($"{detail}, after {attempts} attempts"); + } + + return request.CreateException( + failure.Reason, + detail, + failure.StatusCode, + failure.ServiceRequestId, + failure.Error); + } +} diff --git a/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs b/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs new file mode 100644 index 0000000..c280f21 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs @@ -0,0 +1,48 @@ +namespace Dax.Formatter.Transport; + +/// +/// The of every client that was not given one. It is created at its first use and +/// lives as long as the process, so that all the clients share its connections. +/// +internal static class SharedHttpClient +{ + private static readonly Lazy s_instance = new(Create); + + public static HttpClient Instance => s_instance.Value; + + private static HttpClient Create() + { +#if NET + var client = CreateWithPooledConnections(); +#else + var client = new HttpClient(); +#endif + + // Each attempt has its own timer, which is the only one that must end it. + client.Timeout = Timeout.InfiniteTimeSpan; + return client; + } + +#if NET + private static HttpClient CreateWithPooledConnections() + { + SocketsHttpHandler? handler = null; + try + { + handler = new SocketsHttpHandler(); + + // Connections are replaced now and then, so that a change of the DNS record of the service is seen. + handler.PooledConnectionLifetime = TimeSpan.FromMinutes(5); + handler.ConnectTimeout = TimeSpan.FromSeconds(15); + + var client = new HttpClient(handler, disposeHandler: true); + handler = null; + return client; + } + finally + { + handler?.Dispose(); + } + } +#endif +} diff --git a/dotnet/src/Dax.Formatter/Transport/TaskDelay.cs b/dotnet/src/Dax.Formatter/Transport/TaskDelay.cs new file mode 100644 index 0000000..949dfdc --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/TaskDelay.cs @@ -0,0 +1,18 @@ +namespace Dax.Formatter.Transport; + +/// +/// The wait that the client uses outside tests. +/// +internal sealed class TaskDelay : IDelay +{ + public static readonly TaskDelay Instance = new(); + + private TaskDelay() + { + } + + public Task WaitAsync(TimeSpan delay, CancellationToken cancellationToken) + { + return Task.Delay(delay, cancellationToken); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseHeadersTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseHeadersTests.cs new file mode 100644 index 0000000..042aa05 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseHeadersTests.cs @@ -0,0 +1,75 @@ +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using Dax.Formatter.Transport; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class ResponseHeadersTests +{ + private static readonly DateTimeOffset s_serviceTime = new(2026, 1, 15, 10, 0, 0, TimeSpan.Zero); + + [Fact] + public void GetRetryAfter_Seconds_ReturnsThem() + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(7)); + + Assert.Equal(TimeSpan.FromSeconds(7), ResponseHeaders.GetRetryAfter(response)); + } + + [Fact] + public void GetRetryAfter_Date_MeasuresItFromTheDateOfTheResponse() + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.Date = s_serviceTime; + response.Headers.RetryAfter = new RetryConditionHeaderValue(s_serviceTime.AddSeconds(30)); + + Assert.Equal(TimeSpan.FromSeconds(30), ResponseHeaders.GetRetryAfter(response)); + } + + [Fact] + public void GetRetryAfter_DateInThePast_ReturnsZero() + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.Date = s_serviceTime; + response.Headers.RetryAfter = new RetryConditionHeaderValue(s_serviceTime.AddSeconds(-30)); + + Assert.Equal(TimeSpan.Zero, ResponseHeaders.GetRetryAfter(response)); + } + + [Fact] + public void GetRetryAfter_DateWithoutTheDateOfTheResponse_ReturnsNull() + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter = new RetryConditionHeaderValue(s_serviceTime.AddSeconds(30)); + + Assert.Null(ResponseHeaders.GetRetryAfter(response)); + } + + [Fact] + public void GetRetryAfter_NoHeader_ReturnsNull() + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + + Assert.Null(ResponseHeaders.GetRetryAfter(response)); + } + + [Fact] + public void GetServiceRequestId_Header_ReturnsItsValue() + { + using var response = new HttpResponseMessage(HttpStatusCode.OK); + response.Headers.Add("x-azure-ref", "20260115T100000Z-abc"); + + Assert.Equal("20260115T100000Z-abc", ResponseHeaders.GetServiceRequestId(response)); + } + + [Fact] + public void GetServiceRequestId_NoHeader_ReturnsNull() + { + using var response = new HttpResponseMessage(HttpStatusCode.OK); + + Assert.Null(ResponseHeaders.GetServiceRequestId(response)); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs new file mode 100644 index 0000000..6862db7 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs @@ -0,0 +1,102 @@ +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Dax.Formatter.Transport; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class ResponseReaderTests +{ + private const string TwoResults = + "[{\"formatted\":\"a\\r\\n\",\"errors\":[]},{\"formatted\":\"\",\"errors\":[{\"line\":0,\"column\":1,\"message\":\"m\"}]}]"; + + [Fact] + public async Task ReadAsync_OneResultForEachText_ReturnsThem() + { + using var response = CreateResponse(HttpStatusCode.OK, TwoResults, "application/json"); + + var result = await ResponseReader.ReadAsync(response, 2, CancellationToken.None).ConfigureAwait(true); + + Assert.True(result.Succeeded); + Assert.Equal(2, result.Items!.Count); + Assert.Equal("ref-1", result.ServiceRequestId); + } + + [Theory] + [InlineData(1)] + [InlineData(3)] + public async Task ReadAsync_ResultCountDifferentFromTheTexts_IsAnInvalidResponse(int expectedCount) + { + using var response = CreateResponse(HttpStatusCode.OK, TwoResults, "application/json"); + + var result = await ResponseReader.ReadAsync(response, expectedCount, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); + Assert.Contains("2 results", result.Detail, StringComparison.Ordinal); + } + + [Theory] + [InlineData("Service unavailable", "text/html")] + [InlineData("", "application/json")] + [InlineData("{\"formatted\":\"a\"}", "application/json")] + [InlineData("[{\"formatted\":1}]", "application/json")] + [InlineData("[{\"formatted\":\"a\"", "application/json")] + public async Task ReadAsync_BodyThatIsNotTheDocumentedJson_IsAnInvalidResponse(string body, string mediaType) + { + using var response = CreateResponse(HttpStatusCode.OK, body, mediaType); + + var result = await ResponseReader.ReadAsync(response, 1, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); + Assert.IsType(result.Error, exactMatch: false); + } + + [Theory] + [InlineData("null")] + [InlineData("[null]")] + public async Task ReadAsync_NullInPlaceOfResults_IsAnInvalidResponse(string body) + { + using var response = CreateResponse(HttpStatusCode.OK, body, "application/json"); + + var result = await ResponseReader.ReadAsync(response, 1, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); + } + + [Fact] + public async Task ReadAsync_NoContentStatus_IsAnInvalidResponse() + { + using var response = CreateResponse(HttpStatusCode.NoContent, string.Empty, "application/json"); + + var result = await ResponseReader.ReadAsync(response, 1, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); + Assert.Equal(HttpStatusCode.NoContent, result.StatusCode); + } + + [Fact] + public async Task ReadAsync_StatusThatIsNotASuccess_IsAnHttpErrorWithItsDetails() + { + using var response = CreateResponse(HttpStatusCode.ServiceUnavailable, "busy", "text/plain"); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(3)); + + var result = await ResponseReader.ReadAsync(response, 1, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.HttpError, result.Reason); + Assert.Equal((HttpStatusCode.ServiceUnavailable, "ref-1"), (result.StatusCode, result.ServiceRequestId)); + Assert.Equal(TimeSpan.FromSeconds(3), result.RetryAfter); + } + + private static HttpResponseMessage CreateResponse(HttpStatusCode status, string body, string mediaType) + { + var response = new HttpResponseMessage(status) + { + Content = new StringContent(body, Encoding.UTF8, mediaType), + }; + response.Headers.Add("x-azure-ref", "ref-1"); + return response; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs new file mode 100644 index 0000000..7bf1e4f --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs @@ -0,0 +1,143 @@ +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using Dax.Formatter.Transport; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class RetryPolicyTests +{ + private static readonly Guid s_requestId = new("0b7f3c1e-2a4d-4e6f-8a9b-1c2d3e4f5a6b"); + private static readonly TimeSpan s_requestTimeout = TimeSpan.FromSeconds(60); + + [Theory] + [InlineData(DaxFormatterFailureReason.Timeout, null, true)] + [InlineData(DaxFormatterFailureReason.NetworkError, null, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 408, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 429, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 500, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 502, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 503, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 504, true)] + [InlineData(DaxFormatterFailureReason.HttpError, 400, false)] + [InlineData(DaxFormatterFailureReason.HttpError, 401, false)] + [InlineData(DaxFormatterFailureReason.HttpError, 403, false)] + [InlineData(DaxFormatterFailureReason.HttpError, 404, false)] + [InlineData(DaxFormatterFailureReason.HttpError, 413, false)] + [InlineData(DaxFormatterFailureReason.HttpError, 501, false)] + [InlineData(DaxFormatterFailureReason.HttpError, null, false)] + [InlineData(DaxFormatterFailureReason.InvalidResponse, 200, false)] + [InlineData(DaxFormatterFailureReason.InvalidResponse, 204, false)] + [InlineData(DaxFormatterFailureReason.Unknown, 503, false)] + public void IsTransient_ReasonAndStatus_SaysWhetherAnotherAttemptCanHelp( + DaxFormatterFailureReason reason, int? status, bool expected) + { + var transient = RetryPolicy.IsTransient(reason, (HttpStatusCode?)status); + + Assert.Equal(expected, transient); + } + + [Theory] + [InlineData(1, 600, 1000)] + [InlineData(2, 1200, 2000)] + [InlineData(3, 2400, 4000)] + [InlineData(40, 45000, 75000)] + public void TryGetDelay_TransientFailure_DoublesTheWaitWithinAQuarter( + int attempt, int minMilliseconds, int maxMilliseconds) + { + var policy = new RetryPolicy(maxRetries: 100, s_requestTimeout); + + var retry = policy.TryGetDelay(Timeout(), attempt, s_requestId, out var delay); + + Assert.True(retry); + Assert.InRange(delay.TotalMilliseconds, minMilliseconds, maxMilliseconds); + } + + [Fact] + public void TryGetDelay_DifferentRequests_SpreadsTheWaits() + { + var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); + + policy.TryGetDelay(Timeout(), 1, new Guid("00000000-0000-0000-0000-000000000000"), out var shortest); + policy.TryGetDelay(Timeout(), 1, new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff"), out var longest); + + Assert.Equal(TimeSpan.FromMilliseconds(600), shortest); + Assert.Equal(TimeSpan.FromMilliseconds(1000), longest); + } + + [Theory] + [InlineData(0, 1)] + [InlineData(2, 3)] + public void TryGetDelay_AttemptsUsedUp_ReturnsFalse(int maxRetries, int attempt) + { + var policy = new RetryPolicy(maxRetries, s_requestTimeout); + + var retry = policy.TryGetDelay(Timeout(), attempt, s_requestId, out _); + + Assert.False(retry); + } + + [Fact] + public void TryGetDelay_FailureThatIsNotTransient_ReturnsFalse() + { + var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); + using var response = new HttpResponseMessage(HttpStatusCode.BadRequest); + var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + + var retry = policy.TryGetDelay(failure, 1, s_requestId, out _); + + Assert.False(retry); + } + + [Theory] + [InlineData(30, 30000)] + [InlineData(60, 60000)] + public void TryGetDelay_RetryAfterLongerThanTheBackoff_WaitsAsLongAsAsked(int seconds, int expectedMilliseconds) + { + var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); + using var response = CreateBusyResponse(seconds); + var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + + var retry = policy.TryGetDelay(failure, 1, s_requestId, out var delay); + + Assert.True(retry); + Assert.Equal(TimeSpan.FromMilliseconds(expectedMilliseconds), delay); + } + + [Fact] + public void TryGetDelay_RetryAfterShorterThanTheBackoff_KeepsTheBackoff() + { + var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); + using var response = CreateBusyResponse(seconds: 0); + var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + + policy.TryGetDelay(failure, 1, s_requestId, out var delay); + + Assert.InRange(delay.TotalMilliseconds, 600, 1000); + } + + [Fact] + public void TryGetDelay_RetryAfterLongerThanTheRequestTimeout_ReturnsFalse() + { + var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); + using var response = CreateBusyResponse(seconds: 61); + var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + + var retry = policy.TryGetDelay(failure, 1, s_requestId, out _); + + Assert.False(retry); + } + + private static AttemptResult Timeout() + { + return AttemptResult.NoResponse(DaxFormatterFailureReason.Timeout, "detail", error: null); + } + + private static HttpResponseMessage CreateBusyResponse(int seconds) + { + var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(seconds)); + return response; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/SharedHttpClientTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/SharedHttpClientTests.cs new file mode 100644 index 0000000..7c44b2d --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/SharedHttpClientTests.cs @@ -0,0 +1,17 @@ +using Dax.Formatter.Transport; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class SharedHttpClientTests +{ + [Fact] + public void Instance_AnyUse_ReturnsTheSameClientWithoutItsOwnTimeout() + { + var first = SharedHttpClient.Instance; + var second = SharedHttpClient.Instance; + + Assert.Same(first, second); + Assert.Equal(Timeout.InfiniteTimeSpan, first.Timeout); + } +} From a0b569494c8a7008113def9c9e51f674512064b8 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:15 +0100 Subject: [PATCH 07/29] feat(dotnet): split a large call into requests - plan the requests of a call by number of texts and by characters; a text longer than the limit travels alone and a blank text is not sent - run the requests with a few workers that write each result at the index of its text; the first request that fails stops the others - report progress as a count of texts that never decreases --- .../Dax.Formatter/Batching/BatchFormatter.cs | 56 ++++++ .../src/Dax.Formatter/Batching/BatchPlan.cs | 38 ++++ .../Dax.Formatter/Batching/BatchPlanner.cs | 53 ++++++ dotnet/src/Dax.Formatter/Batching/BatchRun.cs | 176 ++++++++++++++++++ dotnet/src/Dax.Formatter/Batching/Chunk.cs | 23 +++ .../Batching/ProgressReporter.cs | 33 ++++ .../Batching/BatchPlannerTests.cs | 91 +++++++++ 7 files changed, 470 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/Batching/BatchFormatter.cs create mode 100644 dotnet/src/Dax.Formatter/Batching/BatchPlan.cs create mode 100644 dotnet/src/Dax.Formatter/Batching/BatchPlanner.cs create mode 100644 dotnet/src/Dax.Formatter/Batching/BatchRun.cs create mode 100644 dotnet/src/Dax.Formatter/Batching/Chunk.cs create mode 100644 dotnet/src/Dax.Formatter/Batching/ProgressReporter.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs diff --git a/dotnet/src/Dax.Formatter/Batching/BatchFormatter.cs b/dotnet/src/Dax.Formatter/Batching/BatchFormatter.cs new file mode 100644 index 0000000..9b080f1 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchFormatter.cs @@ -0,0 +1,56 @@ +using Dax.Formatter.Configuration; +using Dax.Formatter.Transport; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Batching; + +/// +/// Formats the texts of a call with as many requests as they need. One instance serves every call of a client. +/// +internal sealed class BatchFormatter +{ + private readonly RetryingSender _sender; + private readonly RequestBodyWriter _bodyWriter; + private readonly BatchLimits _limits; + private readonly int _maxConcurrentRequests; + + private BatchFormatter( + RetryingSender sender, + RequestBodyWriter bodyWriter, + BatchLimits limits, + int maxConcurrentRequests) + { + _sender = sender; + _bodyWriter = bodyWriter; + _limits = limits; + _maxConcurrentRequests = maxConcurrentRequests; + } + + public static BatchFormatter Create(HttpClient httpClient, ClientSettings settings, IDelay delay, BatchLimits limits) + { + var caller = CallerIdentity.Create(settings.ApplicationName, settings.ApplicationVersion); + var transport = new FormatterTransport(httpClient, settings, caller); + var policy = new RetryPolicy(settings.MaxRetries, settings.RequestTimeout); + var sender = new RetryingSender(transport, policy, delay); + + return new BatchFormatter(sender, new RequestBodyWriter(caller), limits, settings.MaxConcurrentRequests); + } + + /// + /// Formats the texts and returns their results in the same order. + /// + /// A request failed. + /// The token was cancelled. + public async Task FormatAsync( + string[] texts, + FormatSettings settings, + IProgress? progress, + CancellationToken cancellationToken) + { + var plan = BatchPlanner.Plan(texts, settings.Kind, _limits); + var reporter = new ProgressReporter(progress, texts.Length); + using var run = new BatchRun(plan, settings, _bodyWriter, _sender, reporter, cancellationToken); + + return await run.RunAsync(_maxConcurrentRequests).ConfigureAwait(false); + } +} diff --git a/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs b/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs new file mode 100644 index 0000000..f08f2a8 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs @@ -0,0 +1,38 @@ +using Dax.Formatter.Expressions; + +namespace Dax.Formatter.Batching; + +/// +/// How the texts of a call are sent: the header of each text, the requests they are split into, and the blank +/// texts, which are not sent. +/// +internal sealed class BatchPlan +{ + private readonly string[] _texts; + private readonly ExpressionHeader?[]? _headers; + + public BatchPlan(string[] texts, ExpressionHeader?[]? headers, List chunks, List blankIndexes) + { + _texts = texts; + _headers = headers; + Chunks = chunks; + BlankIndexes = blankIndexes; + } + + public int TextCount => _texts.Length; + + public List Chunks { get; } + + public List BlankIndexes { get; } + + public string GetText(int index) + { + return _texts[index]; + } + + /// Gets the header that the text is sent under, or when it is sent as it is. + public ExpressionHeader? GetHeader(int index) + { + return _headers?[index]; + } +} diff --git a/dotnet/src/Dax.Formatter/Batching/BatchPlanner.cs b/dotnet/src/Dax.Formatter/Batching/BatchPlanner.cs new file mode 100644 index 0000000..632938c --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchPlanner.cs @@ -0,0 +1,53 @@ +using Dax.Formatter.Configuration; +using Dax.Formatter.Expressions; + +namespace Dax.Formatter.Batching; + +/// +/// Splits the texts of a call into requests that stay within the limits, and chooses the header of each text. +/// +internal static class BatchPlanner +{ + public static BatchPlan Plan(string[] texts, DaxKind kind, BatchLimits limits) + { + var headers = kind == DaxKind.Expression ? new ExpressionHeader?[texts.Length] : null; + var chunks = new List(); + var blankIndexes = new List(); + var current = new List(); + var currentCharacters = 0; + + for (var index = 0; index < texts.Length; index++) + { + var text = texts[index]; + if (string.IsNullOrWhiteSpace(text)) + { + blankIndexes.Add(index); + continue; + } + + if (headers is not null) + { + headers[index] = ExpressionHeader.For(text); + } + + // A text longer than the limit still travels, in a request of its own. + var isFull = current.Count >= limits.MaxTexts || currentCharacters + text.Length > limits.MaxCharacters; + if (current.Count > 0 && isFull) + { + chunks.Add(new Chunk([.. current])); + current.Clear(); + currentCharacters = 0; + } + + current.Add(index); + currentCharacters += text.Length; + } + + if (current.Count > 0) + { + chunks.Add(new Chunk([.. current])); + } + + return new BatchPlan(texts, headers, chunks, blankIndexes); + } +} diff --git a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs new file mode 100644 index 0000000..c619c2f --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs @@ -0,0 +1,176 @@ +using Dax.Formatter.Configuration; +using Dax.Formatter.Results; +using Dax.Formatter.Transport; +using Dax.Formatter.Wire; + +namespace Dax.Formatter.Batching; + +/// +/// One call in progress: a few workers take the requests of the plan in turn and write each result at the index +/// of its text. The first request that fails stops the others, and the call fails with it. +/// +internal sealed class BatchRun : IDisposable +{ + private readonly BatchPlan _plan; + private readonly FormatSettings _settings; + private readonly RequestBodyWriter _bodyWriter; + private readonly RetryingSender _sender; + private readonly ProgressReporter _progress; + private readonly DaxFormatResult[] _results; + private readonly Guid _operationId = Guid.NewGuid(); + private readonly CancellationToken _callerToken; + + // The workers watch the token of this source: the caller cancels it, and so does the first request that fails. + private readonly CancellationTokenSource _stop; + + private int _nextChunk; + private DaxFormatterException? _failure; + private volatile bool _stopped; + + public BatchRun( + BatchPlan plan, + FormatSettings settings, + RequestBodyWriter bodyWriter, + RetryingSender sender, + ProgressReporter progress, + CancellationToken cancellationToken) + { + _plan = plan; + _settings = settings; + _bodyWriter = bodyWriter; + _sender = sender; + _progress = progress; + _results = new DaxFormatResult[plan.TextCount]; + _callerToken = cancellationToken; + _stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + } + + public async Task RunAsync(int maxConcurrentRequests) + { + _callerToken.ThrowIfCancellationRequested(); + CompleteBlankTexts(); + + var workers = new Task[Math.Min(maxConcurrentRequests, _plan.Chunks.Count)]; + for (var i = 0; i < workers.Length; i++) + { + workers[i] = WorkAsync(); + } + + await Task.WhenAll(workers).ConfigureAwait(false); + + if (!_stopped) + { + return _results; + } + + // A cancellation by the caller wins over a failure that happened at the same time. + _callerToken.ThrowIfCancellationRequested(); + throw _failure ?? new DaxFormatterException("The call stopped before every request was sent."); + } + + public void Dispose() + { + _stop.Dispose(); + } + + // A blank text is not sent: the service would format it to an empty text. + private void CompleteBlankTexts() + { + foreach (var index in _plan.BlankIndexes) + { + _results[index] = DaxFormatResult.Success(_plan.GetText(index), string.Empty); + } + + _progress.Report(_plan.BlankIndexes.Count); + } + + private async Task WorkAsync() + { + var finished = false; + try + { + while (true) + { + var index = Interlocked.Increment(ref _nextChunk) - 1; + if (index >= _plan.Chunks.Count) + { + finished = true; + return; + } + + _stop.Token.ThrowIfCancellationRequested(); + await FormatChunkAsync(_plan.Chunks[index], _stop.Token).ConfigureAwait(false); + } + } + catch (DaxFormatterException exception) + { + Interlocked.CompareExchange(ref _failure, exception, null); + } + catch (OperationCanceledException) + { + // The caller or a failed request stopped the call: RunAsync tells which. + } + finally + { + if (!finished) + { + _stopped = true; + await StopOthersAsync().ConfigureAwait(false); + } + } + } + + private async Task FormatChunkAsync(Chunk chunk, CancellationToken cancellationToken) + { + var request = CreateRequest(chunk); + var response = await _sender.SendAsync(request, cancellationToken).ConfigureAwait(false); + var items = response.Items!; + + for (var position = 0; position < chunk.Count; position++) + { + var index = chunk[position]; + var header = _plan.GetHeader(index); + if (!ResultMapper.TryMap(_plan.GetText(index), header, items[position], out var result)) + { + var detail = FormattableString.Invariant( + $"the result of the text at index {index} does not start with the header that the client added"); + throw request.CreateException( + DaxFormatterFailureReason.InvalidResponse, + detail, + response.StatusCode, + response.ServiceRequestId, + innerException: null); + } + + _results[index] = result; + } + + _progress.Report(chunk.Count); + } + + // The texts get their headers only here, so that a large call does not hold a second copy of every text. + private FormatRequest CreateRequest(Chunk chunk) + { + var dax = new List(chunk.Count); + for (var position = 0; position < chunk.Count; position++) + { + var index = chunk[position]; + var text = _plan.GetText(index); + var header = _plan.GetHeader(index); + dax.Add(header is null ? text : header.AddTo(text)); + } + + var body = _bodyWriter.Write(dax, _settings); + return new FormatRequest(body, chunk.Count, chunk.FirstIndex, chunk.LastIndex, _operationId); + } + + private Task StopOthersAsync() + { +#if NET + return _stop.CancelAsync(); +#else + _stop.Cancel(); + return Task.CompletedTask; +#endif + } +} diff --git a/dotnet/src/Dax.Formatter/Batching/Chunk.cs b/dotnet/src/Dax.Formatter/Batching/Chunk.cs new file mode 100644 index 0000000..745bff6 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/Chunk.cs @@ -0,0 +1,23 @@ +namespace Dax.Formatter.Batching; + +/// +/// The texts of a call that travel in one request, as their indexes in the texts of the call, in order. +/// +internal sealed class Chunk +{ + private readonly int[] _textIndexes; + + public Chunk(int[] textIndexes) + { + _textIndexes = textIndexes; + } + + public int Count => _textIndexes.Length; + + public int FirstIndex => _textIndexes[0]; + + public int LastIndex => _textIndexes[_textIndexes.Length - 1]; + + /// Gets the index, in the texts of the call, of the text at a position of the request. + public int this[int position] => _textIndexes[position]; +} diff --git a/dotnet/src/Dax.Formatter/Batching/ProgressReporter.cs b/dotnet/src/Dax.Formatter/Batching/ProgressReporter.cs new file mode 100644 index 0000000..a62ec63 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/ProgressReporter.cs @@ -0,0 +1,33 @@ +namespace Dax.Formatter.Batching; + +/// +/// Reports how many texts of a call are done. Requests end on different threads, so the count and the report +/// happen together under a lock: the reported count never goes backwards. +/// +internal sealed class ProgressReporter +{ + private readonly object _gate = new(); + private readonly IProgress? _progress; + private readonly int _total; + private int _completed; + + public ProgressReporter(IProgress? progress, int total) + { + _progress = progress; + _total = total; + } + + public void Report(int newlyCompleted) + { + if (_progress is null || newlyCompleted == 0) + { + return; + } + + lock (_gate) + { + _completed += newlyCompleted; + _progress.Report(new DaxFormatProgressInfo(_completed, _total)); + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs new file mode 100644 index 0000000..4939a40 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs @@ -0,0 +1,91 @@ +using Dax.Formatter.Batching; +using Dax.Formatter.Configuration; +using Dax.Formatter.Expressions; +using Xunit; + +namespace Dax.Formatter.Tests.Batching; + +public class BatchPlannerTests +{ + [Theory] + [InlineData(5, 2, "0,1|2,3|4")] + [InlineData(4, 2, "0,1|2,3")] + [InlineData(3, 5, "0,1,2")] + [InlineData(2, 1, "0|1")] + [InlineData(0, 2, "")] + public void Plan_MoreTextsThanARequestCarries_SplitsThemByCount(int textCount, int maxTexts, string expected) + { + var texts = Enumerable.Repeat("EVALUATE Sales", textCount).ToArray(); + + var plan = BatchPlanner.Plan(texts, DaxKind.Auto, new BatchLimits(maxTexts, maxCharacters: 1000)); + + Assert.Equal(expected, Describe(plan)); + } + + [Theory] + [InlineData(new[] { 4, 4, 4 }, 8, "0,1|2")] + [InlineData(new[] { 4, 4, 4 }, 7, "0|1|2")] + [InlineData(new[] { 3, 20, 3 }, 10, "0|1|2")] + [InlineData(new[] { 20, 3, 3 }, 10, "0|1,2")] + [InlineData(new[] { 3, 3, 20 }, 10, "0,1|2")] + public void Plan_MoreCharactersThanARequestCarries_SplitsThemByLength( + int[] lengths, int maxCharacters, string expected) + { + var texts = lengths.Select(length => new string('x', length)).ToArray(); + + var plan = BatchPlanner.Plan(texts, DaxKind.Auto, new BatchLimits(maxTexts: 100, maxCharacters)); + + Assert.Equal(expected, Describe(plan)); + } + + [Fact] + public void Plan_BlankTexts_LeavesThemOutOfTheRequests() + { + string[] texts = ["a", "", " \r\n\t", "b", "c"]; + + var plan = BatchPlanner.Plan(texts, DaxKind.Auto, new BatchLimits(maxTexts: 2, maxCharacters: 1000)); + + Assert.Equal([1, 2], plan.BlankIndexes); + Assert.Equal("0,3|4", Describe(plan)); + } + + [Fact] + public void Plan_Expressions_ChoosesTheHeaderOfEachText() + { + string[] texts = ["SUM(Sales[Amount])", "(a) => a", ""]; + + var plan = BatchPlanner.Plan(texts, DaxKind.Expression, BatchLimits.Default); + + Assert.Same(ExpressionHeader.Measure, plan.GetHeader(0)); + Assert.Same(ExpressionHeader.Function, plan.GetHeader(1)); + Assert.Null(plan.GetHeader(2)); + } + + [Fact] + public void Plan_TextsSentAsTheyAre_HaveNoHeader() + { + string[] texts = ["(a) => a"]; + + var plan = BatchPlanner.Plan(texts, DaxKind.Auto, BatchLimits.Default); + + Assert.Null(plan.GetHeader(0)); + } + + [Fact] + public void Plan_Chunk_KnowsItsFirstAndLastText() + { + string[] texts = ["a", "", "b", "c"]; + + var plan = BatchPlanner.Plan(texts, DaxKind.Auto, new BatchLimits(maxTexts: 2, maxCharacters: 1000)); + + Assert.Equal((0, 2), (plan.Chunks[0].FirstIndex, plan.Chunks[0].LastIndex)); + Assert.Equal((3, 3), (plan.Chunks[1].FirstIndex, plan.Chunks[1].LastIndex)); + } + + private static string Describe(BatchPlan plan) + { + var chunks = plan.Chunks.Select( + chunk => string.Join(",", Enumerable.Range(0, chunk.Count).Select(position => chunk[position]))); + return string.Join("|", chunks); + } +} From 4fe464f0b2fe75948c903e16e5e47e3436529e13 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:16 +0100 Subject: [PATCH 08/29] feat(dotnet)!: add the 2.0 client - add DaxFormatterClient with FormatAsync for one text and FormatBatchAsync for texts or for items with a text selector; the results come back in the order of the input, each with its item - check the arguments before the first request and create nothing in the constructor, so that a class can derive from the client - test the client offline against a fake HTTP handler that records the requests, with a recorded wait in place of the retry delay - pin the public surface in an approved file, on both target frameworks, and the overload each kind of call binds to Closes #40 Closes #6 --- .../src/Dax.Formatter/DaxFormatterClient.cs | 251 ++++++++++++++++ .../Batching/BatchRunTests.cs | 185 ++++++++++++ .../Batching/ProgressReporterTests.cs | 73 +++++ .../Dax.Formatter.Tests.csproj | 1 + .../DaxFormatterClientTests.cs | 281 ++++++++++++++++++ .../Dax.Formatter.Tests/Fakes/EchoService.cs | 103 +++++++ .../Fakes/FakeFormatterHandler.cs | 81 +++++ .../Fakes/FormatterHarness.cs | 46 +++ .../Dax.Formatter.Tests/Fakes/ListProgress.cs | 28 ++ .../Fakes/RecordedRequest.cs | 49 +++ .../Fakes/RecordingDelay.cs | 39 +++ .../Dax.Formatter.Tests/Fakes/Respond.cs | 104 +++++++ .../Fixtures/request-bodies.json | 181 +++++++++++ .../PublicApi.approved.txt | 91 ++++++ .../Dax.Formatter.Tests/PublicApiTests.cs | 156 ++++++++++ .../PublicApiUsageTests.cs | 90 ++++++ .../Transport/FormatterTransportTests.cs | 120 ++++++++ .../Transport/RetryingSenderTests.cs | 150 ++++++++++ .../Wire/RequestBodyWriterTests.cs | 48 +++ 19 files changed, 2077 insertions(+) create mode 100644 dotnet/src/Dax.Formatter/DaxFormatterClient.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/FakeFormatterHandler.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/FormatterHarness.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/ListProgress.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/RecordingDelay.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json create mode 100644 dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt create mode 100644 dotnet/tests/Dax.Formatter.Tests/PublicApiTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/PublicApiUsageTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Transport/RetryingSenderTests.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Wire/RequestBodyWriterTests.cs diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs new file mode 100644 index 0000000..7d5729c --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs @@ -0,0 +1,251 @@ +using Dax.Formatter.Batching; +using Dax.Formatter.Configuration; +using Dax.Formatter.Transport; + +namespace Dax.Formatter; + +/// +/// Formats DAX text with the DAX Formatter service. An instance is thread-safe and meant to be reused: create +/// one and keep it for the life of the application. +/// +/// +/// A syntax error in a text is part of its . A failure of the service or of the +/// network throws , and a cancellation by the caller throws +/// . +/// +public class DaxFormatterClient +{ + private readonly Lazy _formatter; + + /// + /// Initializes a new instance of the class with the default options. It + /// uses an that all such instances share. + /// + public DaxFormatterClient() + : this(httpClient: null, ClientSettings.From(new DaxFormatterClientOptions()), TaskDelay.Instance, BatchLimits.Default) + { + } + + /// + /// Initializes a new instance of the class with the given options. It uses + /// an that all such instances share. + /// + /// The options, which are copied. + public DaxFormatterClient(DaxFormatterClientOptions options) + : this(httpClient: null, ClientSettings.From(options), TaskDelay.Instance, BatchLimits.Default) + { + } + + /// + /// Initializes a new instance of the class that sends its requests with + /// the given . + /// + /// + /// The to use. The caller owns it: the client never changes or disposes it, and + /// ignores its . + /// + public DaxFormatterClient(HttpClient httpClient) + : this(Required(httpClient), ClientSettings.From(new DaxFormatterClientOptions()), TaskDelay.Instance, BatchLimits.Default) + { + } + + /// + /// Initializes a new instance of the class that sends its requests with + /// the given , with the given options. + /// + /// + /// The to use. The caller owns it: the client never changes or disposes it, and + /// ignores its . + /// + /// The options, which are copied. + public DaxFormatterClient(HttpClient httpClient, DaxFormatterClientOptions options) + : this(Required(httpClient), ClientSettings.From(options), TaskDelay.Instance, BatchLimits.Default) + { + } + + internal DaxFormatterClient( + HttpClient httpClient, + DaxFormatterClientOptions options, + IDelay delay, + BatchLimits limits) + : this(Required(httpClient), ClientSettings.From(options), delay, limits) + { + } + + // Nothing is created or resolved here: a class that derives from this one, such as a mock, pays nothing. + private DaxFormatterClient(HttpClient? httpClient, ClientSettings settings, IDelay delay, BatchLimits limits) + { + _formatter = new Lazy( + () => BatchFormatter.Create(httpClient ?? SharedHttpClient.Instance, settings, delay, limits)); + } + + /// + /// Formats one DAX text. + /// + /// The DAX text. A blank text is formatted to an empty text without a request. + /// The options of the call, or for the defaults. + /// The token that cancels the call. + /// The formatted text, or the syntax errors of the text. + /// is . + /// has a value that is not valid. + /// The service or the network failed. + /// The call was cancelled. + public virtual Task FormatAsync( + string text, + DaxFormatOptions? options = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(text); + var settings = FormatSettings.From(options); + + return FormatOneAsync(text, settings, cancellationToken); + } + + /// + /// Formats several DAX texts with as few requests as they need, and returns one result for each text, in + /// the order of the texts. + /// + /// The DAX texts. They are read once, before the first request. + /// The options of the call, or for the defaults. + /// The receiver of the number of texts done, or . + /// The token that cancels the call. + /// One result for each text, or an empty list for no texts. + /// is . + /// + /// A text is , or has a value that is not valid. + /// + /// The service or the network failed: no result is returned. + /// The call was cancelled. + public virtual Task> FormatBatchAsync( + IEnumerable texts, + DaxFormatOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(texts); + + string[] copy = [.. texts]; + var missing = Array.IndexOf(copy, null); + if (missing >= 0) + { + var message = FormattableString.Invariant($"The text at index {missing} is null."); + throw new ArgumentException(message, nameof(texts)); + } + + var settings = FormatSettings.From(options); + + return FormatManyAsync(copy, settings, progress, cancellationToken); + } + + /// + /// Formats the DAX text of several items, such as the measures of a model, and returns one result for each + /// item, in the order of the items, each with the item it belongs to. + /// + /// The type of the items. + /// The items. They are read once, before the first request. + /// The function that returns the DAX text of an item. + /// The options of the call, or for the defaults. + /// The receiver of the number of texts done, or . + /// The token that cancels the call. + /// One result for each item, or an empty list for no items. + /// + /// This method calls + /// , + /// so a class that overrides that method changes this one too. + /// + /// + /// or is . + /// + /// + /// returned , or has a value + /// that is not valid. + /// + /// The service or the network failed: no result is returned. + /// The call was cancelled. + public Task>> FormatBatchAsync( + IEnumerable items, + Func textSelector, + DaxFormatOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(textSelector); + + TItem[] copy = [.. items]; + var texts = new string[copy.Length]; + for (var index = 0; index < copy.Length; index++) + { + var text = textSelector(copy[index]); + if (text is null) + { + var message = FormattableString.Invariant( + $"The text selector returned null for the item at index {index}."); + throw new ArgumentException(message, nameof(textSelector)); + } + + texts[index] = text; + } + + // The options are checked here so that a wrong value throws now, like the other arguments. + _ = FormatSettings.From(options); + + return FormatItemsAsync(copy, texts, options, progress, cancellationToken); + } + + private static HttpClient Required(HttpClient httpClient) + { + ArgumentNullException.ThrowIfNull(httpClient); + return httpClient; + } + + private async Task FormatOneAsync( + string text, + FormatSettings settings, + CancellationToken cancellationToken) + { + var results = await _formatter.Value + .FormatAsync([text], settings, progress: null, cancellationToken) + .ConfigureAwait(false); + + return results[0]; + } + + private async Task> FormatManyAsync( + string[] texts, + FormatSettings settings, + IProgress? progress, + CancellationToken cancellationToken) + { + if (texts.Length == 0) + { + return []; + } + + return await _formatter.Value + .FormatAsync(texts, settings, progress, cancellationToken) + .ConfigureAwait(false); + } + + private async Task>> FormatItemsAsync( + TItem[] items, + string[] texts, + DaxFormatOptions? options, + IProgress? progress, + CancellationToken cancellationToken) + { + var results = await FormatBatchAsync(texts, options, progress, cancellationToken).ConfigureAwait(false); + if (results is null || results.Count != items.Length) + { + throw new InvalidOperationException("FormatBatchAsync must return one result for each text."); + } + + var paired = new DaxFormatResult[items.Length]; + for (var index = 0; index < items.Length; index++) + { + paired[index] = new DaxFormatResult(items[index], results[index]); + } + + return paired; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs new file mode 100644 index 0000000..7838c6d --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs @@ -0,0 +1,185 @@ +using System.Net; +using Dax.Formatter.Configuration; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests.Batching; + +public class BatchRunTests +{ + private static readonly BatchLimits s_oneTextPerRequest = new(maxTexts: 1, maxCharacters: 1000); + private static readonly BatchLimits s_twoTextsPerRequest = new(maxTexts: 2, maxCharacters: 1000); + private static readonly string[] s_fiveTexts = ["a", "b", "c", "d", "e"]; + + [Fact] + public async Task FormatBatchAsync_AnswersOutOfOrder_ReturnsTheResultsInTheOrderOfTheTexts() + { + var lastArrived = NewSignal(); + Responder responder = async (request, cancellationToken) => + { + // The first two requests are answered only after the third one has arrived. + if (request.Number == 2) + { + lastArrived.TrySetResult(true); + } + + await lastArrived.Task.ConfigureAwait(false); + return await Respond.Echo(request, cancellationToken).ConfigureAwait(false); + }; + using var harness = new FormatterHarness( + responder, options => options.MaxConcurrentRequests = 3, s_twoTextsPerRequest); + + var results = await harness.Client.FormatBatchAsync(s_fiveTexts).ConfigureAwait(true); + + Assert.Equal(3, harness.Handler.Requests.Count); + Assert.Equal(s_fiveTexts, results.Select(result => result.FormattedText)); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public async Task FormatBatchAsync_MoreRequestsThanAllowedAtOnce_KeepsToTheLimit(int maxConcurrentRequests) + { + var enoughArrived = NewSignal(); + Responder responder = async (request, cancellationToken) => + { + // Nothing is answered until as many requests as the limit allows are in progress. + if (request.Number == maxConcurrentRequests - 1) + { + enoughArrived.TrySetResult(true); + } + + await enoughArrived.Task.ConfigureAwait(false); + return await Respond.Echo(request, cancellationToken).ConfigureAwait(false); + }; + using var harness = new FormatterHarness( + responder, options => options.MaxConcurrentRequests = maxConcurrentRequests, s_oneTextPerRequest); + + await harness.Client.FormatBatchAsync(s_fiveTexts).ConfigureAwait(true); + + Assert.Equal(5, harness.Handler.Requests.Count); + Assert.Equal(maxConcurrentRequests, harness.Handler.MaxInFlight); + } + + [Fact] + public async Task FormatBatchAsync_RequestsOfOneCall_ShareTheOperationIdOnly() + { + using var harness = new FormatterHarness(Respond.Echo, limits: s_twoTextsPerRequest); + + await harness.Client.FormatBatchAsync(s_fiveTexts).ConfigureAwait(true); + + var requests = harness.Handler.Requests; + Assert.Single(requests.Select(request => request.GetHeader("DaxFormatter-Operation-Id")).Distinct()); + Assert.Equal(3, requests.Select(request => request.GetHeader("DaxFormatter-Request-Id")).Distinct().Count()); + } + + [Fact] + public async Task FormatBatchAsync_OneRequestFails_StopsTheOthersAndThrowsItsFailure() + { + var allArrived = NewSignal(); + Responder responder = async (request, cancellationToken) => + { + if (request.Number == 2) + { + allArrived.TrySetResult(true); + } + + await allArrived.Task.ConfigureAwait(false); + var answer = request.Dax[0] == "c" ? Respond.Status(HttpStatusCode.BadRequest) : Respond.Hang; + return await answer(request, cancellationToken).ConfigureAwait(false); + }; + using var harness = new FormatterHarness( + responder, options => options.MaxConcurrentRequests = 3, s_twoTextsPerRequest); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatBatchAsync(s_fiveTexts)) + .ConfigureAwait(true); + + Assert.Equal(HttpStatusCode.BadRequest, exception.StatusCode); + Assert.Contains("the texts at indexes 2 to 3", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task FormatBatchAsync_OneRequestFails_DoesNotSendTheRemainingOnes() + { + var responder = Respond.Sequence(Respond.Echo, Respond.Status(HttpStatusCode.BadRequest), Respond.Echo); + using var harness = new FormatterHarness( + responder, options => options.MaxConcurrentRequests = 1, s_oneTextPerRequest); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatBatchAsync(s_fiveTexts)) + .ConfigureAwait(true); + + Assert.Equal(2, harness.Handler.Requests.Count); + Assert.Contains("the text at index 1 ", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task FormatBatchAsync_CallerCancels_ThrowsOperationCanceledWithTheTokenOfTheCaller() + { + using var cancellation = new CancellationTokenSource(); + var responder = Respond.OnArrival(cancellation.Cancel, Respond.Hang); + using var harness = new FormatterHarness(responder, limits: s_oneTextPerRequest); + + var exception = await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatBatchAsync(s_fiveTexts, cancellationToken: cancellation.Token)) + .ConfigureAwait(true); + + Assert.Equal(cancellation.Token, exception.CancellationToken); + } + + [Fact] + public async Task FormatBatchAsync_CallerCancelsWhileARequestFails_ThrowsOperationCanceled() + { + using var cancellation = new CancellationTokenSource(); + var responder = Respond.OnArrival(cancellation.Cancel, Respond.Status(HttpStatusCode.BadRequest)); + using var harness = new FormatterHarness(responder, limits: s_oneTextPerRequest); + + var exception = await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatBatchAsync(s_fiveTexts, cancellationToken: cancellation.Token)) + .ConfigureAwait(true); + + Assert.Equal(cancellation.Token, exception.CancellationToken); + } + + [Fact] + public async Task FormatBatchAsync_TokenAlreadyCancelled_SendsNothing() + { + var cancelled = new CancellationToken(canceled: true); + using var harness = new FormatterHarness(Respond.Echo); + + await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatBatchAsync(s_fiveTexts, cancellationToken: cancelled)) + .ConfigureAwait(true); + + Assert.Empty(harness.Handler.Requests); + } + + [Fact] + public async Task FormatBatchAsync_ResultWithoutTheHeaderOfTheClient_FailsAndNamesTheText() + { + var withoutHeader = Respond.Json("[{\"formatted\":\"1 + 2\\r\\n\",\"errors\":[]}]"); + using var harness = new FormatterHarness( + Respond.Sequence(Respond.Echo, withoutHeader), + options => options.MaxConcurrentRequests = 1, + s_oneTextPerRequest); + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatBatchAsync(["1", "1+2"], options)) + .ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, exception.Reason); + Assert.Contains("the text at index 1 ", exception.Message, StringComparison.Ordinal); + Assert.Equal(Respond.ServiceRequestId, exception.ServiceRequestId); + } + + private static TaskCompletionSource NewSignal() + { + return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs new file mode 100644 index 0000000..84b539b --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs @@ -0,0 +1,73 @@ +using Dax.Formatter.Batching; +using Dax.Formatter.Configuration; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests.Batching; + +public class ProgressReporterTests +{ + [Fact] + public void Report_SeveralTimes_AddsUpTheTextsDone() + { + var progress = new ListProgress(); + var reporter = new ProgressReporter(progress, total: 10); + + reporter.Report(2); + reporter.Report(3); + + Assert.Equal([(2, 10), (5, 10)], progress.Reports); + } + + [Fact] + public void Report_NoTextsDone_ReportsNothing() + { + var progress = new ListProgress(); + var reporter = new ProgressReporter(progress, total: 10); + + reporter.Report(0); + + Assert.Empty(progress.Reports); + } + + [Fact] + public void Report_NoReceiver_DoesNothing() + { + var reporter = new ProgressReporter(progress: null, total: 10); + + var exception = Record.Exception(() => reporter.Report(2)); + + Assert.Null(exception); + } + + [Fact] + public async Task FormatBatchAsync_BlankTexts_CountsThemBeforeTheFirstRequest() + { + var progress = new ListProgress(); + using var harness = new FormatterHarness( + Respond.Echo, + options => options.MaxConcurrentRequests = 1, + new BatchLimits(maxTexts: 1, maxCharacters: 1000)); + + await harness.Client.FormatBatchAsync(["", "a", "b", " "], progress: progress).ConfigureAwait(true); + + Assert.Equal([(2, 4), (3, 4), (4, 4)], progress.Reports); + } + + [Fact] + public async Task FormatBatchAsync_RequestsInParallel_NeverReportsFewerTextsThanBefore() + { + var progress = new ListProgress(); + var texts = Enumerable.Range(0, 40).Select(number => "EVALUATE T" + number); + using var harness = new FormatterHarness( + Respond.Echo, + options => options.MaxConcurrentRequests = 4, + new BatchLimits(maxTexts: 3, maxCharacters: 1000)); + + await harness.Client.FormatBatchAsync(texts, progress: progress).ConfigureAwait(true); + + var completed = progress.Reports.Select(report => report.Completed).ToList(); + Assert.Equal(completed.OrderBy(count => count), completed); + Assert.Equal((40, 40), progress.Reports[progress.Reports.Count - 1]); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj index b5cf10f..a65f9ad 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -29,6 +29,7 @@ + diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs new file mode 100644 index 0000000..b377b3e --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs @@ -0,0 +1,281 @@ +using System.Collections; +using System.Net.Http; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxFormatterClientTests +{ + private static readonly DaxFormatOptions s_expression = new() { Kind = DaxKind.Expression }; + private static readonly DaxFormatOptions s_invalidOptions = new() { LineStyle = (DaxLineStyle)7 }; + + [Fact] + public void Constructor_NullArgument_Throws() + { + using var httpClient = new HttpClient(); + + Assert.Throws("httpClient", () => new DaxFormatterClient((HttpClient)null!)); + Assert.Throws("options", () => new DaxFormatterClient((DaxFormatterClientOptions)null!)); + Assert.Throws("options", () => new DaxFormatterClient(httpClient, null!)); + } + + [Fact] + public void Constructor_OptionOutOfRange_Throws() + { + var options = new DaxFormatterClientOptions { MaxConcurrentRequests = 0 }; + + Assert.Throws("options", () => new DaxFormatterClient(options)); + } + + [Fact] + public void FormatAsync_NullText_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + + Assert.Throws("text", () => { _ = harness.Client.FormatAsync(null!); }); + } + + [Fact] + public void FormatAsync_OptionOutsideItsEnumeration_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + + Assert.Throws("options", () => { _ = harness.Client.FormatAsync("1", s_invalidOptions); }); + } + + [Fact] + public void FormatBatchAsync_NullTexts_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + + Assert.Throws( + "texts", () => { _ = harness.Client.FormatBatchAsync((IEnumerable)null!); }); + } + + [Fact] + public void FormatBatchAsync_NullText_ThrowsWithItsIndex() + { + using var harness = new FormatterHarness(Respond.Echo); + + var exception = Assert.Throws( + "texts", () => { _ = harness.Client.FormatBatchAsync(["a", "b", null!, null!]); }); + + Assert.Contains("index 2", exception.Message, StringComparison.Ordinal); + Assert.Empty(harness.Handler.Requests); + } + + [Fact] + public void FormatBatchAsync_NullItemsOrSelector_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1, 2]; + + Assert.Throws( + "items", () => { _ = harness.Client.FormatBatchAsync((IEnumerable)null!, item => "1"); }); + Assert.Throws( + "textSelector", () => { _ = harness.Client.FormatBatchAsync(items, (Func)null!); }); + } + + [Fact] + public void FormatBatchAsync_SelectorReturnsNull_ThrowsWithTheIndexOfTheItem() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1, 2, 3]; + + var exception = Assert.Throws( + "textSelector", () => { _ = harness.Client.FormatBatchAsync(items, item => item == 2 ? null! : "1"); }); + + Assert.Contains("index 1", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void FormatBatchAsync_ItemsWithOptionOutsideItsEnumeration_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1]; + + Assert.Throws( + "options", () => { _ = harness.Client.FormatBatchAsync(items, item => "1", s_invalidOptions); }); + } + + [Fact] + public async Task FormatAsync_Query_ReturnsItFormattedWithoutTheFinalLineBreak() + { + using var harness = new FormatterHarness(Respond.Echo); + + var result = await harness.Client.FormatAsync("EVALUATE\nSales").ConfigureAwait(true); + + Assert.True(result.Succeeded); + Assert.Equal(("EVALUATE\nSales", "EVALUATE\r\nSales"), (result.OriginalText, result.FormattedText)); + } + + [Fact] + public async Task FormatAsync_Expression_ReturnsItWithoutTheHeader() + { + using var harness = new FormatterHarness(Respond.Echo); + + var result = await harness.Client.FormatAsync("SUM ( Sales[Amount] )", s_expression).ConfigureAwait(true); + + Assert.Equal("[x] :=\nSUM ( Sales[Amount] )", Assert.Single(harness.Handler.Requests[0].Dax)); + Assert.Equal("SUM ( Sales[Amount] )", result.FormattedText); + } + + [Theory] + [InlineData("(a) =>\n a + 1", "(a) =>\r\n a + 1")] + [InlineData("// c\n(a) =>\n a + 1", "// c\r\n(a) =>\r\n a + 1")] + public async Task FormatAsync_FunctionBody_ReturnsItWithoutTheHeaderAndItsIndentation(string text, string expected) + { + using var harness = new FormatterHarness(Respond.Echo); + + var result = await harness.Client.FormatAsync(text, s_expression).ConfigureAwait(true); + + Assert.StartsWith("FUNCTION x =\n", harness.Handler.Requests[0].Dax[0], StringComparison.Ordinal); + Assert.Equal(expected, result.FormattedText); + } + + [Fact] + public async Task FormatAsync_SyntaxError_ReturnsItAsAResultWithItsPositionInTheText() + { + using var harness = new FormatterHarness(Respond.Echo); + + var result = await harness.Client.FormatAsync("1 +\n\t2 +* 3", s_expression).ConfigureAwait(true); + + Assert.False(result.Succeeded); + Assert.Null(result.FormattedText); + Assert.Equal(new DaxSyntaxError(1, 3, EchoService.ErrorMessage), Assert.Single(result.Errors)); + } + + [Theory] + [InlineData("")] + [InlineData(" \r\n\t")] + public async Task FormatAsync_BlankText_ReturnsAnEmptyTextWithoutARequest(string text) + { + using var harness = new FormatterHarness(Respond.Echo); + + var result = await harness.Client.FormatAsync(text, s_expression).ConfigureAwait(true); + + Assert.Equal((text, string.Empty), (result.OriginalText, result.FormattedText)); + Assert.Empty(harness.Handler.Requests); + } + + [Fact] + public async Task FormatBatchAsync_NoTexts_ReturnsNoResultsWithoutARequest() + { + using var harness = new FormatterHarness(Respond.Echo); + var progress = new ListProgress(); + + var results = await harness.Client.FormatBatchAsync([], progress: progress).ConfigureAwait(true); + + Assert.Empty(results); + Assert.Empty(harness.Handler.Requests); + Assert.Empty(progress.Reports); + } + + [Fact] + public async Task FormatBatchAsync_BlankTextsAmongOthers_KeepsEachResultAtTheIndexOfItsText() + { + using var harness = new FormatterHarness(Respond.Echo); + + var results = await harness.Client.FormatBatchAsync(["", "1", " ", "2 +* 2"], s_expression).ConfigureAwait(true); + + Assert.Equal(["", "1", "", null], results.Select(result => result.FormattedText)); + Assert.Equal(["", "1", " ", "2 +* 2"], results.Select(result => result.OriginalText)); + Assert.Equal(2, Assert.Single(harness.Handler.Requests).Dax.Count); + } + + [Fact] + public async Task FormatBatchAsync_Items_ReturnsEachResultWithItsItem() + { + using var harness = new FormatterHarness(Respond.Echo); + var measures = new[] + { + new KeyValuePair("Sales", "SUM ( Sales[Amount] )"), + new KeyValuePair("Broken", "1 +* 2"), + new KeyValuePair("Cost", "SUM ( Sales[Cost] )"), + }; + + var results = await harness.Client + .FormatBatchAsync(measures, measure => measure.Value, s_expression) + .ConfigureAwait(true); + + Assert.Equal(measures, results.Select(result => result.Item)); + Assert.Equal(["SUM ( Sales[Amount] )", null, "SUM ( Sales[Cost] )"], results.Select(result => result.FormattedText)); + } + + [Fact] + public async Task FormatBatchAsync_TextsThatCanBeReadOnce_ReadsThemOnce() + { + using var harness = new FormatterHarness(Respond.Echo); + var texts = new CountingEnumerable(["EVALUATE A", "EVALUATE B"]); + + var results = await harness.Client.FormatBatchAsync(texts).ConfigureAwait(true); + + Assert.Equal(1, texts.Enumerations); + Assert.Equal(2, results.Count); + } + + [Fact] + public async Task FormatBatchAsync_ItemsOnADerivedClient_UsesItsOverrideForTexts() + { + var client = new CannedClient(texts => [.. texts.Select(text => DaxFormatResult.Success(text, "canned " + text))]); + + var results = await client.FormatBatchAsync([1, 2], item => "text " + item).ConfigureAwait(true); + + Assert.Equal([1, 2], results.Select(result => result.Item)); + Assert.Equal(["canned text 1", "canned text 2"], results.Select(result => result.FormattedText)); + } + + [Fact] + public async Task FormatBatchAsync_OverrideReturnsTheWrongNumberOfResults_Throws() + { + var client = new CannedClient(_ => []); + + await Assert + .ThrowsAsync(() => client.FormatBatchAsync([1, 2], item => "text")) + .ConfigureAwait(true); + } + + // What an application does to replace the client in its tests: nothing but the override runs. + private sealed class CannedClient : DaxFormatterClient + { + private readonly Func, IReadOnlyList> _format; + + public CannedClient(Func, IReadOnlyList> format) + { + _format = format; + } + + public override Task> FormatBatchAsync( + IEnumerable texts, + DaxFormatOptions? options = null, + IProgress? progress = null, + CancellationToken cancellationToken = default) + { + return Task.FromResult(_format(texts)); + } + } + + private sealed class CountingEnumerable : IEnumerable + { + private readonly string[] _texts; + + public CountingEnumerable(string[] texts) + { + _texts = texts; + } + + public int Enumerations { get; private set; } + + public IEnumerator GetEnumerator() + { + Enumerations++; + return ((IEnumerable)_texts).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs new file mode 100644 index 0000000..05b522a --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs @@ -0,0 +1,103 @@ +using System.Text.Json.Nodes; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// Imitates the answers of the service without formatting anything: each text comes back as it was sent, with +/// the line breaks, the header layout and the indentation that the service gives. A text that contains +/// comes back with a syntax error at the marker. +/// +internal static class EchoService +{ + public const string ErrorMarker = "+*"; + public const string ErrorMessage = "Syntax error, expected: ..."; + + private const string MeasureHeader = "[x] :=\n"; + private const string FunctionHeader = "FUNCTION x =\n"; + + public static string Answer(IReadOnlyList dax) + { + var results = new JsonArray(); + foreach (var text in dax) + { + results.Add(AnswerOne(text)); + } + + return results.ToJsonString(); + } + + private static JsonObject AnswerOne(string text) + { + var marker = text.IndexOf(ErrorMarker, StringComparison.Ordinal); + if (marker >= 0) + { + return new JsonObject + { + ["formatted"] = string.Empty, + ["errors"] = new JsonArray(CreateError(text, marker)), + }; + } + + return new JsonObject + { + ["formatted"] = Format(text), + ["errors"] = new JsonArray(), + }; + } + + private static JsonObject CreateError(string text, int position) + { + var before = text.Substring(0, position); + var lineStart = before.LastIndexOf('\n') + 1; + + return new JsonObject + { + ["line"] = before.Count(character => character == '\n'), + ["column"] = ToServiceColumn(before.Substring(lineStart)), + ["message"] = ErrorMessage, + }; + } + + // The service counts a tab up to the next multiple of 8 and gives a carriage return no width. + private static int ToServiceColumn(string lineBeforeTheError) + { + var column = 0; + foreach (var character in lineBeforeTheError) + { + if (character == '\t') + { + column = ((column / 8) + 1) * 8; + } + else if (character != '\r') + { + column++; + } + } + + return column; + } + + private static string Format(string text) + { + if (text.StartsWith(MeasureHeader, StringComparison.Ordinal)) + { + return "[x] :=\r\n" + ToServiceLines(text.Substring(MeasureHeader.Length), indentation: "") + "\r\n"; + } + + if (!text.StartsWith(FunctionHeader, StringComparison.Ordinal)) + { + return ToServiceLines(text, indentation: "") + "\r\n"; + } + + // The service puts the parameters on the line of the header, unless a comment comes first. + var body = ToServiceLines(text.Substring(FunctionHeader.Length), indentation: " "); + var startsWithParameters = body.Length > 0 && body[0] == '('; + return (startsWithParameters ? "FUNCTION x = " : "FUNCTION x =\r\n ") + body + "\r\n"; + } + + private static string ToServiceLines(string text, string indentation) + { + var lines = text.Split('\n').Select(line => line.TrimEnd('\r')); + return string.Join("\r\n" + indentation, lines); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/FakeFormatterHandler.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/FakeFormatterHandler.cs new file mode 100644 index 0000000..a9b6cbe --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/FakeFormatterHandler.cs @@ -0,0 +1,81 @@ +using System.Net.Http; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// Answers a request in place of the service. +/// +internal delegate Task Responder(RecordedRequest request, CancellationToken cancellationToken); + +/// +/// Stands in for the service: records each request it receives and answers with a . +/// +internal sealed class FakeFormatterHandler : HttpMessageHandler +{ + private readonly object _gate = new(); + private readonly List _requests = []; + private readonly Responder _responder; + private int _inFlight; + private int _maxInFlight; + + public FakeFormatterHandler(Responder responder) + { + _responder = responder; + } + + public IReadOnlyList Requests + { + get + { + lock (_gate) + { + return [.. _requests]; + } + } + } + + /// Gets the largest number of requests that were in progress at the same time. + public int MaxInFlight + { + get + { + lock (_gate) + { + return _maxInFlight; + } + } + } + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + // The body is read before anything else: the client disposes the request when the call ends. +#if NET + var body = await request.Content!.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); +#else + var body = await request.Content!.ReadAsByteArrayAsync().ConfigureAwait(false); +#endif + + RecordedRequest recorded; + lock (_gate) + { + recorded = new RecordedRequest(_requests.Count, request, body); + _requests.Add(recorded); + _inFlight++; + _maxInFlight = Math.Max(_maxInFlight, _inFlight); + } + + try + { + return await _responder(recorded, cancellationToken).ConfigureAwait(false); + } + finally + { + lock (_gate) + { + _inFlight--; + } + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/FormatterHarness.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/FormatterHarness.cs new file mode 100644 index 0000000..f435334 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/FormatterHarness.cs @@ -0,0 +1,46 @@ +using System.Net.Http; +using Dax.Formatter.Configuration; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// A client wired to a and a , with what a test +/// needs to look at afterwards. +/// +internal sealed class FormatterHarness : IDisposable +{ + public const string ApplicationName = "Test App"; + public const string ApplicationVersion = "1.2.3"; + + public FormatterHarness( + Responder responder, + Action? configure = null, + BatchLimits? limits = null) + { + var options = new DaxFormatterClientOptions + { + ApplicationName = ApplicationName, + ApplicationVersion = ApplicationVersion, + }; + configure?.Invoke(options); + + Handler = new FakeFormatterHandler(responder); + HttpClient = new HttpClient(Handler); + Delay = new RecordingDelay(); + Client = new DaxFormatterClient(HttpClient, options, Delay, limits ?? BatchLimits.Default); + } + + public FakeFormatterHandler Handler { get; } + + public HttpClient HttpClient { get; } + + public RecordingDelay Delay { get; } + + public DaxFormatterClient Client { get; } + + public void Dispose() + { + HttpClient.Dispose(); + Handler.Dispose(); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/ListProgress.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/ListProgress.cs new file mode 100644 index 0000000..b71557e --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/ListProgress.cs @@ -0,0 +1,28 @@ +namespace Dax.Formatter.Tests.Fakes; + +/// +/// Collects progress reports in the order they are made, on the thread that makes them. +/// +internal sealed class ListProgress : IProgress +{ + private readonly List _reports = []; + + public IReadOnlyList<(int Completed, int Total)> Reports + { + get + { + lock (_reports) + { + return [.. _reports.Select(report => (report.Completed, report.Total))]; + } + } + } + + public void Report(DaxFormatProgressInfo value) + { + lock (_reports) + { + _reports.Add(value); + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs new file mode 100644 index 0000000..3720b60 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs @@ -0,0 +1,49 @@ +using System.Net.Http; +using System.Text.Json; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// A request that received, copied when it arrived. +/// +internal sealed class RecordedRequest +{ + private readonly Dictionary _headers = new(StringComparer.OrdinalIgnoreCase); + + public RecordedRequest(int number, HttpRequestMessage request, byte[] body) + { + Number = number; + Method = request.Method; + Uri = request.RequestUri; + Body = body; + ContentType = request.Content?.Headers.ContentType?.ToString(); + + foreach (var header in request.Headers) + { + _headers[header.Key] = string.Join(" ", header.Value); + } + + using var document = JsonDocument.Parse(body); + Json = document.RootElement.Clone(); + } + + /// Gets the position of the request among those the handler received, from zero. + public int Number { get; } + + public HttpMethod Method { get; } + + public Uri? Uri { get; } + + public byte[] Body { get; } + + public string? ContentType { get; } + + public JsonElement Json { get; } + + public IReadOnlyList Dax => [.. Json.GetProperty("dax").EnumerateArray().Select(text => text.GetString()!)]; + + public string? GetHeader(string name) + { + return _headers.TryGetValue(name, out var value) ? value : null; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordingDelay.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordingDelay.cs new file mode 100644 index 0000000..f733271 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordingDelay.cs @@ -0,0 +1,39 @@ +using Dax.Formatter.Transport; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// Records the waits between attempts and does not wait, so that no test does. +/// +internal sealed class RecordingDelay : IDelay +{ + private readonly List _delays = []; + + public IReadOnlyList Delays + { + get + { + lock (_delays) + { + return [.. _delays]; + } + } + } + + /// Gets or sets what happens when a wait starts, such as a cancellation by the caller. + public Action? OnWait { get; set; } + + public Task WaitAsync(TimeSpan delay, CancellationToken cancellationToken) + { + lock (_delays) + { + _delays.Add(delay); + } + + OnWait?.Invoke(); + + return cancellationToken.IsCancellationRequested + ? Task.FromCanceled(cancellationToken) + : Task.CompletedTask; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs new file mode 100644 index 0000000..75b1470 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs @@ -0,0 +1,104 @@ +using System.Net; +using System.Net.Http; +using System.Text; + +namespace Dax.Formatter.Tests.Fakes; + +/// +/// The answers that a test can give in place of the service. +/// +internal static class Respond +{ + public const string ServiceRequestId = "fake-azure-ref"; + + /// Answers as does. + public static Responder Echo { get; } = (request, _) => Task.FromResult(CreateJson(EchoService.Answer(request.Dax))); + + /// Never answers: the request ends only when it is cancelled. + public static Responder Hang { get; } = async (_, cancellationToken) => + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("A request that hangs can only be cancelled."); + }; + + public static Responder Json(string json) + { + return (_, _) => Task.FromResult(CreateJson(json)); + } + + /// Answers with the JSON that a function builds from the texts of the request. + public static Responder Json(Func, string> answer) + { + return (request, _) => Task.FromResult(CreateJson(answer(request.Dax))); + } + + public static Responder Content(HttpStatusCode status, string content, string mediaType) + { + return (_, _) => + { + var response = Create(status); + response.Content = new StringContent(content, Encoding.UTF8, mediaType); + return Task.FromResult(response); + }; + } + + public static Responder Status(HttpStatusCode status, Action? configure = null) + { + return (_, _) => + { + var response = Create(status); + response.Content = new ByteArrayContent([]); + configure?.Invoke(response); + return Task.FromResult(response); + }; + } + + public static Responder Throw(Func createException) + { + return (_, _) => Task.FromException(createException()); + } + + /// Answers with once completes. + public static Responder After(Task gate, Responder then) + { + return async (request, cancellationToken) => + { + await gate.ConfigureAwait(false); + return await then(request, cancellationToken).ConfigureAwait(false); + }; + } + + /// Does something when a request arrives, such as a cancellation by the caller, then answers. + public static Responder OnArrival(Action action, Responder then) + { + return (request, cancellationToken) => + { + action(); + return then(request, cancellationToken); + }; + } + + /// Answers the first request with the first responder, and so on; the last one answers the rest. + public static Responder Sequence(params Responder[] responders) + { + return (request, cancellationToken) => + { + var responder = responders[Math.Min(request.Number, responders.Length - 1)]; + return responder(request, cancellationToken); + }; + } + + private static HttpResponseMessage CreateJson(string json) + { + var response = Create(HttpStatusCode.OK); + response.Content = new StringContent(json, Encoding.UTF8, "application/json"); + return response; + } + + private static HttpResponseMessage Create(HttpStatusCode status) + { + var response = new HttpResponseMessage(status); + response.Headers.Add("x-azure-ref", ServiceRequestId); + return response; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json new file mode 100644 index 0000000..573ddc5 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json @@ -0,0 +1,181 @@ +{ + "description": "Calls of a client with the JSON body of the request that it sends. The application is the name and the version that the client was given. Blank texts are not sent. Line breaks appear only as escapes.", + "cases": [ + { + "name": "default options", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": {}, + "texts": [ "EVALUATE Sales", "EVALUATE Customer" ], + "body": { + "dax": [ "EVALUATE Sales", "EVALUATE Customer" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "short lines", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "lineStyle": "shortLine" }, + "texts": [ "EVALUATE Sales" ], + "body": { + "dax": [ "EVALUATE Sales" ], + "maxLineLength": 1, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "no space after function names", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "spacingStyle": "noSpaceAfterFunction" }, + "texts": [ "EVALUATE Sales" ], + "body": { + "dax": [ "EVALUATE Sales" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": true, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "semicolon and comma as separators", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "separatorStyle": "semicolonAndComma" }, + "texts": [ "EVALUATE ROW(\"a\"; 1,5)" ], + "body": { + "dax": [ "EVALUATE ROW(\"a\"; 1,5)" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ";", + "decimalSeparator": ",", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "expressions under their headers", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "kind": "expression" }, + "texts": [ "SUM(Sales[Amount])", "(a, b) => a + b", "// c\r\n(a) => a", "(1 + 2) * 3" ], + "body": { + "dax": [ + "[x] :=\nSUM(Sales[Amount])", + "FUNCTION x =\n(a, b) => a + b", + "FUNCTION x =\n// c\r\n(a) => a", + "[x] :=\n(1 + 2) * 3" + ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "blank texts left out", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "kind": "expression" }, + "texts": [ "", "1 + 2", " \r\n\t" ], + "body": { + "dax": [ "[x] :=\n1 + 2" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "text with characters outside ASCII", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": {}, + "texts": [ "EVALUATE ROW(\"città\", \"😀 <&>\")" ], + "body": { + "dax": [ "EVALUATE ROW(\"città\", \"😀 <&>\")" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "every property of the model", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { + "modelInfo": { + "serverName": "MyServerName1", + "databaseName": "MyDatabaseName1", + "serverType": "SSAS", + "serverMode": "Tabular", + "serverEdition": "Enterprise64", + "serverLocation": "OnPremise", + "serverVersion": "16.0.143.21", + "compatibilityLevel": 1600 + } + }, + "texts": [ "EVALUATE Sales" ], + "body": { + "dax": [ "EVALUATE Sales" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "serverName": "f4139cb312e198bedebf0d71198c27db761f5c4cab73da7dd2faea2672d082af", + "databaseName": "6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863", + "serverType": "SSAS", + "serverMode": "Tabular", + "serverEdition": "Enterprise64", + "serverLocation": "OnPremise", + "serverVersion": "16.0.143.21", + "databaseCompatibilityLevel": "1600", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "empty names of the model", + "application": { "name": "Test App", "version": "1.2.3" }, + "options": { "modelInfo": { "serverName": "", "databaseName": "" } }, + "texts": [ "EVALUATE Sales" ], + "body": { + "dax": [ "EVALUATE Sales" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "serverName": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "databaseName": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "callerApp": "Test App", + "callerVersion": "1.2.3" + } + }, + { + "name": "application name with a space", + "application": { "name": "DAX Studio", "version": "3.0.11" }, + "options": {}, + "texts": [ "EVALUATE Sales" ], + "body": { + "dax": [ "EVALUATE Sales" ], + "maxLineLength": 0, + "skipSpaceAfterFunctionName": false, + "listSeparator": ",", + "decimalSeparator": ".", + "callerApp": "DAX Studio", + "callerVersion": "3.0.11" + } + } + ] +} diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt new file mode 100644 index 0000000..3e6a893 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt @@ -0,0 +1,91 @@ +sealed class Dax.Formatter.DaxFormatOptions + Dax.Formatter.DaxKind Kind { get; set; } + Dax.Formatter.DaxLineStyle LineStyle { get; set; } + Dax.Formatter.DaxModelInfo ModelInfo { get; set; } + Dax.Formatter.DaxSeparatorStyle SeparatorStyle { get; set; } + Dax.Formatter.DaxSpacingStyle SpacingStyle { get; set; } + constructor() +sealed class Dax.Formatter.DaxFormatProgressInfo + System.Int32 Completed { get; } + System.Int32 Total { get; } + constructor(System.Int32 completed, System.Int32 total) +class Dax.Formatter.DaxFormatResult + System.Boolean Succeeded { get; } + System.Collections.Generic.IReadOnlyList Errors { get; } + System.String FormattedText { get; } + System.String OriginalText { get; } + static Dax.Formatter.DaxFormatResult Failure(System.String originalText, System.Collections.Generic.IEnumerable errors) + static Dax.Formatter.DaxFormatResult Success(System.String originalText, System.String formattedText) +sealed class Dax.Formatter.DaxFormatResult : Dax.Formatter.DaxFormatResult + TItem Item { get; } + constructor(TItem item, Dax.Formatter.DaxFormatResult result) +class Dax.Formatter.DaxFormatterClient + System.Threading.Tasks.Task>> FormatBatchAsync(System.Collections.Generic.IEnumerable items, System.Func textSelector, Dax.Formatter.DaxFormatOptions options = default, System.IProgress progress = default, System.Threading.CancellationToken cancellationToken = default) + constructor() + constructor(Dax.Formatter.DaxFormatterClientOptions options) + constructor(System.Net.Http.HttpClient httpClient) + constructor(System.Net.Http.HttpClient httpClient, Dax.Formatter.DaxFormatterClientOptions options) + virtual System.Threading.Tasks.Task FormatAsync(System.String text, Dax.Formatter.DaxFormatOptions options = default, System.Threading.CancellationToken cancellationToken = default) + virtual System.Threading.Tasks.Task> FormatBatchAsync(System.Collections.Generic.IEnumerable texts, Dax.Formatter.DaxFormatOptions options = default, System.IProgress progress = default, System.Threading.CancellationToken cancellationToken = default) +sealed class Dax.Formatter.DaxFormatterClientOptions + System.Int32 MaxConcurrentRequests { get; set; } + System.Int32 MaxRetries { get; set; } + System.String ApplicationName { get; set; } + System.String ApplicationVersion { get; set; } + System.TimeSpan RequestTimeout { get; set; } + System.Uri Endpoint { get; set; } + constructor() +sealed class Dax.Formatter.DaxFormatterException : System.Exception + Dax.Formatter.DaxFormatterFailureReason Reason { get; } + System.Net.HttpStatusCode? StatusCode { get; } + System.String RequestId { get; } + System.String ServiceRequestId { get; } + constructor() + constructor(System.String message) + constructor(System.String message, Dax.Formatter.DaxFormatterFailureReason reason, System.Net.HttpStatusCode? statusCode, System.String requestId, System.String serviceRequestId, System.Exception innerException) + constructor(System.String message, System.Exception innerException) +enum Dax.Formatter.DaxFormatterFailureReason + HttpError = 3 + InvalidResponse = 4 + NetworkError = 2 + Timeout = 1 + Unknown = 0 +enum Dax.Formatter.DaxKind + Auto = 0 + Expression = 1 +enum Dax.Formatter.DaxLineStyle + LongLine = 0 + ShortLine = 1 +sealed class Dax.Formatter.DaxModelInfo + System.Int32? CompatibilityLevel { get; set; } + System.String DatabaseName { get; set; } + System.String ServerEdition { get; set; } + System.String ServerLocation { get; set; } + System.String ServerMode { get; set; } + System.String ServerName { get; set; } + System.String ServerType { get; set; } + System.String ServerVersion { get; set; } + constructor() +enum Dax.Formatter.DaxSeparatorStyle + CommaAndPoint = 0 + SemicolonAndComma = 1 +static class Dax.Formatter.DaxServerTypes + const System.String AnalysisServices = "SSAS" + const System.String AzureAnalysisServices = "AzureAS" + const System.String Offline = "Offline" + const System.String PowerBIDesktop = "PBI Desktop" + const System.String PowerBIReportServer = "PBI Report Server" + const System.String PowerBIService = "PBI Service" + const System.String PowerPivot = "PowerPivot" + const System.String Ssdt = "SSDT" +enum Dax.Formatter.DaxSpacingStyle + NoSpaceAfterFunction = 1 + SpaceAfterFunction = 0 +sealed class Dax.Formatter.DaxSyntaxError : System.IEquatable + System.Boolean Equals(Dax.Formatter.DaxSyntaxError other) + System.Int32 Column { get; } + System.Int32 Line { get; } + System.String Message { get; } + constructor(System.Int32 line, System.Int32 column, System.String message) + override System.Boolean Equals(System.Object obj) + override System.Int32 GetHashCode() diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApiTests.cs b/dotnet/tests/Dax.Formatter.Tests/PublicApiTests.cs new file mode 100644 index 0000000..0d42d31 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApiTests.cs @@ -0,0 +1,156 @@ +using System.Reflection; +using System.Text; +using Dax.Formatter.Tests.Fixtures; +using Xunit; + +namespace Dax.Formatter.Tests; + +/// +/// Compares the public surface of the library with PublicApi.approved.txt, on each target framework: a +/// change of the surface is a decision, so it must show up as a change of that file. +/// +public class PublicApiTests +{ + private const BindingFlags Declared = + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; + + private static readonly Assembly s_library = typeof(DaxFormatterClient).Assembly; + + [Fact] + public void PublicSurface_OfTheLibrary_IsTheApprovedOne() + { + var approved = FixtureFile.ReadText("PublicApi.approved.txt"); + + var actual = Describe(s_library.GetExportedTypes()); + + Assert.Equal(approved, actual); + } + + [Fact] + public void PublicTypes_OfTheLibrary_AreAllInItsRootNamespace() + { + var namespaces = s_library.GetExportedTypes().Select(type => type.Namespace).Distinct(); + + Assert.Equal(["Dax.Formatter"], namespaces); + } + + private static string Describe(IEnumerable types) + { + var text = new StringBuilder(); + foreach (var type in types.OrderBy(type => type.FullName, StringComparer.Ordinal)) + { + text.Append(DescribeType(type)).Append('\n'); + foreach (var member in DescribeMembers(type).OrderBy(member => member, StringComparer.Ordinal)) + { + text.Append(" ").Append(member).Append('\n'); + } + } + + return text.ToString().TrimEnd(); + } + + private static string DescribeType(Type type) + { + if (type.IsEnum) + { + return "enum " + Name(type); + } + + var modifiers = type.IsAbstract && type.IsSealed ? "static " : type.IsSealed ? "sealed " : string.Empty; + var bases = new List(); + if (type.BaseType is not null && type.BaseType != typeof(object)) + { + bases.Add(Name(type.BaseType)); + } + + // Only the interfaces that the type adds: those of a framework base type differ between frameworks. + var inherited = type.BaseType?.GetInterfaces() ?? []; + bases.AddRange(type.GetInterfaces().Except(inherited).Select(Name).OrderBy(name => name, StringComparer.Ordinal)); + return modifiers + "class " + Name(type) + (bases.Count == 0 ? string.Empty : " : " + string.Join(", ", bases)); + } + + private static IEnumerable DescribeMembers(Type type) + { + if (type.IsEnum) + { + return Enum.GetNames(type).Select(name => name + " = " + Convert.ToInt32(Enum.Parse(type, name), null)); + } + + var constructors = type.GetConstructors(Declared).Where(IsVisible).Select( + constructor => Access(constructor) + "constructor(" + Parameters(constructor) + ")"); + var methods = type.GetMethods(Declared).Where(method => IsVisible(method) && !method.IsSpecialName).Select( + method => Access(method) + Name(method.ReturnType) + " " + method.Name + GenericArguments(method) + + "(" + Parameters(method) + ")"); + var properties = type.GetProperties(Declared).Where(property => Accessors(property).Length > 0).Select( + property => Access(property.GetMethod ?? property.SetMethod!) + Name(property.PropertyType) + " " + + property.Name + " { " + Accessors(property) + "}"); + var fields = type.GetFields(Declared).Where(field => field.IsPublic || field.IsFamily).Select( + field => (field.IsLiteral ? "const " : string.Empty) + Name(field.FieldType) + " " + field.Name + + (field.IsLiteral ? " = \"" + field.GetRawConstantValue() + "\"" : string.Empty)); + + return constructors.Concat(methods).Concat(properties).Concat(fields); + } + + private static bool IsVisible(MethodBase method) + { + return method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly; + } + + private static string Access(MethodBase method) + { + var access = method.IsPublic ? string.Empty : "protected "; + if (method.IsStatic) + { + return access + "static "; + } + + var isOverride = method is MethodInfo info && info.GetBaseDefinition().DeclaringType != info.DeclaringType; + if (isOverride) + { + return access + "override "; + } + + return access + (method.IsVirtual && !method.IsFinal ? "virtual " : string.Empty); + } + + private static string Accessors(PropertyInfo property) + { + var getter = property.GetMethod is not null && IsVisible(property.GetMethod) ? "get; " : string.Empty; + var setter = property.SetMethod is not null && IsVisible(property.SetMethod) ? "set; " : string.Empty; + return getter + setter; + } + + private static string Parameters(MethodBase method) + { + return string.Join(", ", method.GetParameters().Select( + parameter => Name(parameter.ParameterType) + " " + parameter.Name + (parameter.IsOptional ? " = default" : string.Empty))); + } + + private static string GenericArguments(MethodInfo method) + { + return method.IsGenericMethodDefinition + ? "<" + string.Join(", ", method.GetGenericArguments().Select(Name)) + ">" + : string.Empty; + } + + private static string Name(Type type) + { + if (type.IsGenericParameter) + { + return type.Name; + } + + if (Nullable.GetUnderlyingType(type) is Type underlying) + { + return Name(underlying) + "?"; + } + + if (!type.IsGenericType) + { + return type.Namespace + "." + type.Name; + } + + var name = type.Name.Split('`')[0]; + return type.Namespace + "." + name + "<" + string.Join(", ", type.GetGenericArguments().Select(Name)) + ">"; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApiUsageTests.cs b/dotnet/tests/Dax.Formatter.Tests/PublicApiUsageTests.cs new file mode 100644 index 0000000..b60a54f --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApiUsageTests.cs @@ -0,0 +1,90 @@ +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests; + +/// +/// Calls the client the way applications do. The declared types of the results pin which overload each call +/// binds to: a change that moves a call to another overload stops this file from compiling. +/// +public class PublicApiUsageTests +{ + private static readonly string[] s_texts = ["EVALUATE Sales", "EVALUATE Customer"]; + + [Fact] + public async Task FormatBatchAsync_StringArray_BindsToTheOverloadForTexts() + { + using var harness = new FormatterHarness(Respond.Echo); + string[] texts = s_texts; + + IReadOnlyList results = await harness.Client.FormatBatchAsync(texts).ConfigureAwait(true); + + Assert.Equal(2, results.Count); + } + + [Fact] + public async Task FormatBatchAsync_ListOfStrings_BindsToTheOverloadForTexts() + { + using var harness = new FormatterHarness(Respond.Echo); + List texts = [.. s_texts]; + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + IReadOnlyList results = await harness.Client + .FormatBatchAsync(texts, options, cancellationToken: CancellationToken.None) + .ConfigureAwait(true); + + Assert.Equal(2, results.Count); + } + + [Fact] + public async Task FormatBatchAsync_TextsWithNamedOptionalArguments_BindsToTheOverloadForTexts() + { + using var harness = new FormatterHarness(Respond.Echo); + var progress = new ListProgress(); + + IReadOnlyList results = await harness.Client + .FormatBatchAsync(s_texts, options: null, progress: progress) + .ConfigureAwait(true); + + Assert.Equal(2, results.Count); + } + + [Fact] + public async Task FormatBatchAsync_ItemsAndSelector_BindsToTheOverloadForItems() + { + using var harness = new FormatterHarness(Respond.Echo); + List items = [new Uri("https://example.test/a"), new Uri("https://example.test/b")]; + + IReadOnlyList> results = await harness.Client + .FormatBatchAsync(items, item => "EVALUATE " + item.Segments[1]) + .ConfigureAwait(true); + + Assert.Equal(items, results.Select(result => result.Item)); + } + + [Fact] + public async Task FormatBatchAsync_StringsAndSelector_BindsToTheOverloadForItems() + { + using var harness = new FormatterHarness(Respond.Echo); + string[] tableNames = ["Sales", "Customer"]; + var options = new DaxFormatOptions { LineStyle = DaxLineStyle.ShortLine }; + + IReadOnlyList> results = await harness.Client + .FormatBatchAsync(tableNames, tableName => "EVALUATE " + tableName, options) + .ConfigureAwait(true); + + Assert.Equal(tableNames, results.Select(result => result.Item)); + } + + [Fact] + public async Task FormatAsync_ResultThatSucceeded_HasAFormattedTextThatIsNotNull() + { + using var harness = new FormatterHarness(Respond.Echo); + + DaxFormatResult result = await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + // No null check and no "!" below: the compiler knows that the text is there when Succeeded is true. + var length = result.Succeeded ? result.FormattedText.Length : -1; + Assert.Equal(14, length); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs new file mode 100644 index 0000000..a06bc2e --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs @@ -0,0 +1,120 @@ +using System.Net.Http; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class FormatterTransportTests +{ + [Fact] + public async Task FormatAsync_AnyCall_PostsToTheFormatEndpoint() + { + using var harness = new FormatterHarness(Respond.Echo); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.Equal(HttpMethod.Post, request.Method); + Assert.Equal(new Uri("https://api.daxformatter.com/api/daxtextformatmulti"), request.Uri); + } + + [Fact] + public async Task FormatAsync_HttpClientWithBaseAddress_IgnoresIt() + { + using var harness = new FormatterHarness( + Respond.Echo, + options => options.Endpoint = new Uri("https://staging.example.test/dax")); + harness.HttpClient.BaseAddress = new Uri("https://other.example.test/"); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.Equal(new Uri("https://staging.example.test/dax/api/daxtextformatmulti"), request.Uri); + } + + [Fact] + public async Task FormatAsync_AnyCall_IdentifiesTheCallerAndTheRequest() + { + using var harness = new FormatterHarness(Respond.Echo); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.StartsWith("Test-App/1.2.3 Dax.Formatter/", request.GetHeader("User-Agent"), StringComparison.Ordinal); + Assert.True(Guid.TryParse(request.GetHeader("DaxFormatter-Request-Id"), out _)); + Assert.True(Guid.TryParse(request.GetHeader("DaxFormatter-Operation-Id"), out _)); + } + + [Fact] + public async Task FormatAsync_AnyCall_AsksForJsonWithoutCompressionOrExpect() + { + using var harness = new FormatterHarness(Respond.Echo); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.Equal("application/json", request.GetHeader("Accept")); + Assert.Null(request.GetHeader("Accept-Encoding")); + Assert.Null(request.GetHeader("Expect")); + } + + [Fact] + public async Task FormatAsync_HttpClientOfTheCaller_LeavesItUnchanged() + { + using var harness = new FormatterHarness(Respond.Echo); + var timeout = harness.HttpClient.Timeout; + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + Assert.Empty(harness.HttpClient.DefaultRequestHeaders); + Assert.Equal(timeout, harness.HttpClient.Timeout); + } + + [Fact] + public async Task FormatAsync_NoAnswerWithinTheRequestTimeout_FailsWithTimeout() + { + using var harness = new FormatterHarness(Respond.Hang, options => + { + options.RequestTimeout = TimeSpan.FromMilliseconds(50); + options.MaxRetries = 0; + }); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.Timeout, exception.Reason); + Assert.Equal(harness.Handler.Requests[0].GetHeader("DaxFormatter-Request-Id"), exception.RequestId); + Assert.Equal((null, null), (exception.StatusCode, exception.ServiceRequestId)); + } + + [Fact] + public async Task FormatAsync_TimeoutOfTheHttpClientOfTheCaller_FailsWithTimeout() + { + using var harness = new FormatterHarness( + Respond.Throw(() => new TaskCanceledException("The request was canceled due to HttpClient.Timeout.")), + options => options.MaxRetries = 0); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.Timeout, exception.Reason); + } + + [Fact] + public async Task FormatAsync_RequestThatDoesNotReachTheService_FailsWithNetworkError() + { + using var harness = new FormatterHarness( + Respond.Throw(() => new HttpRequestException("No such host is known.")), + options => options.MaxRetries = 0); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.NetworkError, exception.Reason); + Assert.IsType(exception.InnerException); + Assert.Contains("No such host is known.", exception.Message, StringComparison.Ordinal); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/RetryingSenderTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryingSenderTests.cs new file mode 100644 index 0000000..143c8d7 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryingSenderTests.cs @@ -0,0 +1,150 @@ +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests.Transport; + +public class RetryingSenderTests +{ + private static readonly Responder s_busy = Respond.Status(HttpStatusCode.ServiceUnavailable); + + [Fact] + public async Task FormatAsync_TransientFailureThenSuccess_ReturnsTheResult() + { + using var harness = new FormatterHarness(Respond.Sequence(s_busy, Respond.Echo)); + + var result = await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + Assert.True(result.Succeeded); + Assert.Equal(2, harness.Handler.Requests.Count); + Assert.Single(harness.Delay.Delays); + } + + [Fact] + public async Task FormatAsync_SecondAttempt_SendsTheSameBodyAndRequestId() + { + using var harness = new FormatterHarness(Respond.Sequence(s_busy, Respond.Echo)); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + var first = harness.Handler.Requests[0]; + var second = harness.Handler.Requests[1]; + Assert.Equal(first.Body, second.Body); + Assert.Equal(first.GetHeader("DaxFormatter-Request-Id"), second.GetHeader("DaxFormatter-Request-Id")); + } + + [Fact] + public async Task FormatAsync_NetworkErrorThenSuccess_ReturnsTheResult() + { + var unreachable = Respond.Throw(() => new HttpRequestException("Connection reset.")); + using var harness = new FormatterHarness(Respond.Sequence(unreachable, Respond.Echo)); + + var result = await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + Assert.True(result.Succeeded); + Assert.Equal(2, harness.Handler.Requests.Count); + } + + [Fact] + public async Task FormatAsync_TransientFailureEveryTime_FailsAfterTheRetries() + { + using var harness = new FormatterHarness(s_busy, options => options.MaxRetries = 2); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Equal(3, harness.Handler.Requests.Count); + Assert.Equal(2, harness.Delay.Delays.Count); + Assert.Contains("503", exception.Message, StringComparison.Ordinal); + Assert.Contains("after 3 attempts", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task FormatAsync_NoRetriesAllowed_FailsAtTheFirstFailure() + { + using var harness = new FormatterHarness(s_busy, options => options.MaxRetries = 0); + + await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Single(harness.Handler.Requests); + Assert.Empty(harness.Delay.Delays); + } + + [Fact] + public async Task FormatAsync_StatusThatIsNotTransient_FailsAtOnceWithItsDetails() + { + using var harness = new FormatterHarness(Respond.Status(HttpStatusCode.BadRequest)); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Single(harness.Handler.Requests); + Assert.Equal(DaxFormatterFailureReason.HttpError, exception.Reason); + Assert.Equal((HttpStatusCode.BadRequest, Respond.ServiceRequestId), (exception.StatusCode, exception.ServiceRequestId)); + } + + [Fact] + public async Task FormatAsync_InvalidResponse_FailsAtOnce() + { + var html = Respond.Content(HttpStatusCode.OK, "Sign in", "text/html"); + using var harness = new FormatterHarness(html); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Single(harness.Handler.Requests); + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, exception.Reason); + } + + [Fact] + public async Task FormatAsync_RetryAfter_WaitsAsLongAsTheServiceAsks() + { + var throttled = Respond.Status( + (HttpStatusCode)429, + response => response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(20))); + using var harness = new FormatterHarness(Respond.Sequence(throttled, Respond.Echo)); + + await harness.Client.FormatAsync("EVALUATE Sales").ConfigureAwait(true); + + Assert.Equal(TimeSpan.FromSeconds(20), Assert.Single(harness.Delay.Delays)); + } + + [Fact] + public async Task FormatAsync_RetryAfterLongerThanTheRequestTimeout_FailsAtOnce() + { + var throttled = Respond.Status( + (HttpStatusCode)429, + response => response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(120))); + using var harness = new FormatterHarness(throttled); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Single(harness.Handler.Requests); + Assert.Equal((HttpStatusCode)429, exception.StatusCode); + } + + [Fact] + public async Task FormatAsync_CancellationDuringTheWait_ThrowsOperationCanceled() + { + using var cancellation = new CancellationTokenSource(); + using var harness = new FormatterHarness(s_busy); + harness.Delay.OnWait = cancellation.Cancel; + + var exception = await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatAsync("EVALUATE Sales", cancellationToken: cancellation.Token)) + .ConfigureAwait(true); + + Assert.Equal(cancellation.Token, exception.CancellationToken); + Assert.Single(harness.Handler.Requests); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Wire/RequestBodyWriterTests.cs b/dotnet/tests/Dax.Formatter.Tests/Wire/RequestBodyWriterTests.cs new file mode 100644 index 0000000..fdc3ae8 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Wire/RequestBodyWriterTests.cs @@ -0,0 +1,48 @@ +using System.Text.Json; +using Dax.Formatter.Tests.Fakes; +using Dax.Formatter.Tests.Fixtures; +using Xunit; + +namespace Dax.Formatter.Tests.Wire; + +public class RequestBodyWriterTests +{ + private const string Fixture = "request-bodies.json"; + + public static IEnumerable Cases => FixtureFile.CaseNames(Fixture); + + [Theory] + [MemberData(nameof(Cases))] + public async Task FormatBatchAsync_FixtureCall_SendsTheExpectedBody(string name) + { + var testCase = FixtureFile.Case(Fixture, name); + var application = testCase.GetProperty("application"); + var texts = testCase.GetProperty("texts").EnumerateArray().Select(text => text.GetString()!); + using var harness = new FormatterHarness(Respond.Echo, options => + { + options.ApplicationName = application.GetProperty("name").GetString(); + options.ApplicationVersion = application.GetProperty("version").GetString(); + }); + + await harness.Client + .FormatBatchAsync(texts, FixtureOptions.Read(testCase.GetProperty("options"))) + .ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.True( + JsonElement.DeepEquals(testCase.GetProperty("body"), request.Json), + $"The body sent is {request.Json.GetRawText()}"); + } + + [Fact] + public async Task FormatBatchAsync_AnyCall_SendsJsonAsUtf8() + { + using var harness = new FormatterHarness(Respond.Echo); + + await harness.Client.FormatAsync("EVALUATE ROW(\"città\", 1)").ConfigureAwait(true); + + var request = Assert.Single(harness.Handler.Requests); + Assert.Equal("application/json; charset=utf-8", request.ContentType); + Assert.Equal("EVALUATE ROW(\"città\", 1)", Assert.Single(request.Dax)); + } +} From ae760d9872c2c9f2f3b03768da516ca7d28422c0 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:16 +0100 Subject: [PATCH 09/29] docs(dotnet): rewrite the package readme for 2.0 - follow the sections of the NuGet readme guidance: getting started, usage with one snippet for each operation, migration from 1.x, limits of the service, further documentation and feedback - keep every C# block equal to a region of a compiled test file, whose tests run the code against a fake of the service --- dotnet/README.md | 275 +++++++++++++----- .../Dax.Formatter.Tests.csproj | 2 + .../Readme/ReadmeClient.cs | 26 ++ .../Readme/ReadmeSamples.cs | 240 +++++++++++++++ .../Readme/ReadmeService.cs | 58 ++++ .../Dax.Formatter.Tests/Readme/ReadmeTests.cs | 61 ++++ 6 files changed, 594 insertions(+), 68 deletions(-) create mode 100644 dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeClient.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeTests.cs diff --git a/dotnet/README.md b/dotnet/README.md index 82120b7..1cc1dfb 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -1,87 +1,226 @@ +# Dax.Formatter [![CI](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml/badge.svg)](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml) -# Dax Formatter [![CI](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml/badge.svg)](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml) +`Dax.Formatter` is the .NET client of [DAX Formatter](https://www.daxformatter.com), the service by SQLBI that formats DAX code following the [rules for DAX code formatting](https://www.sqlbi.com/articles/rules-for-dax-code-formatting/) and reports its syntax errors. One call formats one text or the thousands of measures of a model. -DAX Formatter is a service available at https://www.daxformatter.com. -The service receives DAX expressions and format them according to rules for [DAX code formatting](https://www.sqlbi.com/articles/rules-for-dax-code-formatting/). -The NuGet package contains a client library to invoke the service from your .NET application. -All the requests are designed to be asynchronous. -You should minimize the requests made to the service: to format multiple expressions, use a single API call providing the `DaxFormatterMultipleRequest` structure. +## Getting started -# Quick guide -Create an instance of `DaxFormatterClient`. -Invoke the `FormatAsync` method for each request. -Possibly, use the `DaxFormatterMultipleRequest` structure to provide more statistical details about the database and the server (all the names are anonymized and used only to count the number of unique servers/databases serviced). +Install the package, which targets .NET Standard 2.0 and .NET 10: + +```bash +dotnet add package Dax.Formatter +``` + +Create a client and format a query. The types are in the `Dax.Formatter` namespace. -# DaxFormatterClient -The default constructor creates an instance of the client using the current assembly name and version to identify the client. You can specify an application name and version in the constructor arguments. -Each instance creates one `HttpClient` and reuses it for every request. -It is suggested to reuse the same instance in multiple requests to minimize the latency. ```csharp -var formatter = new DaxFormatterClient(); -var response = await formatter.FormatAsync( "evaluate('Table') order by 'Table'[Column]" ); +var client = new DaxFormatterClient(); + +DaxFormatResult result = await client.FormatAsync("EVALUATE FILTER(Customer, Customer[Country] = \"Italy\")"); + +Console.WriteLine(result.FormattedText); +// EVALUATE +// FILTER ( Customer, Customer[Country] = "Italy" ) ``` -# DaxFormatterMultipleRequest -Use the `DaxFormatterMultipleRequest` class to send multiple DAX expressions in a single API call. + +- The client is thread-safe: create one and reuse it for the life of the application. +- The DAX text goes to the service, which formats it. Nothing else about the model leaves the machine, unless you fill `DaxModelInfo`, whose server and database names are sent only as hashes. +- Every method is asynchronous and takes a `CancellationToken`. + +## Usage + +### Format the objects of a model + +Pass your own objects and a function that returns the DAX of each one. Every result carries its object in `Item`, so nothing has to be matched by position. + ```csharp -var formatter = new DaxFormatterClient(); -var request = new DaxFormatterMultipleRequest +var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + +IReadOnlyList> results = + await client.FormatBatchAsync(model.Measures, measure => measure.Expression, options); + +foreach (var result in results) { - DatabaseName = "MyDatabaseName", // The name will be anonymized by the client library - ServerName = "MyServerName", // The name will be anonymized by the client library - - // Format arguments (you can skip all of them to keep the default values) - ListSeparator = ',', - DecimalSeparator = '.', - MaxLineLength = DaxFormatterLineStyle.LongLine, - SkipSpaceAfterFunctionName = DaxFormatterSpacingStyle.BestPractice, - - // Identify the server type using the corresponding enum values - ServerMode = Dax.Formatter.AnalysisServices.ServerMode.Tabular, - ServerType = Dax.Formatter.AnalysisServices.ServerType.AnalysisServices, - ServerEdition = Dax.Formatter.AnalysisServices.ServerEdition.Enterprise, - ServerLocation = Dax.Formatter.AnalysisServices.ServerLocation.OnPremise, + if (result.Succeeded) + { + result.Item.Expression = result.FormattedText; + } + else + { + Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); + } +} +``` + +Here `Measure` and `model` stand for the types of your application: any type works. + +- `DaxKind.Expression` says that each text is the DAX of one model object without its name: a measure, a calculated column, a calculated table, a calculation item or the body of a user-defined function. The formatted text has no name either. +- `DaxKind.Auto`, the default, sends the text as it is. Use it for a query and for a text that carries its own name, such as `[Margin] := [Sales] - [Cost]`. Don't use it for the DAX of a model object: without a name, the service can take an expression such as `Customer[Name] = "A"` for a definition named `Customer[Name]`. +- The client splits a large call into several requests and sends a few of them at a time. The results come back in the order of the input, all of them or an exception. +- A blank text gets an empty formatted text, without a request. +- `FormatBatchAsync` also takes plain strings: `await client.FormatBatchAsync(texts)`. + +### Options + +```csharp +var options = new DaxFormatOptions +{ + Kind = DaxKind.Expression, + LineStyle = DaxLineStyle.ShortLine, + SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, + SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, + ModelInfo = new DaxModelInfo + { + ServerType = DaxServerTypes.PowerBIDesktop, + DatabaseName = "Contoso", + }, }; -// Add the code to format -request.Dax.Add( "evaluate('Table') order by 'Table'[Column]" ); -request.Dax.Add( "[X]:=CALCULATE([Amt],USERELATIONSHIP(Sales[DueDateKey],'Date'[DateKey]))" ); +DaxFormatResult result = await client.FormatAsync("DIVIDE([Sales Amount]; 1,5)", options); +``` + +- `LineStyle`: `LongLine` (default) keeps an expression on one line while it fits, `ShortLine` puts each argument on its own line. +- `SpacingStyle`: `SpaceAfterFunction` (default) writes `SUM ( x )`, `NoSpaceAfterFunction` writes `SUM( x )`. +- `SeparatorStyle`: the separators that your DAX uses. `CommaAndPoint` (default) is `DIVIDE ( 1.5, 2 )`, `SemicolonAndComma` is `DIVIDE ( 1,5; 2 )`. +- `ModelInfo` is optional and doesn't change the formatting: the service uses it for anonymous usage statistics. `ServerName` and `DatabaseName` are sent as SHA-256 hashes, never as names. + +### Syntax errors + +A syntax error is not an exception: it is the result of that text. + +```csharp +DaxFormatResult result = await client.FormatAsync("SUMX(Sales, Sales[Amount] *", options); + +if (!result.Succeeded) +{ + foreach (DaxSyntaxError error in result.Errors) + { + Console.WriteLine($"Line {error.Line + 1}, column {error.Column + 1}: {error.Message}"); + } +} +``` + +- `Succeeded` is `false`, `FormattedText` is `null`, and `Errors` has at least one error. +- `Line` and `Column` are zero-based and refer to `OriginalText`, the text you passed: lines are separated by `\n`, and `Column` is an index into the UTF-16 characters of the line, so a tab counts as one. An error at the end of the text has the length of the last line as its column. + +### Functions + +With `DaxKind.Expression`, the body of a [user-defined function](https://learn.microsoft.com/dax/best-practices/dax-user-defined-functions) is formatted like any other expression. The client recognizes it by its parameter list followed by `=>`. + +```csharp +var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + +DaxFormatResult result = await client.FormatAsync( + "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)", options); + +Console.WriteLine(result.FormattedText); +// ( +// amount : NUMERIC, +// rate : NUMERIC +// ) => +// amount * ( 1 + rate ) +``` + +### Progress and cancellation + +```csharp +var progress = new Progress( + info => Console.WriteLine($"{info.Completed} of {info.Total} expressions formatted")); + +IReadOnlyList results = + await client.FormatBatchAsync(expressions, options, progress, cancellationToken); +``` + +`Completed` counts texts, grows as the requests of the call complete, and never decreases. A cancelled call throws `OperationCanceledException`. -// Send the request and wait the result -var responses = await formatter.FormatAsync(request); +### Failures of the service -// Process the result -foreach (var response in responses) +When the service or the network fails, the call throws `DaxFormatterException` and returns no result. + +```csharp +try { - Console.WriteLine(response.Formatted); + IReadOnlyList results = await client.FormatBatchAsync(expressions); + Console.WriteLine($"{results.Count} expressions formatted"); +} +catch (DaxFormatterException exception) +{ + Console.WriteLine($"{exception.Reason}: {exception.Message}"); + Console.WriteLine($"Request {exception.RequestId}, status {exception.StatusCode}"); } ``` -# DaxFormatterSingleRequest -Use the `DaxFormatterSingleRequest` class to send one DAX expressions in a single API call. + +- `Reason` is `Timeout`, `NetworkError`, `HttpError` or `InvalidResponse`. The message names the texts of the failed request by their indexes. +- Before it gives up, the client tries again after a timeout, a network error and the statuses 408, 429, 500, 502, 503 and 504, with a growing wait, and it honors `Retry-After`. +- `RequestId` is the identifier that the client sent in the `DaxFormatter-Request-Id` header; `ServiceRequestId` is the one in the answer, when an answer arrived. Quote both when you report a problem. + +### Client options and HttpClient + ```csharp -var formatter = new DaxFormatterClient(); -var request = new DaxFormatterSingleRequest +var client = new DaxFormatterClient(new DaxFormatterClientOptions { - Dax = "evaluate('Table') order by 'Table'[Column]", - - DatabaseName = "MyDatabaseName", // The name will be anonymized by the client library - ServerName = "MyServerName", // The name will be anonymized by the client library - - // Format arguments (you can skip all of them to keep the default values) - ListSeparator = ',', - DecimalSeparator = '.', - MaxLineLength = DaxFormatterLineStyle.LongLine, - SkipSpaceAfterFunctionName = DaxFormatterSpacingStyle.BestPractice, - - // Identify the server type using the corresponding enum values - ServerMode = Dax.Formatter.AnalysisServices.ServerMode.Tabular, - ServerType = Dax.Formatter.AnalysisServices.ServerType.AnalysisServices, - ServerEdition = Dax.Formatter.AnalysisServices.ServerEdition.Enterprise, - ServerLocation = Dax.Formatter.AnalysisServices.ServerLocation.OnPremise, -}; - -// Send the request and wait the result -var response = await formatter.FormatAsync(request); + ApplicationName = "Contoso Model Tools", + ApplicationVersion = "1.4.0", + RequestTimeout = TimeSpan.FromSeconds(120), + MaxRetries = 3, + MaxConcurrentRequests = 4, +}); +``` -// Display the result -Console.WriteLine(response.Formatted); +- `ApplicationName` and `ApplicationVersion` tell the service which application calls it, for usage statistics. They default to the name and the file version of the entry assembly. +- `RequestTimeout` (60 seconds) is the wait for the answer to one request; `MaxRetries` (2) is how many times a request is sent again; `MaxConcurrentRequests` (2) is how many requests of one call are in progress at the same time. + +Without an `HttpClient`, all the clients share one that lives as long as the process and doesn't check certificate revocation. To control the handler, the proxy or the certificate checks, pass your own: + +```csharp +var client = new DaxFormatterClient(httpClient); ``` + +The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register the client as a typed client: `services.AddHttpClient()`. + +To replace the client in the tests of your application, derive from it and override `FormatAsync` and the `FormatBatchAsync` that takes strings: both are virtual, the one that takes items calls the one that takes strings, and the parameterless constructor does no work. `DaxFormatResult.Success` and `DaxFormatResult.Failure` create the results. + +## Migrating from 1.x + +Version 2.0 replaces the whole API. The requests that 1.x exposed are gone: a call takes the text and the options, and returns results. + +| 1.x | 2.0 | +|---|---| +| `new DaxFormatterClient(application, version)` | `new DaxFormatterClient(new DaxFormatterClientOptions { ApplicationName = ..., ApplicationVersion = ... })` | +| `FormatAsync(string)`, `FormatAsync(DaxFormatterSingleRequest)` | `FormatAsync(text, options)` | +| `FormatAsync(IEnumerable)`, `FormatAsync(DaxFormatterMultipleRequest)` | `FormatBatchAsync(texts, options)`, or `FormatBatchAsync(items, textSelector, options)` | +| `[x] :=` written before an expression, and removed from the result | `DaxFormatOptions.Kind = DaxKind.Expression` | +| `MaxLineLength`, `SkipSpaceAfterFunctionName` | `DaxFormatOptions.LineStyle`, `DaxFormatOptions.SpacingStyle` | +| `ListSeparator`, `DecimalSeparator` | `DaxFormatOptions.SeparatorStyle` | +| `ServerName`, `DatabaseName`, `ServerVersion`, `DatabaseCompatibilityLevel` on the request | `DaxFormatOptions.ModelInfo`, where the compatibility level is a number | +| The enums `ServerType`, `ServerMode`, `ServerEdition`, `ServerLocation` | Strings; `DaxServerTypes` has the server types | +| `DaxFormatterResponse.Formatted`, empty when there are errors | `DaxFormatResult.FormattedText`, `null` when `Succeeded` is `false` | +| `DaxFormatterError` with nullable `Line` and `Column` | `DaxSyntaxError` | +| `HttpRequestException`, `TaskCanceledException` after 60 seconds | `DaxFormatterException` with a `Reason` | +| `IDaxFormatterClient` | Derive from `DaxFormatterClient`, whose methods are virtual | +| `Dispose()` | Nothing: the client is not disposable | + +What else changes: + +- The formatted text has no final line break. +- For `DaxKind.Expression`, the position of an error refers to your text, not to the text with `[x] :=` before it. +- A call with many texts no longer fails for its size: the client splits it. +- 2.0 formats DAX only. In 1.x, `FormatAsync(string)` and `FormatAsync(DaxFormatterSingleRequest)` also formatted MDX. +- The package no longer has a `net8.0` target: applications on .NET 8 and 9 use the .NET Standard 2.0 one. + +## Service limits + +The service, not the client, rejects these texts with a syntax error: + +- a function without parameters, such as `() => 1`; +- a function parameter with a default value, such as `(a, b = 1) => a + b`; +- with `DaxKind.Expression`, an expression that has `=>` inside a string or a comment. + +## Additional documentation + +- [SQLBI Docs](https://docs.sqlbi.com/dax-formatter/): the user documentation of DAX Formatter. +- [Client API](https://github.com/sql-bi/DaxFormatter/blob/master/docs/design/client-api.md): the behavior of the client in detail. +- [REST API](https://github.com/sql-bi/DaxFormatter/blob/master/docs/design/rest-api.md): the contract of the service that the client calls. + +## Feedback + +Report bugs and request features in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues). Report security vulnerabilities privately, as the [security policy](https://github.com/sql-bi/DaxFormatter/blob/master/SECURITY.md) explains. diff --git a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj index a65f9ad..e070777 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -30,6 +30,8 @@ + + diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeClient.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeClient.cs new file mode 100644 index 0000000..c0b0498 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeClient.cs @@ -0,0 +1,26 @@ +using System.Net.Http; + +namespace Dax.Formatter.Tests.Readme; + +/// +/// The client that the samples of the readme create. It has the public constructors and members of +/// , and sends its requests to unless it is given +/// an : the samples run as they are written, without the live service. +/// +internal sealed class ReadmeClient : DaxFormatterClient +{ + public ReadmeClient() + : base(ReadmeService.HttpClient) + { + } + + public ReadmeClient(DaxFormatterClientOptions options) + : base(ReadmeService.HttpClient, options) + { + } + + public ReadmeClient(HttpClient httpClient) + : base(httpClient) + { + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs new file mode 100644 index 0000000..cf9adc4 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -0,0 +1,240 @@ +using System.Net; +using System.Net.Http; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests.Readme; + +// In this file the name of the client means a client that answers from a fake service: see ReadmeClient. +// The alias must stay inside the namespace: outside it, the real type in the parent namespace would win. +using DaxFormatterClient = ReadmeClient; + +// The regions are the code of the readme, written for applications: ConfigureAwait would be noise there. +#pragma warning disable CA2007 + +/// +/// The C# code of the package readme. Each region is one code block of dotnet/README.md, character for +/// character: compares them, and the tests here run them. +/// +public class ReadmeSamples +{ + [Fact] + public async Task FormatAsync_GettingStartedSample_FormatsTheQuery() + { + #region GettingStarted + var client = new DaxFormatterClient(); + + DaxFormatResult result = await client.FormatAsync("EVALUATE FILTER(Customer, Customer[Country] = \"Italy\")"); + + Console.WriteLine(result.FormattedText); + // EVALUATE + // FILTER ( Customer, Customer[Country] = "Italy" ) + #endregion + + Assert.Equal("EVALUATE\r\nFILTER ( Customer, Customer[Country] = \"Italy\" )", result.FormattedText); + } + + [Fact] + public async Task FormatBatchAsync_ModelObjectsSample_UpdatesTheMeasuresThatAreValid() + { + var client = new DaxFormatterClient(); + var model = new Model(); + + #region ModelObjects + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + IReadOnlyList> results = + await client.FormatBatchAsync(model.Measures, measure => measure.Expression, options); + + foreach (var result in results) + { + if (result.Succeeded) + { + result.Item.Expression = result.FormattedText; + } + else + { + Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); + } + } + #endregion + + Assert.Equal("CALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )", model.Measures[0].Expression); + Assert.Equal("SUMX(Sales, Sales[Amount] *", model.Measures[1].Expression); + Assert.Equal("DIVIDE ( [Sales Amount], [Total Cost] )", model.Measures[2].Expression); + } + + [Fact] + public async Task FormatAsync_OptionsSample_SendsTheOptions() + { + var client = new DaxFormatterClient(); + + #region Options + var options = new DaxFormatOptions + { + Kind = DaxKind.Expression, + LineStyle = DaxLineStyle.ShortLine, + SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, + SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, + ModelInfo = new DaxModelInfo + { + ServerType = DaxServerTypes.PowerBIDesktop, + DatabaseName = "Contoso", + }, + }; + + DaxFormatResult result = await client.FormatAsync("DIVIDE([Sales Amount]; 1,5)", options); + #endregion + + var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0].EndsWith("1,5)", StringComparison.Ordinal)).Json; + Assert.True(result.Succeeded); + Assert.Equal((1, true), (body.GetProperty("maxLineLength").GetInt32(), body.GetProperty("skipSpaceAfterFunctionName").GetBoolean())); + Assert.Equal((";", ","), (body.GetProperty("listSeparator").GetString(), body.GetProperty("decimalSeparator").GetString())); + } + + [Fact] + public async Task FormatAsync_SyntaxErrorsSample_ReadsThePositionOfTheError() + { + var client = new DaxFormatterClient(); + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + #region SyntaxErrors + DaxFormatResult result = await client.FormatAsync("SUMX(Sales, Sales[Amount] *", options); + + if (!result.Succeeded) + { + foreach (DaxSyntaxError error in result.Errors) + { + Console.WriteLine($"Line {error.Line + 1}, column {error.Column + 1}: {error.Message}"); + } + } + #endregion + + Assert.Equal((0, 27), (result.Errors[0].Line, result.Errors[0].Column)); + } + + [Fact] + public async Task FormatAsync_FunctionsSample_FormatsTheBodyOfTheFunction() + { + var client = new DaxFormatterClient(); + + #region Functions + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + DaxFormatResult result = await client.FormatAsync( + "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)", options); + + Console.WriteLine(result.FormattedText); + // ( + // amount : NUMERIC, + // rate : NUMERIC + // ) => + // amount * ( 1 + rate ) + #endregion + + Assert.Equal( + "(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", result.FormattedText); + } + + [Fact] + public async Task FormatBatchAsync_ProgressSample_ReturnsEveryResult() + { + var client = new DaxFormatterClient(); + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + var expressions = Enumerable.Range(1, 600).Select(number => "[Sales] * " + number).ToList(); + using var cancellation = new CancellationTokenSource(); + var cancellationToken = cancellation.Token; + + #region Progress + var progress = new Progress( + info => Console.WriteLine($"{info.Completed} of {info.Total} expressions formatted")); + + IReadOnlyList results = + await client.FormatBatchAsync(expressions, options, progress, cancellationToken); + #endregion + + Assert.Equal(expressions, results.Select(result => result.FormattedText)); + } + + [Fact] + public async Task FormatBatchAsync_FailuresSample_CatchesTheFailureOfTheService() + { + using var handler = new FakeFormatterHandler(Respond.Status(HttpStatusCode.BadRequest)); + using var httpClient = new HttpClient(handler); + var client = new DaxFormatterClient(httpClient); + string[] expressions = ["[Sales] * 2"]; + + #region Failures + try + { + IReadOnlyList results = await client.FormatBatchAsync(expressions); + Console.WriteLine($"{results.Count} expressions formatted"); + } + catch (DaxFormatterException exception) + { + Console.WriteLine($"{exception.Reason}: {exception.Message}"); + Console.WriteLine($"Request {exception.RequestId}, status {exception.StatusCode}"); + } + #endregion + + Assert.Single(handler.Requests); + } + + [Fact] + public async Task Constructor_ClientOptionsSample_IdentifiesTheApplication() + { + #region ClientOptions + var client = new DaxFormatterClient(new DaxFormatterClientOptions + { + ApplicationName = "Contoso Model Tools", + ApplicationVersion = "1.4.0", + RequestTimeout = TimeSpan.FromSeconds(120), + MaxRetries = 3, + MaxConcurrentRequests = 4, + }); + #endregion + + await client.FormatAsync("EVALUATE Tools"); + + var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0] == "EVALUATE Tools").Json; + Assert.Equal("Contoso Model Tools", body.GetProperty("callerApp").GetString()); + } + + [Fact] + public async Task Constructor_HttpClientSample_SendsTheRequestsWithIt() + { + using var handler = new FakeFormatterHandler(Respond.Echo); + using var httpClient = new HttpClient(handler); + + #region HttpClient + var client = new DaxFormatterClient(httpClient); + #endregion + + await client.FormatAsync("EVALUATE Sales"); + + Assert.Single(handler.Requests); + } + + private sealed class Measure + { + public Measure(string name, string expression) + { + Name = name; + Expression = expression; + } + + public string Name { get; } + + public string Expression { get; set; } + } + + private sealed class Model + { + public List Measures { get; } = + [ + new Measure("Sales", "CALCULATE(SUM(Sales[Amount]), Sales[Quantity] > 0)"), + new Measure("Broken", "SUMX(Sales, Sales[Amount] *"), + new Measure("Cost Ratio", "DIVIDE([Sales Amount], [Total Cost])"), + ]; + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs new file mode 100644 index 0000000..ce9973f --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs @@ -0,0 +1,58 @@ +using System.Net.Http; +using System.Text.Json.Nodes; +using Dax.Formatter.Tests.Fakes; + +namespace Dax.Formatter.Tests.Readme; + +/// +/// Stands in for the service in the samples of the readme: it gives the answers that the service gave for the +/// texts of the samples, and the answer of for any other text. +/// +internal static class ReadmeService +{ + private static readonly Dictionary s_formatted = new(StringComparer.Ordinal) + { + ["EVALUATE FILTER(Customer, Customer[Country] = \"Italy\")"] = + "EVALUATE\r\nFILTER ( Customer, Customer[Country] = \"Italy\" )\r\n", + ["[x] :=\nCALCULATE(SUM(Sales[Amount]), Sales[Quantity] > 0)"] = + "[x] :=\r\nCALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )\r\n", + ["[x] :=\nDIVIDE([Sales Amount], [Total Cost])"] = + "[x] :=\r\nDIVIDE ( [Sales Amount], [Total Cost] )\r\n", + ["FUNCTION x =\n(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"] = + "FUNCTION x = (\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n ) =>\r\n amount * ( 1 + rate )\r\n", + }; + + // The service reports the end of the input as the line after the last one. + private static readonly Dictionary s_errors = new(StringComparer.Ordinal) + { + ["[x] :=\nSUMX(Sales, Sales[Amount] *"] = (2, 0), + }; + + public static FakeFormatterHandler Handler { get; } = new(Respond.Json(Answer)); + + public static HttpClient HttpClient { get; } = new(Handler); + + private static string Answer(IReadOnlyList dax) + { + var echoed = JsonNode.Parse(EchoService.Answer(dax))!.AsArray(); + for (var index = 0; index < dax.Count; index++) + { + if (s_formatted.TryGetValue(dax[index], out var formatted)) + { + echoed[index] = new JsonObject { ["formatted"] = formatted, ["errors"] = new JsonArray() }; + } + else if (s_errors.TryGetValue(dax[index], out var position)) + { + var error = new JsonObject + { + ["line"] = position.Line, + ["column"] = position.Column, + ["message"] = EchoService.ErrorMessage, + }; + echoed[index] = new JsonObject { ["formatted"] = string.Empty, ["errors"] = new JsonArray(error) }; + } + } + + return echoed.ToJsonString(); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeTests.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeTests.cs new file mode 100644 index 0000000..040ecd9 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeTests.cs @@ -0,0 +1,61 @@ +using System.Text.RegularExpressions; +using Dax.Formatter.Tests.Fixtures; +using Xunit; + +namespace Dax.Formatter.Tests.Readme; + +/// +/// Keeps the C# code of the package readme equal to code that compiles and runs: the regions of +/// . A readme on nuget.org can be corrected only with a new version of the package. +/// +public class ReadmeTests +{ + private static readonly Regex s_codeBlock = new(@"^```csharp\n(?.*?)\n```$", RegexOptions.Multiline | RegexOptions.Singleline); + private static readonly Regex s_region = new(@"^[ ]*#region (?\w+)\n(?.*?)\n[ ]*#endregion", RegexOptions.Multiline | RegexOptions.Singleline); + + public static IEnumerable RegionNames => ReadRegions().Keys.Select(name => new object[] { name }); + + [Fact] + public void Readme_EveryCSharpBlock_IsARegionOfTheSamples() + { + var regions = ReadRegions().Values.ToList(); + + var blocks = ReadCodeBlocks(); + + Assert.NotEmpty(blocks); + Assert.All(blocks, block => Assert.Contains(block, regions)); + } + + [Theory] + [MemberData(nameof(RegionNames))] + public void Samples_EveryRegion_IsACSharpBlockOfTheReadme(string name) + { + var region = ReadRegions()[name]; + + var blocks = ReadCodeBlocks(); + + Assert.Contains(region, blocks); + } + + private static List ReadCodeBlocks() + { + var readme = FixtureFile.ReadText("README.md"); + return [.. s_codeBlock.Matches(readme).Cast().Select(match => match.Groups["code"].Value)]; + } + + private static Dictionary ReadRegions() + { + var source = FixtureFile.ReadText("ReadmeSamples.cs"); + return s_region.Matches(source).Cast().ToDictionary( + match => match.Groups["name"].Value, + match => RemoveIndentation(match.Groups["code"].Value)); + } + + // A region sits inside a method: its lines lose the indentation of the least indented one. + private static string RemoveIndentation(string code) + { + var lines = code.Split('\n'); + var indentation = lines.Where(line => line.Trim().Length > 0).Min(line => line.Length - line.TrimStart().Length); + return string.Join("\n", lines.Select(line => line.Length >= indentation ? line.Substring(indentation) : line.Trim())); + } +} From ceaa7c0495a1e4dad79ed658816820d1e20141b0 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:17 +0100 Subject: [PATCH 10/29] test(dotnet): add live tests that run only on request - skip the tests that call the service unless DAXFORMATTER_LIVE_TESTS is set, so that CI stays offline - check the recorded answers of the fixtures against the service, the formatting of a function, the three known limits of the service and a call that needs several requests --- .../Live/LiveFactAttribute.cs | 21 +++ .../Live/LiveServiceTestGroup.cs | 12 ++ .../Live/LiveServiceTests.cs | 149 ++++++++++++++++++ 3 files changed, 182 insertions(+) create mode 100644 dotnet/tests/Dax.Formatter.Tests/Live/LiveFactAttribute.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTestGroup.cs create mode 100644 dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs diff --git a/dotnet/tests/Dax.Formatter.Tests/Live/LiveFactAttribute.cs b/dotnet/tests/Dax.Formatter.Tests/Live/LiveFactAttribute.cs new file mode 100644 index 0000000..806f1c6 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Live/LiveFactAttribute.cs @@ -0,0 +1,21 @@ +using Xunit; + +namespace Dax.Formatter.Tests.Live; + +/// +/// Marks a test that calls the live DAX Formatter service. The test is skipped unless the environment variable +/// is set, so that a normal run needs no network. +/// +[AttributeUsage(AttributeTargets.Method)] +public sealed class LiveFactAttribute : FactAttribute +{ + public const string EnvironmentVariable = "DAXFORMATTER_LIVE_TESTS"; + + public LiveFactAttribute() + { + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable))) + { + Skip = "Calls the live service: set " + EnvironmentVariable + " to run it."; + } + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTestGroup.cs b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTestGroup.cs new file mode 100644 index 0000000..c092cb0 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTestGroup.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace Dax.Formatter.Tests.Live; + +/// +/// Puts the tests that call the live service in one collection, so that they run one at a time. +/// +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class LiveServiceTestGroup +{ + public const string Name = "Live service"; +} diff --git a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs new file mode 100644 index 0000000..cbdf329 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs @@ -0,0 +1,149 @@ +using System.Text.Json; +using Dax.Formatter.Tests.Fixtures; +using Xunit; + +namespace Dax.Formatter.Tests.Live; + +/// +/// Pins, on the live service, the facts that the client relies on. A failure here with green offline tests +/// means that the service changed: the fixtures and the client follow. +/// +[Collection(LiveServiceTestGroup.Name)] +[Trait("Category", "Live")] +public class LiveServiceTests +{ + private const string Fixture = "format-results.json"; + + private static readonly DaxFormatterClient s_client = new(new DaxFormatterClientOptions + { + ApplicationName = "Dax.Formatter.Tests", + ApplicationVersion = "2.0", + }); + + private static readonly DaxFormatOptions s_expression = new() { Kind = DaxKind.Expression }; + + [LiveFact] + public async Task FormatBatchAsync_FixtureTextsSentAsTheyAre_ReturnsTheRecordedResults() + { + await AssertFixtureResultsAsync(DaxKind.Auto).ConfigureAwait(true); + } + + [LiveFact] + public async Task FormatBatchAsync_FixtureExpressions_ReturnsTheRecordedResults() + { + await AssertFixtureResultsAsync(DaxKind.Expression).ConfigureAwait(true); + } + + [LiveFact] + public async Task FormatAsync_FunctionBody_ReturnsItFormattedWithoutHeaderAndIndentation() + { + var result = await s_client + .FormatAsync("// tax\n(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)", s_expression) + .ConfigureAwait(true); + + Assert.Equal( + "// tax\r\n(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", + result.FormattedText); + } + + [LiveFact] + public async Task FormatBatchAsync_KnownLimitsOfTheService_StillReturnSyntaxErrors() + { + string[] texts = ["() => 1", "(a, b = 1) => a + b", "\"a => b\""]; + + var results = await s_client.FormatBatchAsync(texts, s_expression).ConfigureAwait(true); + + // When one of these starts to succeed, the service has lost that limit: update the documents. + Assert.Equal([false, false, false], results.Select(result => result.Succeeded)); + Assert.Equal((0, 0), (results[2].Errors[0].Line, results[2].Errors[0].Column)); + } + + [LiveFact] + public async Task FormatBatchAsync_MoreTextsThanARequestCarries_ReturnsEveryResultInOrder() + { + var texts = Enumerable.Range(1, 600).Select(number => "[Sales]*" + number).ToList(); + + var results = await s_client.FormatBatchAsync(texts, s_expression).ConfigureAwait(true); + + var expected = Enumerable.Range(1, 600).Select(number => "[Sales] * " + number); + Assert.Equal(expected, results.Select(result => result.FormattedText)); + } + + [LiveFact] + public async Task FormatAsync_ShortLinesWithoutSpaceAfterFunctions_FormatsThatWay() + { + var options = new DaxFormatOptions + { + Kind = DaxKind.Expression, + LineStyle = DaxLineStyle.ShortLine, + SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, + }; + + var result = await s_client.FormatAsync("IF(1=1,1,0)", options).ConfigureAwait(true); + + Assert.Equal("IF(\r\n 1 = 1,\r\n 1,\r\n 0\r\n)", result.FormattedText); + } + + [LiveFact] + public async Task FormatAsync_SemicolonAndCommaWithEveryModelProperty_FormatsTheText() + { + var options = new DaxFormatOptions + { + Kind = DaxKind.Expression, + SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, + ModelInfo = new DaxModelInfo + { + ServerName = "MyServerName1", + DatabaseName = "MyDatabaseName1", + ServerType = DaxServerTypes.AnalysisServices, + ServerMode = "Tabular", + ServerEdition = "Enterprise64", + ServerLocation = "OnPremise", + ServerVersion = "16.0.143.21", + CompatibilityLevel = 1600, + }, + }; + + var result = await s_client.FormatAsync("DIVIDE(1,5;2)", options).ConfigureAwait(true); + + Assert.Equal("DIVIDE ( 1,5; 2 )", result.FormattedText); + } + + private static async Task AssertFixtureResultsAsync(DaxKind kind) + { + var cases = FixtureFile.Load(Fixture).GetProperty("cases").EnumerateArray() + .Where(testCase => FixtureOptions.ReadKind(testCase) == kind) + .ToList(); + var texts = cases.Select(testCase => testCase.GetProperty("text").GetString()!); + + var results = await s_client + .FormatBatchAsync(texts, new DaxFormatOptions { Kind = kind }) + .ConfigureAwait(true); + + Assert.All(cases.Zip(results, (testCase, result) => (testCase, result)), pair => + { + var name = pair.testCase.GetProperty("name").GetString(); + Assert.True(Describe(pair.testCase.GetProperty("result")) == Describe(pair.result), name); + }); + } + + // The message of an error is long and lists what the grammar accepts, so only its position is compared. + private static string Describe(JsonElement expected) + { + if (expected.TryGetProperty("formattedText", out var formattedText)) + { + return "text: " + formattedText.GetString(); + } + + var positions = expected.GetProperty("errors").EnumerateArray().Select( + error => (error.GetProperty("line").GetInt32(), error.GetProperty("column").GetInt32())); + return "errors: " + string.Join(" ", positions); + } + + private static string Describe(DaxFormatResult result) + { + return result.Succeeded + ? "text: " + result.FormattedText + : "errors: " + string.Join(" ", result.Errors.Select(error => (error.Line, error.Column))); + } +} From 4c0c548e0df47e2aec03121d1232c6588b1bf267 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:17 +0100 Subject: [PATCH 11/29] build(dotnet)!: set the package version to 2.0.0 - write the full version by hand: the git height is now only the fourth number of the file version --- dotnet/version.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/version.json b/dotnet/version.json index f6fb214..b3ca6f6 100644 --- a/dotnet/version.json +++ b/dotnet/version.json @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", - "version": "1.2", + "version": "2.0.0", "assemblyVersion": { "precision": "major" }, From ed2a1ca742fa6c9353f7d356e61034f3073ed6ad Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:18:17 +0100 Subject: [PATCH 12/29] docs: describe the 2.0 client and its versioning - add client-api.md, the model of a client that the other languages will port, with the three limits of the service - separate in rest-api.md the contract of the service from what the clients do, and add the new headers, the string enums and how the service reports positions - update the architecture for the offline tests and the version written by hand - close B-10, B-12 and B-13 in the backlog, reword B-4, B-5, B-8, B-11 and B-16, and add B-17 to B-22 - update dotnet/AGENTS.md: no sample, offline tests, how to run the live ones, the version rules --- docs/backlog.md | 23 ++++++---- docs/design/README.md | 1 + docs/design/architecture.md | 14 +++--- docs/design/client-api.md | 85 ++++++++++++++++++++++++++++++++++++ docs/design/rest-api.md | 86 ++++++++++++++++++++++--------------- dotnet/AGENTS.md | 33 +++++++++----- 6 files changed, 180 insertions(+), 62 deletions(-) create mode 100644 docs/design/client-api.md diff --git a/docs/backlog.md b/docs/backlog.md index 9345862..eadd831 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,6 +1,6 @@ # Backlog -Next ID: B-17 +Next ID: B-23 Reports and requests from users stay in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues); an item here links its issue instead of copying it. @@ -8,20 +8,25 @@ Reports and requests from users stay in [GitHub Issues](https://github.com/sql-b - B-1 The MCP server's workflows run on a supported Node.js LTS: `typescript-ci.yml` and `typescript-release-daxformatter-mcp.yml` set `node-version: "20"`, which reached end of life on 2026-04-30; on 2026-11-19 the LTS majors are 22, 24 and 26 ([release schedule](https://github.com/nodejs/Release#release-schedule)). It lands before the next MCP release: on Node.js 20, `npm ci` in the release may fail without a placeholder `NODE_AUTH_TOKEN`, which setup-node v7 no longer sets ([setup-node](https://github.com/actions/setup-node)). Done when both workflows set the same supported LTS major and CI passes on it. `engines` in `package.json` stays out: changing it changes the published package. - B-2 npm trusted publishing for the MCP server release: the release workflow publishes with a long-lived npm token, which can leak and is rotated by hand. Done when the trusted publisher on npm names `typescript-release-daxformatter-mcp.yml`, the release job runs on Node.js 22.14 or later with npm 11.5.1 or later, a release publishes without the token, and a maintainer deletes the token. Depends on B-1. - B-3 MCP registry entry for the stdio server, so that AI clients that browse the registry find it. Done when a `server.json` describes the npm package with `repository.subfolder` set to `typescript/packages/daxformatter-mcp`, the server appears in the registry, and `typescript/AGENTS.md` has the command that updates the entry. +- B-19 The .NET release workflow stops before the build when the tag of the version already exists: since the version is written by hand ([ADR-0006](decisions/0006-write-the-dax-formatter-package-version-by-hand.md)), a release from a `master` whose version was already published is stopped only by `dotnet nuget push`, after the build and the tests. Done when `dotnet-release-dax-formatter.yml` fails right after it reads the version if the tag `Dax.Formatter-v` exists, with a message that says to raise the version in `dotnet/version.json`. ## Later -- B-4 OpenAPI contract in `spec/`, with test vectors shared by all clients: one definition of the REST contract (see Known debt). -- B-5 TypeScript client library in `typescript/packages/daxformatter`, extracted from the port inside the MCP package and used by it. +- B-4 OpenAPI contract in `spec/`, with test vectors shared by all clients: one definition of the REST contract (see Known debt). The vectors start from the fixtures of the .NET tests in `dotnet/tests/Dax.Formatter.Tests/Fixtures/`, which hold nothing specific to .NET ([client API](design/client-api.md#code-and-tests)). +- B-5 TypeScript client library in `typescript/packages/daxformatter`: a port of the client model of [`client-api.md`](design/client-api.md) ([ADR-0005](decisions/0005-decouple-the-client-api-from-the-rest-contract.md)), which replaces the port inside the MCP package and is used by it. Done when it passes the shared fixtures (B-4). - B-6 npm workspaces rooted at `typescript/`, so the npm packages share one lockfile and one install; needed once there are two npm packages. - B-7 Python client in `python/`. -- B-8 `timeout-minutes` for the job of `dotnet-ci.yml`, whose tests call the live service: without it, a stuck run lasts up to GitHub's default of 360 minutes ([workflow syntax](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idtimeout-minutes)). +- B-8 `timeout-minutes` for the job of `dotnet-ci.yml`: without it, a stuck run lasts up to GitHub's default of 360 minutes ([workflow syntax](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idtimeout-minutes)). - B-9 `concurrency` groups in both CI workflows, so that a newer push to a pull request cancels its older run. +- B-17 The .NET client finds the text that makes a request fail: when the service fails on one text, the whole request fails and the call with it, and the exception names only the texts of that request by their indexes. Done when the client sends the texts of a failed request again in smaller requests, reports the one that fails, and [`client-api.md`](design/client-api.md) says how. +- B-18 Measured limits for the requests of the .NET client: 250 texts and 250,000 characters for each request and 2 requests at a time are estimates ([client API](design/client-api.md#requests)). Done when the numbers come from measures on the service with real models, and `client-api.md` states them. +- B-21 One version scheme for both packages when the MCP server leaves its beta: until then it stays on `0.2-beta` with the git height as its third number, while `Dax.Formatter` has a version written by hand ([ADR-0006](decisions/0006-write-the-dax-formatter-package-version-by-hand.md)). Done when a decision record says which scheme the MCP server follows from its first stable version. + +## Open decisions +- B-20 Remove NBGV from the .NET toolchain? Since [ADR-0006](decisions/0006-write-the-dax-formatter-package-version-by-hand.md) it no longer computes the package version: it stamps the one in `dotnet/version.json`, adds the commit suffix outside `master` and puts the git height in the file version. The options: keep it, or set the version in the project file and change the release workflow, which reads the version from NBGV. The answer depends on whether the commit suffix and the file version are worth the tool, and on the scheme the MCP server takes (B-21). ## Known debt -- B-10 The clients send enums in different forms: the .NET client sends `ServerMode`, `ServerEdition` and `ServerLocation` as numbers, the TypeScript port as strings; `ServerType` is a string in both. Cost: the service receives two forms of the same fields, a new client has no rule to follow, and changing the .NET form changes the wire format of a published package. Repay with the OpenAPI contract, which fixes one form for every client. -- B-11 The REST contract is restated in each client: the .NET request and response models, the TypeScript port's types and serializer, and the zod schemas of the MCP tool. Cost: every contract change touches each copy, and the copies already drift (B-10). Repay with the OpenAPI contract and its shared test vectors. -- B-12 The getting-started sample references `Dax.Formatter` 1.0.0, while nuget.org has 1.2.2. Cost: the sample builds against a package from 2021, not the one users install. Repay in the next change to the sample. -- B-13 The .NET tests call the live service (`DaxFormatterClientTests`). Cost: .NET CI depends on the service and the network, and an outage fails unrelated pull requests. Repay with the shared test vectors: unit tests against recorded responses, and the live tests in a separate job. +- B-11 The REST contract is restated in each client: the .NET wire types in `dotnet/src/Dax.Formatter/Wire/`, the TypeScript port's types and serializer, and the zod schemas of the MCP tool. Cost: every contract change touches each copy. Repay with the OpenAPI contract and its shared test vectors (B-4). - B-14 The MCP server says that `formatted` is null for invalid DAX, in the tool description in `typescript/packages/daxformatter-mcp/src/format-tool.ts` and in the comment of `formatted` in `src/daxformatter/types.ts`, while the service returns an empty string ([REST API, Response](design/rest-api.md#response)). Cost: an AI client that follows the tool description misses the empty string. Repay by fixing both texts, which raises the MCP server's version. - B-15 Releases are tied to `master` only by the branch guard of the release workflows: a run uses the workflow file of the commit it runs on ([Workflows](https://docs.github.com/en/actions/concepts/workflows-and-actions/workflows)), so a branch whose copy drops the guard runs with the repository secrets, and the nuget.org Trusted Publishing policy names the workflow file, not a branch. Cost: whoever can push a branch and run workflows can publish from it. Repay: remove the nuget.org policy for `release.yml`, the .NET release workflow's name before the move in `6df1bf0`; run each release job in a GitHub environment that only `master` can deploy to, which holds the release secrets and which the nuget.org policy names ([Trusted Publishing](https://learn.microsoft.com/en-us/nuget/nuget-org/trusted-publishing), [environments](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)). -- B-16 Some files under `dotnet/` don't follow `.editorconfig`: a missing or unwanted byte order mark, no final newline, trailing whitespace, and tabs, including in the two `.sln` files, which Visual Studio writes with tabs. Cost: saving one in an editor that applies `.editorconfig` puts changes unrelated to the edit in the diff. Repay with one commit that only normalizes these files, and a `[*.sln]` section with `indent_style = tab`. +- B-16 Some files under `dotnet/` don't follow `.editorconfig`: a missing or unwanted byte order mark, no final newline, trailing whitespace, and tabs, including in `Dax.Formatter.sln`, which Visual Studio writes with tabs. Cost: saving one in an editor that applies `.editorconfig` puts changes unrelated to the edit in the diff. Repay with one commit that only normalizes these files, and a `[*.sln]` section with `indent_style = tab`. +- B-22 The service rejects three kinds of valid DAX with a syntax error: a function without parameters, a function parameter with a default value and, sent as the expression of a model object, an expression with `=>` inside a string or a comment ([client API](design/client-api.md#limits-of-the-service)). Cost: no client can format them, and each returns the syntax error to its caller. Repay in the service, which is outside this repository; then remove the limits from `client-api.md`, `rest-api.md` and the .NET package readme, and update the live test that pins them. diff --git a/docs/design/README.md b/docs/design/README.md index 9bf0ba9..44e2ba6 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -4,3 +4,4 @@ How the system works today. A design document changes in the same pull request a - [`architecture.md`](architecture.md): the packages, the service they call, the rules they share, and how each is versioned, released and built by CI. Read before changing a package's boundaries, a `version.json` or a workflow. - [`rest-api.md`](rest-api.md): the REST contract of the DAX Formatter service, as the clients use it. Read before changing a request, a response or how a client calls the service. +- [`client-api.md`](client-api.md): the model of a client, whatever its language, and what it does around the REST contract: kinds of text, results, splitting, retries. Read before changing the public API or the behavior of a client, and before porting it to another language. diff --git a/docs/design/architecture.md b/docs/design/architecture.md index b319065..3033e55 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -8,23 +8,23 @@ DAX Formatter is a service that formats DAX expressions and reports their syntax Each package lives in its language folder and builds with its own toolchain ([ADR-0001](../decisions/0001-organize-the-repository-by-language.md)). -- `Dax.Formatter`, in `dotnet/`: `DaxFormatterClient` formats one expression or many in one call; each instance keeps one `HttpClient` for its lifetime, so reusing an instance reuses its connections. One solution holds the library and its tests; samples build against the published package ([ADR-0003](../decisions/0003-keep-one-net-solution-with-role-folders.md)). +- `Dax.Formatter`, in `dotnet/`: `DaxFormatterClient` formats one DAX text or thousands in one call, splits a large call into requests, retries them and returns one result for each text ([`client-api.md`](client-api.md), [ADR-0005](../decisions/0005-decouple-the-client-api-from-the-rest-contract.md)). Its public API doesn't show the wire format. All the clients share one `HttpClient`, unless the application passes its own. One solution holds the library and its tests ([ADR-0003](../decisions/0003-keep-one-net-solution-with-role-folders.md)); the examples are in the package readme, checked by the tests. - `@sqlbi/daxformatter-mcp`, in `typescript/packages/daxformatter-mcp/`: one read-only tool, `format_dax`, which sends every expression in one request to the multiple endpoint, through the package's own TypeScript port of the client in `src/daxformatter/`, not published on its own. -- The REST contract is implemented twice, once per client; [`rest-api.md`](rest-api.md) is its only description, and the [backlog](../backlog.md#known-debt) records where the two implementations differ. +- The REST contract is implemented twice, once per client; [`rest-api.md`](rest-api.md) is its only description. The TypeScript port doesn't follow the client model of [`client-api.md`](client-api.md) yet ([backlog](../backlog.md)). ## Cross-cutting rules - Privacy: the DAX text goes to the service, where the formatting happens; server and database names are hashed by the client before they leave it ([hashing](rest-api.md#hashing-of-server-and-database-names)). - Caller identity: each request names the calling application and its version, for usage statistics; the MCP server adds the AI client's name and version ([caller identity](rest-api.md#caller-identity)). -- Errors: DAX syntax errors are normal results; only transport failures, timeouts and non-success HTTP statuses are errors ([errors](rest-api.md#errors)). -- Tests: the .NET tests call the live service, while the MCP tests replace `fetch` and run offline ([backlog](../backlog.md#known-debt)). +- Errors: DAX syntax errors are normal results; only transport failures, timeouts, non-success HTTP statuses and responses that a client can't use are errors ([errors](rest-api.md#errors)). The .NET client reports them all as `DaxFormatterException`, and a cancellation by the caller as `OperationCanceledException` ([outcomes](client-api.md#outcomes)). +- Tests: both test suites run offline: the .NET tests answer from a fake `HttpMessageHandler`, the MCP tests replace `fetch`. The .NET tests that call the live service are skipped unless asked for ([`dotnet/AGENTS.md`](../../dotnet/AGENTS.md)); they check the answers recorded in the fixtures against the service. ## Deployment -Each package has its own version, tags and release workflow ([ADR-0004](../decisions/0004-version-tag-and-release-each-package-independently.md)). Nerdbank.GitVersioning (NBGV) computes the version from the package's `version.json`: the height counts the commits that touch its path filters, and only `master` gets a version without a commit suffix. +Each package has its own version, tags and release workflow ([ADR-0004](../decisions/0004-version-tag-and-release-each-package-independently.md)). Nerdbank.GitVersioning (NBGV) reads the version from the package's `version.json`; the height counts the commits that touch its path filters, and only `master` gets a version without a commit suffix. -- `Dax.Formatter`: `dotnet/version.json`, path filter `./src/Dax.Formatter`; stamped by the `Nerdbank.GitVersioning` MSBuild package that `dotnet/Directory.Build.props` references; released by `dotnet-release-dax-formatter.yml` to nuget.org, with Trusted Publishing. -- `@sqlbi/daxformatter-mcp`: `typescript/packages/daxformatter-mcp/version.json`, path filter `.`, so any change in the package folder, its README included, raises the version; stamped by the `nerdbank-gitversioning` npm package, whose `nbgv-setversion` writes the version into `package.json` at release over the committed placeholder; released by `typescript-release-daxformatter-mcp.yml` to npm, with provenance. +- `Dax.Formatter`: `dotnet/version.json` holds the full version, three numbers written by hand, such as `2.0.0`, which is the version of the package ([ADR-0006](../decisions/0006-write-the-dax-formatter-package-version-by-hand.md)); the height, counted on the path filter `./src/Dax.Formatter`, is only the fourth number of the file version. Stamped by the `Nerdbank.GitVersioning` MSBuild package that `dotnet/Directory.Build.props` references; released by `dotnet-release-dax-formatter.yml` to nuget.org, with Trusted Publishing. +- `@sqlbi/daxformatter-mcp`: `typescript/packages/daxformatter-mcp/version.json` holds two numbers and NBGV adds the height as the third; the path filter is `.`, so any change in the package folder, its README included, raises the version; stamped by the `nerdbank-gitversioning` npm package, whose `nbgv-setversion` writes the version into `package.json` at release over the committed placeholder; released by `typescript-release-daxformatter-mcp.yml` to npm, with provenance. - Both release workflows read the version from the same NBGV copy that stamps the package: two NBGV versions can compute different heights for the same commit, so another copy could tag or push a version other than the packed one. They run only from `master` and create a draft GitHub release. - `dotnet-ci.yml` and `typescript-ci.yml` run on pull requests and pushes to `master` that change their language folder or their own file, and by hand. Their job ids start with the language, so each check, named after its job, is unique across workflows. - A required check that a path filter skips stays pending and blocks merging ([Troubleshooting required status checks](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks)), so neither CI check can be required: a required check needs a job that runs on every pull request, such as a gate job in a workflow without path filters. diff --git a/docs/design/client-api.md b/docs/design/client-api.md new file mode 100644 index 0000000..3b39e20 --- /dev/null +++ b/docs/design/client-api.md @@ -0,0 +1,85 @@ +# Client API + +The model of a DAX Formatter client: what a caller gives it, what it returns, and what it does between the caller and the [REST API](rest-api.md). The model doesn't depend on a language ([ADR-0005](../decisions/0005-decouple-the-client-api-from-the-rest-contract.md)). The .NET library `Dax.Formatter` implements it and gives the names used here; the TypeScript and Python clients will port it ([backlog](../backlog.md)). The TypeScript port inside the MCP server predates this model and doesn't follow it yet. + +## Model + +- **Client** (`DaxFormatterClient`): formats one text (`FormatAsync`) or several (`FormatBatchAsync`). It is thread-safe, meant to be created once, and holds nothing to dispose. Its methods can be overridden, so a test can replace it without an interface. +- **Client options** (`DaxFormatterClientOptions`), copied and checked when the client is created: + + | Option | Default | Meaning | + |---|---|---| + | `ApplicationName`, `ApplicationVersion` | the entry assembly's name and file version | The [caller identity](rest-api.md#caller-identity) | + | `Endpoint` | `https://api.daxformatter.com/` | The base address of the service | + | `RequestTimeout` | 60 seconds | The wait for the answer to one attempt of one request | + | `MaxRetries` | 2 | How many times a request is sent again | + | `MaxConcurrentRequests` | 2 | How many requests of one call are in progress at the same time | + +- **Format options** (`DaxFormatOptions`), copied and checked at the start of each call: `Kind`, `LineStyle`, `SpacingStyle`, `SeparatorStyle`, and the optional `ModelInfo` with the description of the model for the usage statistics. The first value of each enum is its default. +- **Kind** (`DaxKind`): `Auto` sends the text as it is, for a query or a text with its own name; `Expression` is the DAX of one model object without its name, the body of a user-defined function included. +- **Result** (`DaxFormatResult`): `OriginalText`, `Succeeded`, `FormattedText` (absent when `Succeeded` is false) and `Errors` (empty when it is true). A result of the batch operation that takes items also has `Item`, the caller's object. +- **Syntax error** (`DaxSyntaxError`): `Line`, `Column`, `Message`, with value equality. +- **Progress** (`DaxFormatProgressInfo`): `Completed` and `Total`, as numbers of texts. +- **Failure** (`DaxFormatterException`): `Reason` (`Timeout`, `NetworkError`, `HttpError`, `InvalidResponse`, or `Unknown` when the exception was not created by the client), `StatusCode`, `RequestId`, `ServiceRequestId`. + +## Outcomes + +- A syntax error is a value: the result of that text has `Succeeded` false and at least one error. +- A failure of the service or of the network throws `DaxFormatterException`. A batch returns every result, in the order of the input, or throws: it never returns a part. +- A cancellation by the caller throws the cancellation exception of the language. It wins over a failure that happens at the same time. +- A wrong argument throws before any request: a null text, a null text in a batch (the message has its index), a text selector that returns null, an option outside its enum. + +## Texts + +- A blank text, empty or made of white space, is not sent: its result has an empty formatted text. A batch without texts, or with blank texts only, sends no request. +- The formatted text is the service's, without the final line break. Line breaks are not converted: the service writes `\r\n` and returns the line breaks inside strings and comments as they were sent. +- `Auto`: the text travels as it is, and the position of an error is the one the service reports, limited to the text. +- `Expression`: the client writes a header line before the text and removes it from the answer. + - The header is `FUNCTION x =` for a function body and `[x] :=` for anything else, followed by a line feed, so that the lines of the text keep their columns. + - A text is a function body when, after white space and comments, it starts with a parameter list in balanced parentheses followed by `=>`. Parentheses inside strings, names and comments don't count. DAX has the arrow only in [function definitions](https://learn.microsoft.com/dax/function-statement-dax). + - The answer must start with the header: the client removes it with the spaces and the one line break that follow it. An answer that doesn't start with it is an `InvalidResponse` failure, so a text that the client can't verify never reaches the caller. + - Under a function header the service indents every line by four more spaces, and writes the parameter list either on the header line or, when a comment comes first, on the next one. The client removes four spaces from the start of each line after the header line. A line that starts inside a string, a quoted or bracketed name or a block comment is content: the service returns it as it was sent, and the client leaves it alone. + +## Error positions + +`Line` and `Column` are zero-based and refer to the text that the caller gave. Lines are separated by `\n`. `Column` is an index into the UTF-16 code units of the line, and equals the length of the line, without its `\r`, when the error is at its end. + +The client converts the [position that the service reports](rest-api.md#response): + +- for `Expression`, the line minus one, because of the header line; an error on the header line becomes line 0, column 0; +- the column from the service's count, where a tab reaches the next multiple of 8 and `\r` has no width, to the index in the line; +- an error past the last line, as the service reports the end of the input, becomes the end of the last line. + +## Requests + +- A call is split into requests of at most 250 texts and 250,000 characters; a longer text travels alone. The two numbers are internal constants, not yet measured ([backlog](../backlog.md)). +- The header lines are added when a request is written, and its body is kept as bytes for its retries. +- At most `MaxConcurrentRequests` requests are in progress. Each result is stored at the index of its text. +- Progress is reported after each request, and once before the first one for the blank texts. The count never decreases. +- Retry: after a timeout, a network error and the statuses 408, 429, 500, 502, 503 and 504. Any other status and an invalid response fail at once. The wait starts at 0.8 seconds and doubles up to 60, varied by a quarter either way; a longer `Retry-After`, in seconds or as a date measured from the `Date` header of the same response, replaces it, and one longer than `RequestTimeout` fails the request at once. Each attempt sends the same body and the same request identifier. +- The first request that fails after its retries stops the others, and the call fails with it. The message names the texts of that request by their indexes. +- A request that timed out is not split in two: the service keeps working on an abandoned request, so smaller requests would add load when it is slow. +- Invalid responses: status 204, a body that is not the documented JSON, a number of results other than the number of texts sent, a null result. In a result, a null `errors` is no errors, and a null `formatted` without errors is an empty text; `formatted` is not read when there are errors. + +## Identity and transport + +- Each request has the [caller identity](rest-api.md#caller-identity) in its body, and the headers `User-Agent`, `DaxFormatter-Request-Id` (one for each request, the same in its retries) and `DaxFormatter-Operation-Id` (one for each call) ([headers](rest-api.md#endpoints)). +- `User-Agent` is `/ Dax.Formatter/ ()`. The application name and version are cleaned into HTTP tokens, so `DAX Studio` becomes `DAX-Studio`; the body keeps them as they are. +- Without an HTTP client from the caller, all the clients share one that lives as long as the process, has no timeout of its own and doesn't check certificate revocation; on .NET 10 it replaces its pooled connections every 5 minutes, so that a DNS change is seen ([guidelines](https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines)). Nothing is created before the first call. +- An HTTP client from the caller is never changed or disposed. Its base address is ignored: every request has an absolute URI built from `Endpoint`. Its own timeout applies too, so the shorter one wins, and is reported as `Timeout`. +- The server and database names of `ModelInfo` leave the client only as [hashes](rest-api.md#hashing-of-server-and-database-names). + +## Limits of the service + +The client returns these as the syntax errors that the service reports. They were observed on 2026-11-22 and the live tests check that they still hold: + +1. A function without parameters, `() => 1`, is a syntax error, though [valid DAX](https://learn.microsoft.com/dax/best-practices/dax-user-defined-functions). +2. A function parameter with a default value, `(a, b = 1) => a + b`, is a syntax error. +3. With `Expression`, an expression that is not a function and has `=>` inside a string or a comment is a syntax error on the header line, which the client reports at line 0, column 0. + +## Code and tests + +- .NET: `dotnet/src/Dax.Formatter`. Public types are in the root folder, one in each file; internal ones in a folder for each responsibility: `Configuration/` (copies of the options, request limits, caller identity), `Wire/` (request and response bodies, name hashing), `Expressions/` (the DAX text scanner, the function recognizer, the header, its removal, error positions), `Results/`, `Batching/` (planning, workers, progress), `Transport/` (one attempt, the retry loop and its policy, the shared HTTP client), `Polyfills/` (what `netstandard2.0` lacks). +- The cases of the wire format are JSON files in `dotnet/tests/Dax.Formatter.Tests/Fixtures/`, written so that every client can run them: request bodies, name hashes, function bodies, and recorded answers of the service with the result expected from each. They move to `spec/` with the shared contract ([backlog](../backlog.md)). +- The tests run offline against a fake HTTP handler. The tests in `Live/` call the service and run only on request ([`dotnet/AGENTS.md`](../../dotnet/AGENTS.md)). +- `PublicApiTests` pins the public surface in `PublicApi.approved.txt`; `ReadmeTests` pins the code of the package readme to code that runs. diff --git a/docs/design/rest-api.md b/docs/design/rest-api.md index e166e86..3731934 100644 --- a/docs/design/rest-api.md +++ b/docs/design/rest-api.md @@ -1,17 +1,26 @@ # REST API -The public REST contract of the DAX Formatter service, as the .NET client and the TypeScript port inside the MCP server use it. The service is maintained outside this repository; this document is the only place in the repository that states its contract. +The public REST contract of the DAX Formatter service, as observed from outside, and how the two clients of this repository use it: the .NET client and the TypeScript port inside the MCP server. The service is maintained outside this repository; this document is the only place in the repository that states its contract. What the .NET client does around the contract, such as splitting and retries, is in [`client-api.md`](client-api.md). ## Endpoints | Method | URL | Body | Response | |---|---|---|---| | `POST` | `https://api.daxformatter.com/api/daxtextformat` | a request whose `dax` is a string | one result | -| `POST` | `https://api.daxformatter.com/api/daxtextformatmulti` | a request whose `dax` is an array of strings | an array of results, one per expression, in the order sent | +| `POST` | `https://api.daxformatter.com/api/daxtextformatmulti` | a request whose `dax` is an array of strings | an array of results, one per text, in the order sent | - No authentication. -- Request: `Content-Type: application/json`, UTF-8; `Accept: application/json`. The .NET client also sends `Accept-Encoding: GZip` and decompresses gzip responses. -- The .NET client uses either endpoint (`DaxFormatterSingleRequest`, `DaxFormatterMultipleRequest`); the MCP server always uses the multiple one. +- Request: `Content-Type: application/json`, UTF-8; `Accept: application/json`. +- The multiple endpoint formats DAX only; the single one also formats MDX. The .NET client and the MCP server use only the multiple one. +- A request whose `dax` array is empty gets `204 No Content`. +- Responses are not compressed, and each has an `x-azure-ref` header that identifies the request on the service side. +- The .NET client adds three headers, which don't change the answer and let a request be traced: + + | Header | Value | + |---|---| + | `User-Agent` | `/ Dax.Formatter/ ()` | + | `DaxFormatter-Request-Id` | a GUID for the request, the same in its retries | + | `DaxFormatter-Operation-Id` | a GUID for the client call, the same in all its requests | ## Request @@ -19,25 +28,25 @@ A JSON object with camelCase names. Both clients omit a field whose value is nul | Field | Type | Meaning | Clients | |---|---|---|---| -| `dax` | string, or array of strings | The DAX to format: one expression on the single endpoint, a list on the multiple one. | always sent | -| `maxLineLength` | integer | Line style: `0` long lines, `1` short lines. | always sent, default `0`; in .NET a caller can set it to null | -| `skipSpaceAfterFunctionName` | boolean | `false`: a space between a function name and its parenthesis, `SUM ( ... )`; `true`: none, `SUM( ... )`. | always sent, default `false`; in .NET a caller can set it to null | +| `dax` | string, or array of strings | The DAX to format: one text on the single endpoint, a list on the multiple one. | always sent | +| `maxLineLength` | integer | Line style: `0` long lines, `1` short lines. | always sent, default `0` | +| `skipSpaceAfterFunctionName` | boolean | `false`: a space between a function name and its parenthesis, `SUM ( ... )`; `true`: none, `SUM( ... )`. | always sent, default `false` | | `listSeparator` | string, one character | Separator of arguments and list items. | always sent, default `,` | | `decimalSeparator` | string, one character | Decimal point in numbers. | always sent, default `.` | | `serverName` | string | Hash of the server name ([hashing](#hashing-of-server-and-database-names)). | when given | | `databaseName` | string | Hash of the database name ([hashing](#hashing-of-server-and-database-names)). | when given | | `serverType` | string | Kind of server the DAX comes from ([enums](#enums)). | when given | -| `serverMode` | number or string | Analysis Services server mode ([enums](#enums)). | when given | -| `serverEdition` | number or string | Analysis Services edition ([enums](#enums)). | when given | -| `serverLocation` | number or string | On premises or Azure ([enums](#enums)). | when given | -| `serverVersion` | string | Server version, for example `14.0.800.192`. | when given | -| `databaseCompatibilityLevel` | string | Compatibility level of the database, for example `1500`. | when given | +| `serverMode` | string | Analysis Services server mode ([enums](#enums)). | when given | +| `serverEdition` | string | Analysis Services edition ([enums](#enums)). | when given | +| `serverLocation` | string | On premises or Azure ([enums](#enums)). | when given | +| `serverVersion` | string | Server version, for example `16.0.143.21`. | when given | +| `databaseCompatibilityLevel` | string | Compatibility level of the database, for example `1600`. | when given | | `callerApp` | string | Name of the calling application ([caller identity](#caller-identity)). | when known | | `callerVersion` | string | Version of the calling application ([caller identity](#caller-identity)). | when known | -The model metadata, from `serverName` to `databaseCompatibilityLevel`, doesn't change the formatting: the service uses it for usage statistics. +The model metadata, from `serverName` to `databaseCompatibilityLevel`, doesn't change the formatting: the service uses it for usage statistics. The options hold for the whole request. -Example, as the TypeScript port sends it: +Example: ```json { @@ -53,30 +62,28 @@ Example, as the TypeScript port sends it: } ``` -Here `serverName` is the hash of `MyServer`, and the .NET client would send `serverMode` as `2` ([enums](#enums)). +Here `serverName` is the hash of `MyServer`. ## Enums -`serverType` is a string in both clients, with these values: +`serverType`, `serverMode`, `serverEdition` and `serverLocation` are strings. The TypeScript port has an enum for each; the .NET client takes any string, and has the values of `serverType` as the constants of `DaxServerTypes`. -| .NET `ServerType` and TypeScript `ServerType` member | Wire value | +| `DaxServerTypes` constant, TypeScript `ServerType` member | `serverType` | |---|---| | `AnalysisServices` | `SSAS` | | `PowerBIDesktop` | `PBI Desktop` | | `PowerBIReportServer` | `PBI Report Server` | | `PowerPivot` | `PowerPivot` | -| `SSDT` | `SSDT` | +| `Ssdt` in .NET, `SSDT` in TypeScript | `SSDT` | | `AzureAnalysisServices` | `AzureAS` | | `PowerBIService` | `PBI Service` | | `Offline` | `Offline` | -`serverMode`, `serverEdition` and `serverLocation` have the same members in both clients, but their wire form differs: the .NET client sends the member's number, the TypeScript port sends the member's name as a string. This divergence is known debt, not a rule to copy ([backlog](../backlog.md#known-debt)). - -| Field | Member: .NET number, TypeScript string | +| Field | Values | |---|---| -| `serverMode` | `Multidimensional`: 0; `SharePoint`: 1; `Tabular`: 2; `Default`: 3 | -| `serverEdition` | `Standard`: 0; `Standard64`: 1; `Enterprise`: 2; `Enterprise64`: 3; `Developer`: 4; `Developer64`: 5; `Evaluation`: 6; `Evaluation64`: 7; `LocalCube`: 8; `LocalCube64`: 9; `BusinessIntelligence`: 10; `BusinessIntelligence64`: 11; `EnterpriseCore`: 12; `EnterpriseCore64`: 13 | -| `serverLocation` | `OnPremise`: 0; `Azure`: 1 | +| `serverMode` | `Multidimensional`, `SharePoint`, `Tabular`, `Default` | +| `serverEdition` | `Standard`, `Standard64`, `Enterprise`, `Enterprise64`, `Developer`, `Developer64`, `Evaluation`, `Evaluation64`, `LocalCube`, `LocalCube64`, `BusinessIntelligence`, `BusinessIntelligence64`, `EnterpriseCore`, `EnterpriseCore64` | +| `serverLocation` | `OnPremise`, `Azure` | ## Response @@ -84,13 +91,13 @@ A result is a JSON object: | Field | Type | Meaning | |---|---|---| -| `formatted` | string | The formatted DAX, with `\r\n` line breaks. When the expression has syntax errors, the service returns an empty string; both clients also accept `null`. | -| `errors` | array of objects | Syntax errors in the expression, empty when it is valid. | -| `errors[].line` | integer | Line of the error, as the service reports it. | -| `errors[].column` | integer | Column of the error, as the service reports it. | +| `formatted` | string | The formatted DAX. When the text has syntax errors, the service returns an empty string; both clients also accept `null`. | +| `errors` | array of objects | Syntax errors in the text, empty when it is valid. | +| `errors[].line` | integer | Zero-based line of the error in the text sent, where lines are separated by `\n`. | +| `errors[].column` | integer | Zero-based column of the error in that line. | | `errors[].message` | string | Description of the error. | -Both clients model every field as nullable, so a client must accept `null` for any of them. The TypeScript port turns a `null` or missing `errors` into an empty array; the .NET client returns it as `null`. +Both clients accept `null` for any field, and read a `null` or missing `errors` as no errors. From the multiple endpoint: @@ -101,11 +108,20 @@ From the multiple endpoint: ] ``` +What the service does with a text: + +- The formatted text has `\r\n` line breaks and ends with one. Line breaks inside strings and block comments come back as they were sent. A blank text comes back as an empty string without errors. +- A text of the form `name = expression` or `name := expression` is a definition, and the name is kept. A text without a name can be taken for one: `Customer[Name] = "A"` is read as the definition of `Customer[Name]`. A client that formats the DAX of a model object therefore sends it under a name, as `[x] :=` and a line feed before the text, and gets `[x] :=`, a line break and the formatted text. +- A function is sent as `FUNCTION x =`, a line feed and its body, a parameter list followed by `=>`. The service answers with the parameter list on the line of `FUNCTION x =`, or on the next line when a comment comes first, and indents every following line by four more spaces, except the lines that start inside a string or a block comment. +- The column of an error counts UTF-16 code units; a tab counts up to the next multiple of 8, and `\r` has no width. +- An error at the end of the input has the line after the last one and column 0. +- Known limits: a function without parameters, `() => 1`, and a function parameter with a default value, `(a, b = 1) => a + b`, are syntax errors; so is an expression sent under `[x] :=` that has `=>` inside a string or a comment, at line 0. + ## Errors - DAX syntax errors are not HTTP errors: the service answers `200 OK` with the errors in the result. - Any other failure is a non-success HTTP status, for example `500` for a body that is not valid JSON, or a transport failure with no response at all. -- The .NET client throws `HttpRequestException` for a non-success status or a transport failure, and `TaskCanceledException` when a request takes longer than 60 seconds. +- The .NET client throws `DaxFormatterException` with a reason for a failure, a timeout or a response it can't use, after its retries ([client API](client-api.md#requests)). - The TypeScript port throws an `Error` with the status for a non-success status, rejects with the error of `fetch` for a transport failure, and aborts a request that takes longer than its `timeoutMs` option, 60 seconds by default, which the MCP server keeps. - The MCP tool returns each of these failures as a tool error. @@ -114,8 +130,8 @@ From the multiple endpoint: `serverName` and `databaseName` never carry the names themselves. The client sends the SHA-256 hash of the name's UTF-8 bytes, as 64 lowercase hexadecimal characters, so that the service can count distinct servers and databases without learning their names. - An empty name is hashed too: `""` becomes `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. A missing name is not sent. -- The .NET models hash on assignment: reading `ServerName` or `DatabaseName` back returns the hash. The TypeScript port hashes while it builds the request. -- Both clients test the same vectors: `SecurityHelpersTests` in .NET and `hash.test.ts` in TypeScript. +- The .NET client hashes when it copies the options of a call, and keeps only the hashes. The TypeScript port hashes while it builds the request. +- Both clients test the same vectors: the fixture `name-hashes.json` in .NET and `hash.test.ts` in TypeScript. ## Caller identity @@ -123,13 +139,13 @@ From the multiple endpoint: | Client | `callerApp` | `callerVersion` | |---|---|---| -| .NET `DaxFormatterClient` | the `application` argument of the constructor, or else the entry assembly's name | the `version` argument, or else the entry assembly's file version | +| .NET `DaxFormatterClient` | the `ApplicationName` option, or else the entry assembly's name | the `ApplicationVersion` option, or else the entry assembly's file version | | TypeScript port | the `appName` option | the `appVersion` option | | MCP server | `daxformatter-mcp-local/`, or `daxformatter-mcp-local` when the MCP client doesn't send its name | `/`, or the server version alone | -The .NET client writes both fields from the client instance into every request, over any value set on the request object. The MCP server takes the client's name and version from the MCP `initialize` request. +The .NET client also sends the same identity in `User-Agent` ([endpoints](#endpoints)); the body fields stay the identity of reference. The MCP server takes the client's name and version from the MCP `initialize` request. ## Implementations -- .NET: `dotnet/src/Dax.Formatter`, the request and response models in `Models/`, the enums in `AnalysisServices/`, the JSON converters in `Serialization/`, the hashing in `Security/`, the HTTP calls in `Client/Http/`. +- .NET: `dotnet/src/Dax.Formatter`, the request and response bodies, their JSON and the hashing in `Wire/`, the header lines and the error positions in `Expressions/`, the headers and the HTTP calls in `Transport/`, the caller identity in `Configuration/`; the cases of the wire format in `dotnet/tests/Dax.Formatter.Tests/Fixtures/`. - TypeScript: `typescript/packages/daxformatter-mcp/src/daxformatter/`, the types in `types.ts`, the wire form in `serialize.ts`, the hashing in `hash.ts`, the HTTP calls in `client.ts`; the options that the MCP tool exposes are in the zod schemas of `src/format-tool.ts`. diff --git a/dotnet/AGENTS.md b/dotnet/AGENTS.md index 3f775cd..a1f2dae 100644 --- a/dotnet/AGENTS.md +++ b/dotnet/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md -The .NET client library `Dax.Formatter`, published on NuGet, with its tests and a getting-started sample. This file adds the rules of `dotnet/` to the root [`AGENTS.md`](../AGENTS.md). +The .NET client library `Dax.Formatter`, published on NuGet, with its tests. This file adds the rules of `dotnet/` to the root [`AGENTS.md`](../AGENTS.md). ## Commands @@ -12,38 +12,49 @@ dotnet test ./tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj --configurati dotnet pack ./src/Dax.Formatter/Dax.Formatter.csproj --configuration Release # the version a release would publish, when run on an up-to-date master; elsewhere it has a commit suffix dotnet msbuild ./src/Dax.Formatter/Dax.Formatter.csproj -restore -target:GetBuildVersion -getProperty:NuGetPackageVersion -# the sample, against the package on nuget.org and without the build settings of dotnet/ -dotnet build ./samples/GettingStarted/getting-started.sln ``` - The test project also targets `net472`, which runs only on Windows; elsewhere, add `--framework net10.0` to `dotnet test`. +- The tests run offline. Those in `tests/Dax.Formatter.Tests/Live/` call the live DAX Formatter service and are skipped unless the environment variable `DAXFORMATTER_LIVE_TESTS` is set; add `--filter "Category=Live"` to run only them. Run them when a change touches what the client sends or how it reads an answer: they send a few tens of requests, with made-up DAX only. - Local builds are not strong-named: the build signs only when `src/Dax.Formatter/DaxFormatter.snk` exists (`Directory.Build.props`), and only `dotnet-release-dax-formatter.yml` writes it, from the `SIGNING_KEY` secret. ## Done means -- Build, tests and pack succeed from `dotnet/`, with no new warnings. -- The tests call the live DAX Formatter service: they need network access, and a failure can come from the service rather than from the change. +- Build, tests and pack succeed from `dotnet/`, with no warnings: the build of `master` has none. +- A live test that fails while the offline tests pass means that the service changed: say so, don't change the fixture to make it pass without checking the service. ## Boundaries -- Ask first: changes to `Directory.Build.props`, package references, target frameworks, or the public API of `Dax.Formatter`, which is a published package. +- Ask first: changes to `Directory.Build.props`, package references, target frameworks, or the public API of `Dax.Formatter`, which is a published package. `PublicApiTests` fails when the public API changes: update `tests/Dax.Formatter.Tests/PublicApi.approved.txt` only after the change is approved. - Never: edit `global.json` or `nuget.config` to make a build pass. - Never: commit the strong-name key `src/Dax.Formatter/DaxFormatter.snk`; `.gitignore` ignores it. -- Never: delete `samples/Directory.Build.props` or `samples/Directory.Build.targets`. They contain only ``, so the samples don't inherit the build settings of `dotnet/`; an empty file fails with MSB4024. - Never: run `dotnet format`, lower `AnalysisMode` or `AnalysisLevel`, or add a broad `NoWarn` to get a clean build. +- Never: call the network from a test outside `Live/`: use `FormatterHarness` and the responders of `Respond`, as the existing tests do. - Always: follow the root `.editorconfig` (C# style, indentation, encoding) in the lines you change; don't reformat the rest of a file. ## When you change X, update Y -- `version.json` → read the [pitfall](#pitfalls) below first; after the change, check with the version command above that a commit under `src/Dax.Formatter` still raises the version. +- `version.json` → the version rules of [ADR-0006](../docs/decisions/0006-write-the-dax-formatter-package-version-by-hand.md), in short: + - `master` holds the next version to publish, three numbers written by hand; + - right after a release, a one-line pull request raises the patch number (`2.0.0` → `2.0.1`); + - a pull request that adds a feature sets the minor number (`2.1.0`), one with a breaking change the major number; + - a preview is written out: `2.0.0-beta.1`, `2.0.0-beta.2`, then `2.0.0`. - The `.snk` path in `Directory.Build.props` → the path where `dotnet-release-dax-formatter.yml` writes the key, and the other way round: a mismatch builds an unsigned package without an error. -- The public API or the behavior of the client → `README.md` in this folder, the NuGet package readme, written for package users and packed into the package. +- The public API or the behavior of the client → [`docs/design/client-api.md`](../docs/design/client-api.md), which the clients of other languages port, and `README.md` in this folder, the NuGet package readme, written for package users and packed into the package. +- A C# code block of `README.md` → the region of the same name in `tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs`, and the other way round: `ReadmeTests` fails when a block and its region differ, and the test around the region runs it. The examples of the package live only there: there is no sample project. +- What the client sends or expects from the service → the fixtures in `tests/Dax.Formatter.Tests/Fixtures/`, with answers recorded from the service, never written by hand; then run the live tests. - A new project → `src/`, `tests/` or `samples/` ([ADR-0001](../docs/decisions/0001-organize-the-repository-by-language.md), [ADR-0003](../docs/decisions/0003-keep-one-net-solution-with-role-folders.md)); libraries and tests go into `Dax.Formatter.sln`. A new test project also goes into the test step of `dotnet-ci.yml` and of the release workflow, which name the test project they run. ## Pitfalls -- `version.json` must never have the same content as `git show 6df1bf0^:version.json`, the root `version.json` before the move to `dotnet/`, whose path filter is `src/Dax.Formatter`. While the two are identical, NBGV resolves the path filter from the old root: commits under `dotnet/src/Dax.Formatter` don't raise the version, and the computed version is one already published on nuget.org. The two differ only in how the filter is written, so it stays `./src/Dax.Formatter`. +- A commit under `src/Dax.Formatter` no longer raises the version of the package: it raises only the fourth number of the file version. The check after a change of `version.json` is that, on an up-to-date `master`, the version command above prints the version written in `version.json`. +- `version.json` must never have the same content as `git show 6df1bf0^:version.json`, the root `version.json` before the move to `dotnet/`, whose version is `1.2` and whose path filter is `src/Dax.Formatter`. While the two are identical, NBGV resolves the path filter from the old root and computes the height from there. The path filter stays `./src/Dax.Formatter`. +- The library builds for `netstandard2.0` and `net10.0`, and the tests run it on .NET Framework too. An API that only .NET 10 has needs an `#if NET` branch or a polyfill in `src/Dax.Formatter/Polyfills/`, and the analyzers of one target can ask for what the other lacks: build both before trusting a fix. +- In `ReadmeSamples.cs` the name `DaxFormatterClient` is an alias of `ReadmeClient`, declared inside the namespace. Outside the namespace the alias loses to the real type, and the samples would call the live service. ## Conventions -- A new test that doesn't need the service doesn't call it. +- C# follows the root `.editorconfig` and the analyzers at `AnalysisMode=all`: fix a warning, don't suppress it. The one suppression is `CA2007` in `ReadmeSamples.cs`, whose regions are the code of the readme. +- Internal types are `internal sealed`, in the folder of their responsibility ([`client-api.md`](../docs/design/client-api.md#code-and-tests)); public types are in the root folder and in the `Dax.Formatter` namespace. +- One test class for each production class, at the same path; test names are `Method_Scenario_Expected`. In a test, `ConfigureAwait(true)` satisfies both CA2007 and xUnit1030. +- The test packages stay as they are: xUnit 2 with fakes written by hand, no mocking library. From 8a29b09aca452b3e7f929674393d4dee6342ed12 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:19:39 +0100 Subject: [PATCH 13/29] fix(dotnet): send the package version in the User-Agent header - drop the fourth number of the informational version, which counts commits since the version is written by hand, and its commit id --- .../Configuration/CallerIdentity.cs | 27 ++++++++++++------- .../Configuration/CallerIdentityTests.cs | 17 +++++++++++- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs index d1c47b0..6040a00 100644 --- a/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs +++ b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs @@ -50,23 +50,30 @@ private static List CreateUserAgent(string? applicationN products.Add(new ProductInfoHeaderValue(application, ToToken(applicationVersion))); } - products.Add(new ProductInfoHeaderValue(LibraryName, ToToken(GetLibraryVersion()))); + var assembly = typeof(CallerIdentity).Assembly; + var informational = assembly.GetCustomAttribute()?.InformationalVersion; + var libraryVersion = informational is null ? null : ToPackageVersion(informational); + + products.Add(new ProductInfoHeaderValue(LibraryName, ToToken(libraryVersion))); products.Add(new ProductInfoHeaderValue(ToComment(RuntimeInformation.FrameworkDescription))); return products; } - private static string? GetLibraryVersion() + /// + /// Gets the version of the package from the informational version that the build stamps on the assembly, + /// such as 2.0.0.5-beta.1+0123abc: without the commit id, and without the fourth number, which counts + /// commits and is not part of the package version. + /// + public static string ToPackageVersion(string informationalVersion) { - var assembly = typeof(CallerIdentity).Assembly; - var version = assembly.GetCustomAttribute()?.InformationalVersion; - if (version is null) - { - return assembly.GetName().Version?.ToString(); - } + var version = informationalVersion.Split('+')[0]; + var parts = version.Split(['-'], 2); + + var numbers = parts[0].Split('.'); + var core = numbers.Length > 3 ? string.Join(".", numbers, 0, 3) : parts[0]; - // The informational version ends with the commit id as build metadata, which says nothing to the service. - return version.Split('+')[0]; + return parts.Length > 1 ? core + "-" + parts[1] : core; } private static string? NullIfBlank(string? value) diff --git a/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs b/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs index b551b0b..8d34605 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs @@ -13,7 +13,22 @@ public void Create_NameAndVersion_BuildsTheUserAgent() var userAgent = string.Join(" ", identity.UserAgent); - Assert.Matches(new Regex(@"^Contoso/1\.2\.3 Dax\.Formatter/[0-9]+\.[0-9]+\.[0-9]+\S* \([^()]+\)$"), userAgent); + Assert.Matches( + new Regex(@"^Contoso/1\.2\.3 Dax\.Formatter/[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)? \([^()]+\)$"), userAgent); + } + + [Theory] + [InlineData("2.0.0.0+ed2a1ca742", "2.0.0")] + [InlineData("2.0.1.7+ed2a1ca742", "2.0.1")] + [InlineData("2.1.0.3-beta.1+ed2a1ca742", "2.1.0-beta.1")] + [InlineData("2.0.0-beta.2", "2.0.0-beta.2")] + [InlineData("2.0.0", "2.0.0")] + [InlineData("2.0", "2.0")] + public void ToPackageVersion_InformationalVersion_DropsTheHeightAndTheCommit(string informational, string expected) + { + var version = CallerIdentity.ToPackageVersion(informational); + + Assert.Equal(expected, version); } [Fact] From 32fc7de56f85aa07f660baae822ef6b9a90d5c4f Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 12:34:38 +0100 Subject: [PATCH 14/29] refactor(dotnet): simplify the client after a review pass - chain the public constructors instead of repeating their arguments - read the library version from the constant that the build generates, not from the assembly attribute - let the plan of a call write the texts of a request under their headers, so that the run only schedules - share the answers of the fake service between the echo and the readme fakes, and hold answers until enough requests arrived with one responder - test the progress lock from several threads: the old test ran its requests one after the other and passed without the lock --- .../src/Dax.Formatter/Batching/BatchPlan.cs | 19 +++++++ dotnet/src/Dax.Formatter/Batching/BatchRun.cs | 12 +---- .../Configuration/CallerIdentity.cs | 4 +- .../src/Dax.Formatter/DaxFormatterClient.cs | 6 +-- .../Transport/FormatterTransport.cs | 6 ++- .../Dax.Formatter/Transport/RetryingSender.cs | 9 ++-- .../Batching/BatchPlannerTests.cs | 19 +++++++ .../Batching/BatchRunTests.cs | 52 ++++++------------- .../Batching/ProgressReporterTests.cs | 29 ++--------- .../Dax.Formatter.Tests/Fakes/EchoService.cs | 39 +++++++++----- .../Dax.Formatter.Tests/Fakes/Respond.cs | 15 ++++-- .../Fixtures/FixtureFile.cs | 11 ++-- .../Live/LiveServiceTests.cs | 2 +- .../Readme/ReadmeService.cs | 36 +++++++------ .../Results/ResultMapperTests.cs | 13 ----- .../Transport/RetryPolicyTests.cs | 18 +++---- 16 files changed, 142 insertions(+), 148 deletions(-) diff --git a/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs b/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs index f08f2a8..13ee636 100644 --- a/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs +++ b/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs @@ -35,4 +35,23 @@ public string GetText(int index) { return _headers?[index]; } + + /// Gets the texts of a request as they travel, each under its header. + /// + /// The texts get their headers only when a request is written, so that a large call does not hold a second + /// copy of every text. + /// + public List GetTextsToSend(Chunk chunk) + { + var dax = new List(chunk.Count); + for (var position = 0; position < chunk.Count; position++) + { + var index = chunk[position]; + var text = _texts[index]; + var header = GetHeader(index); + dax.Add(header is null ? text : header.AddTo(text)); + } + + return dax; + } } diff --git a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs index c619c2f..6f8afae 100644 --- a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs +++ b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs @@ -148,19 +148,9 @@ private async Task FormatChunkAsync(Chunk chunk, CancellationToken cancellationT _progress.Report(chunk.Count); } - // The texts get their headers only here, so that a large call does not hold a second copy of every text. private FormatRequest CreateRequest(Chunk chunk) { - var dax = new List(chunk.Count); - for (var position = 0; position < chunk.Count; position++) - { - var index = chunk[position]; - var text = _plan.GetText(index); - var header = _plan.GetHeader(index); - dax.Add(header is null ? text : header.AddTo(text)); - } - - var body = _bodyWriter.Write(dax, _settings); + var body = _bodyWriter.Write(_plan.GetTextsToSend(chunk), _settings); return new FormatRequest(body, chunk.Count, chunk.FirstIndex, chunk.LastIndex, _operationId); } diff --git a/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs index 6040a00..9b0269a 100644 --- a/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs +++ b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs @@ -50,9 +50,7 @@ private static List CreateUserAgent(string? applicationN products.Add(new ProductInfoHeaderValue(application, ToToken(applicationVersion))); } - var assembly = typeof(CallerIdentity).Assembly; - var informational = assembly.GetCustomAttribute()?.InformationalVersion; - var libraryVersion = informational is null ? null : ToPackageVersion(informational); + var libraryVersion = ToPackageVersion(ThisAssembly.AssemblyInformationalVersion); products.Add(new ProductInfoHeaderValue(LibraryName, ToToken(libraryVersion))); products.Add(new ProductInfoHeaderValue(ToComment(RuntimeInformation.FrameworkDescription))); diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs index 7d5729c..64a3df3 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs @@ -22,7 +22,7 @@ public class DaxFormatterClient /// uses an that all such instances share. /// public DaxFormatterClient() - : this(httpClient: null, ClientSettings.From(new DaxFormatterClientOptions()), TaskDelay.Instance, BatchLimits.Default) + : this(new DaxFormatterClientOptions()) { } @@ -45,7 +45,7 @@ public DaxFormatterClient(DaxFormatterClientOptions options) /// ignores its . /// public DaxFormatterClient(HttpClient httpClient) - : this(Required(httpClient), ClientSettings.From(new DaxFormatterClientOptions()), TaskDelay.Instance, BatchLimits.Default) + : this(httpClient, new DaxFormatterClientOptions()) { } @@ -59,7 +59,7 @@ public DaxFormatterClient(HttpClient httpClient) /// /// The options, which are copied. public DaxFormatterClient(HttpClient httpClient, DaxFormatterClientOptions options) - : this(Required(httpClient), ClientSettings.From(options), TaskDelay.Instance, BatchLimits.Default) + : this(httpClient, options, TaskDelay.Instance, BatchLimits.Default) { } diff --git a/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs index 30cf28b..ff06ae6 100644 --- a/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs +++ b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs @@ -12,7 +12,9 @@ internal sealed class FormatterTransport private const string RequestIdHeader = "DaxFormatter-Request-Id"; private const string OperationIdHeader = "DaxFormatter-Operation-Id"; - private static readonly MediaTypeWithQualityHeaderValue s_json = new("application/json"); + private const string JsonMediaType = "application/json"; + + private static readonly MediaTypeWithQualityHeaderValue s_json = new(JsonMediaType); private readonly HttpClient _httpClient; private readonly Uri _formatUri; @@ -79,7 +81,7 @@ private HttpRequestMessage CreateMessage(FormatRequest request) } message.Content = new ByteArrayContent(request.Body); - message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; + message.Content.Headers.ContentType = new MediaTypeHeaderValue(JsonMediaType) { CharSet = "utf-8" }; return message; } diff --git a/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs b/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs index 8e5b954..ef06d7f 100644 --- a/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs +++ b/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs @@ -34,7 +34,7 @@ public async Task SendAsync(FormatRequest request, CancellationTo if (!_policy.TryGetDelay(result, attempt, request.RequestId, out var delay)) { - throw CreateException(request, result, attempt); + throw CreateException(request, result, result.Detail, attempt); } await _delay.WaitAsync(delay, cancellationToken).ConfigureAwait(false); @@ -42,9 +42,12 @@ public async Task SendAsync(FormatRequest request, CancellationTo } } - private static DaxFormatterException CreateException(FormatRequest request, AttemptResult failure, int attempts) + private static DaxFormatterException CreateException( + FormatRequest request, + AttemptResult failure, + string detail, + int attempts) { - var detail = failure.Detail ?? "the reason is not known"; if (attempts > 1) { detail = FormattableString.Invariant($"{detail}, after {attempts} attempts"); diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs index 4939a40..fcdf9f9 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs @@ -1,12 +1,17 @@ using Dax.Formatter.Batching; using Dax.Formatter.Configuration; using Dax.Formatter.Expressions; +using Dax.Formatter.Tests.Fixtures; using Xunit; namespace Dax.Formatter.Tests.Batching; public class BatchPlannerTests { + private const string Fixture = "format-results.json"; + + public static IEnumerable FixtureCases => FixtureFile.CaseNames(Fixture); + [Theory] [InlineData(5, 2, "0,1|2,3|4")] [InlineData(4, 2, "0,1|2,3")] @@ -71,6 +76,20 @@ public void Plan_TextsSentAsTheyAre_HaveNoHeader() Assert.Null(plan.GetHeader(0)); } + [Theory] + [MemberData(nameof(FixtureCases))] + public void Plan_FixtureText_SendsItAsTheServiceReceivedIt(string name) + { + var testCase = FixtureFile.Case(Fixture, name); + string[] texts = [testCase.GetProperty("text").GetString()!]; + + var plan = BatchPlanner.Plan(texts, FixtureOptions.ReadKind(testCase), BatchLimits.Default); + + var chunk = Assert.Single(plan.Chunks); + var sent = Assert.Single(plan.GetTextsToSend(chunk)); + Assert.Equal(testCase.GetProperty("sent").GetString(), sent); + } + [Fact] public void Plan_Chunk_KnowsItsFirstAndLastText() { diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs index 7838c6d..e250ed6 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs @@ -14,18 +14,8 @@ public class BatchRunTests [Fact] public async Task FormatBatchAsync_AnswersOutOfOrder_ReturnsTheResultsInTheOrderOfTheTexts() { - var lastArrived = NewSignal(); - Responder responder = async (request, cancellationToken) => - { - // The first two requests are answered only after the third one has arrived. - if (request.Number == 2) - { - lastArrived.TrySetResult(true); - } - - await lastArrived.Task.ConfigureAwait(false); - return await Respond.Echo(request, cancellationToken).ConfigureAwait(false); - }; + // The first two requests are answered only after the third one has arrived. + var responder = Respond.OnceArrived(3, Respond.Echo); using var harness = new FormatterHarness( responder, options => options.MaxConcurrentRequests = 3, s_twoTextsPerRequest); @@ -41,18 +31,8 @@ public async Task FormatBatchAsync_AnswersOutOfOrder_ReturnsTheResultsInTheOrder [InlineData(3)] public async Task FormatBatchAsync_MoreRequestsThanAllowedAtOnce_KeepsToTheLimit(int maxConcurrentRequests) { - var enoughArrived = NewSignal(); - Responder responder = async (request, cancellationToken) => - { - // Nothing is answered until as many requests as the limit allows are in progress. - if (request.Number == maxConcurrentRequests - 1) - { - enoughArrived.TrySetResult(true); - } - - await enoughArrived.Task.ConfigureAwait(false); - return await Respond.Echo(request, cancellationToken).ConfigureAwait(false); - }; + // Nothing is answered until as many requests as the limit allows are in progress. + var responder = Respond.OnceArrived(maxConcurrentRequests, Respond.Echo); using var harness = new FormatterHarness( responder, options => options.MaxConcurrentRequests = maxConcurrentRequests, s_oneTextPerRequest); @@ -77,18 +57,13 @@ public async Task FormatBatchAsync_RequestsOfOneCall_ShareTheOperationIdOnly() [Fact] public async Task FormatBatchAsync_OneRequestFails_StopsTheOthersAndThrowsItsFailure() { - var allArrived = NewSignal(); - Responder responder = async (request, cancellationToken) => + // Once the three requests are in progress, the one that starts with "c" fails and the others never answer. + Responder failOne = (request, cancellationToken) => { - if (request.Number == 2) - { - allArrived.TrySetResult(true); - } - - await allArrived.Task.ConfigureAwait(false); var answer = request.Dax[0] == "c" ? Respond.Status(HttpStatusCode.BadRequest) : Respond.Hang; - return await answer(request, cancellationToken).ConfigureAwait(false); + return answer(request, cancellationToken); }; + var responder = Respond.OnceArrived(3, failOne); using var harness = new FormatterHarness( responder, options => options.MaxConcurrentRequests = 3, s_twoTextsPerRequest); @@ -178,8 +153,15 @@ public async Task FormatBatchAsync_ResultWithoutTheHeaderOfTheClient_FailsAndNam Assert.Equal(Respond.ServiceRequestId, exception.ServiceRequestId); } - private static TaskCompletionSource NewSignal() + [Fact] + public async Task FormatBatchAsync_BlankTexts_CountsThemBeforeTheFirstRequest() { - return new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var progress = new ListProgress(); + using var harness = new FormatterHarness( + Respond.Echo, options => options.MaxConcurrentRequests = 1, s_oneTextPerRequest); + + await harness.Client.FormatBatchAsync(["", "a", "b", " "], progress: progress).ConfigureAwait(true); + + Assert.Equal([(2, 4), (3, 4), (4, 4)], progress.Reports); } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs index 84b539b..bdbbe98 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs @@ -1,5 +1,4 @@ using Dax.Formatter.Batching; -using Dax.Formatter.Configuration; using Dax.Formatter.Tests.Fakes; using Xunit; @@ -41,33 +40,13 @@ public void Report_NoReceiver_DoesNothing() } [Fact] - public async Task FormatBatchAsync_BlankTexts_CountsThemBeforeTheFirstRequest() + public void Report_FromSeveralThreads_NeverReportsFewerTextsThanBefore() { var progress = new ListProgress(); - using var harness = new FormatterHarness( - Respond.Echo, - options => options.MaxConcurrentRequests = 1, - new BatchLimits(maxTexts: 1, maxCharacters: 1000)); + var reporter = new ProgressReporter(progress, total: 2000); - await harness.Client.FormatBatchAsync(["", "a", "b", " "], progress: progress).ConfigureAwait(true); + Parallel.For(0, 2000, _ => reporter.Report(1)); - Assert.Equal([(2, 4), (3, 4), (4, 4)], progress.Reports); - } - - [Fact] - public async Task FormatBatchAsync_RequestsInParallel_NeverReportsFewerTextsThanBefore() - { - var progress = new ListProgress(); - var texts = Enumerable.Range(0, 40).Select(number => "EVALUATE T" + number); - using var harness = new FormatterHarness( - Respond.Echo, - options => options.MaxConcurrentRequests = 4, - new BatchLimits(maxTexts: 3, maxCharacters: 1000)); - - await harness.Client.FormatBatchAsync(texts, progress: progress).ConfigureAwait(true); - - var completed = progress.Reports.Select(report => report.Completed).ToList(); - Assert.Equal(completed.OrderBy(count => count), completed); - Assert.Equal((40, 40), progress.Reports[progress.Reports.Count - 1]); + Assert.Equal(Enumerable.Range(1, 2000), progress.Reports.Select(report => report.Completed)); } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs index 05b522a..6f47cc6 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs @@ -26,35 +26,46 @@ public static string Answer(IReadOnlyList dax) return results.ToJsonString(); } - private static JsonObject AnswerOne(string text) + /// Gets the answer for one text. + public static JsonObject AnswerOne(string text) { var marker = text.IndexOf(ErrorMarker, StringComparison.Ordinal); - if (marker >= 0) + if (marker < 0) { - return new JsonObject - { - ["formatted"] = string.Empty, - ["errors"] = new JsonArray(CreateError(text, marker)), - }; + return Formatted(Format(text)); } + var before = text.Substring(0, marker); + var lineStart = before.LastIndexOf('\n') + 1; + var line = before.Count(character => character == '\n'); + + return Error(line, ToServiceColumn(before.Substring(lineStart))); + } + + /// Gets the answer of the service for a text that it formatted. + public static JsonObject Formatted(string formatted) + { return new JsonObject { - ["formatted"] = Format(text), + ["formatted"] = formatted, ["errors"] = new JsonArray(), }; } - private static JsonObject CreateError(string text, int position) + /// Gets the answer of the service for a text with a syntax error at a position. + public static JsonObject Error(int line, int column) { - var before = text.Substring(0, position); - var lineStart = before.LastIndexOf('\n') + 1; + var error = new JsonObject + { + ["line"] = line, + ["column"] = column, + ["message"] = ErrorMessage, + }; return new JsonObject { - ["line"] = before.Count(character => character == '\n'), - ["column"] = ToServiceColumn(before.Substring(lineStart)), - ["message"] = ErrorMessage, + ["formatted"] = string.Empty, + ["errors"] = new JsonArray(error), }; } diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs index 75b1470..c8d4198 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs @@ -58,12 +58,21 @@ public static Responder Throw(Func createException) return (_, _) => Task.FromException(createException()); } - /// Answers with once completes. - public static Responder After(Task gate, Responder then) + /// + /// Holds every answer until requests have arrived, so that they are in progress at + /// the same time, then answers with . + /// + public static Responder OnceArrived(int count, Responder then) { + var arrived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); return async (request, cancellationToken) => { - await gate.ConfigureAwait(false); + if (request.Number == count - 1) + { + arrived.TrySetResult(true); + } + + await arrived.Task.ConfigureAwait(false); return await then(request, cancellationToken).ConfigureAwait(false); }; } diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs index dcabe10..a5b4e08 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs @@ -8,11 +8,11 @@ namespace Dax.Formatter.Tests.Fixtures; /// internal static class FixtureFile { - public static JsonElement Load(string fileName) + public static JsonElement.ArrayEnumerator Cases(string fileName) { using var stream = OpenResource("Fixtures/" + fileName); using var document = JsonDocument.Parse(stream); - return document.RootElement.Clone(); + return document.RootElement.Clone().GetProperty("cases").EnumerateArray(); } /// Gets the names of the cases of a file, which a theory takes as its data. @@ -26,7 +26,7 @@ public static JsonElement Case(string fileName, string name) return Cases(fileName).Single(testCase => testCase.GetProperty("name").GetString() == name); } - public static Stream OpenResource(string name) + private static Stream OpenResource(string name) { var stream = typeof(FixtureFile).Assembly.GetManifestResourceStream(name); return stream ?? throw new InvalidOperationException($"The embedded resource '{name}' is missing."); @@ -46,9 +46,4 @@ public static string ReadText(string name) return string.Join("\n", lines); } - - private static JsonElement.ArrayEnumerator Cases(string fileName) - { - return Load(fileName).GetProperty("cases").EnumerateArray(); - } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs index cbdf329..2c0af30 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs @@ -111,7 +111,7 @@ public async Task FormatAsync_SemicolonAndCommaWithEveryModelProperty_FormatsThe private static async Task AssertFixtureResultsAsync(DaxKind kind) { - var cases = FixtureFile.Load(Fixture).GetProperty("cases").EnumerateArray() + var cases = FixtureFile.Cases(Fixture) .Where(testCase => FixtureOptions.ReadKind(testCase) == kind) .ToList(); var texts = cases.Select(testCase => testCase.GetProperty("text").GetString()!); diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs index ce9973f..3607fbe 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs @@ -34,25 +34,27 @@ internal static class ReadmeService private static string Answer(IReadOnlyList dax) { - var echoed = JsonNode.Parse(EchoService.Answer(dax))!.AsArray(); - for (var index = 0; index < dax.Count; index++) + var results = new JsonArray(); + foreach (var text in dax) { - if (s_formatted.TryGetValue(dax[index], out var formatted)) - { - echoed[index] = new JsonObject { ["formatted"] = formatted, ["errors"] = new JsonArray() }; - } - else if (s_errors.TryGetValue(dax[index], out var position)) - { - var error = new JsonObject - { - ["line"] = position.Line, - ["column"] = position.Column, - ["message"] = EchoService.ErrorMessage, - }; - echoed[index] = new JsonObject { ["formatted"] = string.Empty, ["errors"] = new JsonArray(error) }; - } + results.Add(AnswerOne(text)); } - return echoed.ToJsonString(); + return results.ToJsonString(); + } + + private static JsonObject AnswerOne(string text) + { + if (s_formatted.TryGetValue(text, out var formatted)) + { + return EchoService.Formatted(formatted); + } + + if (s_errors.TryGetValue(text, out var position)) + { + return EchoService.Error(position.Line, position.Column); + } + + return EchoService.AnswerOne(text); } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs b/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs index f73d256..1d3ae6b 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs @@ -28,19 +28,6 @@ public void TryMap_FixtureAnswer_ReturnsTheExpectedResult(string name) AssertMatches(testCase.GetProperty("result"), result!); } - [Theory] - [MemberData(nameof(Cases))] - public void AddTo_FixtureText_GivesTheTextThatWasSent(string name) - { - var testCase = FixtureFile.Case(Fixture, name); - var text = testCase.GetProperty("text").GetString()!; - var isExpression = FixtureOptions.ReadKind(testCase) == DaxKind.Expression; - - var sent = isExpression ? ExpressionHeader.For(text).AddTo(text) : text; - - Assert.Equal(testCase.GetProperty("sent").GetString(), sent); - } - [Theory] [InlineData("{\"formatted\":\"EVALUATE\\r\\nSales\\r\\n\",\"errors\":null}", "EVALUATE\r\nSales")] [InlineData("{\"formatted\":\"EVALUATE\\r\\nSales\\r\\n\"}", "EVALUATE\r\nSales")] diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs index 7bf1e4f..4849352 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs @@ -96,8 +96,7 @@ public void TryGetDelay_FailureThatIsNotTransient_ReturnsFalse() public void TryGetDelay_RetryAfterLongerThanTheBackoff_WaitsAsLongAsAsked(int seconds, int expectedMilliseconds) { var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); - using var response = CreateBusyResponse(seconds); - var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + var failure = Busy(retryAfterSeconds: seconds); var retry = policy.TryGetDelay(failure, 1, s_requestId, out var delay); @@ -109,8 +108,7 @@ public void TryGetDelay_RetryAfterLongerThanTheBackoff_WaitsAsLongAsAsked(int se public void TryGetDelay_RetryAfterShorterThanTheBackoff_KeepsTheBackoff() { var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); - using var response = CreateBusyResponse(seconds: 0); - var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + var failure = Busy(retryAfterSeconds: 0); policy.TryGetDelay(failure, 1, s_requestId, out var delay); @@ -121,8 +119,7 @@ public void TryGetDelay_RetryAfterShorterThanTheBackoff_KeepsTheBackoff() public void TryGetDelay_RetryAfterLongerThanTheRequestTimeout_ReturnsFalse() { var policy = new RetryPolicy(maxRetries: 2, s_requestTimeout); - using var response = CreateBusyResponse(seconds: 61); - var failure = AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + var failure = Busy(retryAfterSeconds: 61); var retry = policy.TryGetDelay(failure, 1, s_requestId, out _); @@ -134,10 +131,11 @@ private static AttemptResult Timeout() return AttemptResult.NoResponse(DaxFormatterFailureReason.Timeout, "detail", error: null); } - private static HttpResponseMessage CreateBusyResponse(int seconds) + private static AttemptResult Busy(int retryAfterSeconds) { - var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); - response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(seconds)); - return response; + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(retryAfterSeconds)); + + return AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); } } From 9447543d483a25bbdcaa1a51ca38f9e58f6f8357 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 13:09:36 +0100 Subject: [PATCH 15/29] fix(dotnet): handle the edge cases found in review - let a cancellation thrown by the progress receiver of the caller reach the caller, instead of failing the call with an unknown reason - name the request timeout in the message only when its own timer ended the attempt, not the timeout of the HttpClient of the caller - read a response without content as an invalid response on .NET Framework, where it was a null reference - skip a UTF-8 byte order mark before the JSON of an answer - use the default handler where sockets are not supported, as in a browser, where the shared HttpClient could not be created - throw for a cancelled token also when a batch has no texts - record in the fake handler whether a request refuses Expect 100-continue, so that the test can fail without that line --- dotnet/src/Dax.Formatter/Batching/BatchRun.cs | 5 ++- .../src/Dax.Formatter/DaxFormatterClient.cs | 1 + .../Transport/FormatterTransport.cs | 9 ++++- .../Dax.Formatter/Transport/ResponseReader.cs | 24 +++++++++++- .../Transport/SharedHttpClient.cs | 6 +++ .../Batching/BatchRunTests.cs | 37 +++++++++++++++++++ .../Fakes/RecordedRequest.cs | 7 ++++ .../Transport/FormatterTransportTests.cs | 21 ++++++++++- .../Transport/ResponseReaderTests.cs | 22 +++++++++++ 9 files changed, 124 insertions(+), 8 deletions(-) diff --git a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs index 6f8afae..4a4023e 100644 --- a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs +++ b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs @@ -106,9 +106,10 @@ private async Task WorkAsync() { Interlocked.CompareExchange(ref _failure, exception, null); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { - // The caller or a failed request stopped the call: RunAsync tells which. + // The caller or a failed request stopped the call: RunAsync tells which. A cancellation that comes + // from elsewhere, such as the progress receiver of the caller, is not swallowed. } finally { diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs index 64a3df3..bf28809 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs @@ -217,6 +217,7 @@ private async Task> FormatManyAsync( IProgress? progress, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); if (texts.Length == 0) { return []; diff --git a/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs index ff06ae6..c32aa7e 100644 --- a/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs +++ b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs @@ -54,8 +54,13 @@ public async Task SendAsync(FormatRequest request, CancellationTo // or the Timeout of an HttpClient that the caller supplied. cancellationToken.ThrowIfCancellationRequested(); - var seconds = _requestTimeout.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture); - var detail = $"the service did not answer within {seconds} seconds"; + var detail = "the request timed out before the service answered"; + if (timeout.IsCancellationRequested) + { + var seconds = _requestTimeout.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture); + detail = $"the service did not answer within {seconds} seconds"; + } + return AttemptResult.NoResponse(DaxFormatterFailureReason.Timeout, detail, exception); } catch (HttpRequestException exception) diff --git a/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs b/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs index a92518f..44d5a1c 100644 --- a/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs +++ b/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs @@ -32,7 +32,7 @@ public static async Task ReadAsync( List? items; try { - items = JsonSerializer.Deserialize(content, WireJsonContext.Default.ListFormatResponseItem); + items = Parse(content); } catch (JsonException exception) { @@ -64,13 +64,33 @@ private static AttemptResult Invalid(string detail, HttpResponseMessage response return AttemptResult.Rejected(DaxFormatterFailureReason.InvalidResponse, detail, response, error); } + private static List? Parse(byte[] content) + { + // A byte order mark is not JSON, but an intermediary between the client and the service can add one. + ReadOnlySpan byteOrderMark = [0xEF, 0xBB, 0xBF]; + var json = content.AsSpan(); + if (json.StartsWith(byteOrderMark)) + { + json = json.Slice(byteOrderMark.Length); + } + + return JsonSerializer.Deserialize(json, WireJsonContext.Default.ListFormatResponseItem); + } + private static Task ReadContentAsync(HttpResponseMessage response, CancellationToken cancellationToken) { #if NET return response.Content.ReadAsByteArrayAsync(cancellationToken); #else - // The content is already in memory here, so a read that cannot be cancelled does not wait. cancellationToken.ThrowIfCancellationRequested(); + + // Before .NET 5 a response can have no content at all, when a handler of the caller builds it so. + if (response.Content is null) + { + return Task.FromResult(Array.Empty()); + } + + // The content is already in memory here, so a read that cannot be cancelled does not wait. return response.Content.ReadAsByteArrayAsync(); #endif } diff --git a/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs b/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs index c280f21..d16de48 100644 --- a/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs +++ b/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs @@ -26,6 +26,12 @@ private static HttpClient Create() #if NET private static HttpClient CreateWithPooledConnections() { + // In a browser there are no sockets: the default handler of the platform is the only one. + if (!SocketsHttpHandler.IsSupported) + { + return new HttpClient(); + } + SocketsHttpHandler? handler = null; try { diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs index e250ed6..53b391a 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs @@ -134,6 +134,32 @@ await Assert Assert.Empty(harness.Handler.Requests); } + [Fact] + public async Task FormatBatchAsync_NoTextsWithTokenAlreadyCancelled_Throws() + { + var cancelled = new CancellationToken(canceled: true); + using var harness = new FormatterHarness(Respond.Echo); + + await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatBatchAsync([], cancellationToken: cancelled)) + .ConfigureAwait(true); + } + + [Fact] + public async Task FormatBatchAsync_ProgressReceiverCancelsOnItsOwn_ThrowsTheExceptionOfTheReceiver() + { + using var harness = new FormatterHarness(Respond.Echo, limits: s_oneTextPerRequest); + var progress = new CancellingProgress(); + + var exception = await Assert + .ThrowsAnyAsync( + () => harness.Client.FormatBatchAsync(s_fiveTexts, progress: progress)) + .ConfigureAwait(true); + + Assert.Equal(CancellingProgress.Message, exception.Message); + } + [Fact] public async Task FormatBatchAsync_ResultWithoutTheHeaderOfTheClient_FailsAndNamesTheText() { @@ -164,4 +190,15 @@ public async Task FormatBatchAsync_BlankTexts_CountsThemBeforeTheFirstRequest() Assert.Equal([(2, 4), (3, 4), (4, 4)], progress.Reports); } + + // A receiver that cancels with a token of its own, which the client knows nothing about. + private sealed class CancellingProgress : IProgress + { + public const string Message = "The receiver of the progress cancelled."; + + public void Report(DaxFormatProgressInfo value) + { + throw new OperationCanceledException(Message); + } + } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs index 3720b60..691f951 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs @@ -17,6 +17,7 @@ public RecordedRequest(int number, HttpRequestMessage request, byte[] body) Uri = request.RequestUri; Body = body; ContentType = request.Content?.Headers.ContentType?.ToString(); + ExpectContinue = request.Headers.ExpectContinue; foreach (var header in request.Headers) { @@ -38,6 +39,12 @@ public RecordedRequest(int number, HttpRequestMessage request, byte[] body) public string? ContentType { get; } + /// + /// Gets what the request says about Expect: 100-continue. The header itself is written by the real + /// handler, which on .NET Framework adds it to a POST unless the request says no. + /// + public bool? ExpectContinue { get; } + public JsonElement Json { get; } public IReadOnlyList Dax => [.. Json.GetProperty("dax").EnumerateArray().Select(text => text.GetString()!)]; diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs index a06bc2e..c390b93 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs @@ -55,7 +55,7 @@ public async Task FormatAsync_AnyCall_AsksForJsonWithoutCompressionOrExpect() var request = Assert.Single(harness.Handler.Requests); Assert.Equal("application/json", request.GetHeader("Accept")); Assert.Null(request.GetHeader("Accept-Encoding")); - Assert.Null(request.GetHeader("Expect")); + Assert.False(request.ExpectContinue); } [Fact] @@ -89,7 +89,23 @@ public async Task FormatAsync_NoAnswerWithinTheRequestTimeout_FailsWithTimeout() } [Fact] - public async Task FormatAsync_TimeoutOfTheHttpClientOfTheCaller_FailsWithTimeout() + public async Task FormatAsync_NoAnswerWithinTheRequestTimeout_SaysHowLongItWaited() + { + using var harness = new FormatterHarness(Respond.Hang, options => + { + options.RequestTimeout = TimeSpan.FromMilliseconds(50); + options.MaxRetries = 0; + }); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Contains("within 0.05 seconds", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task FormatAsync_TimeoutOfTheHttpClientOfTheCaller_FailsWithTimeoutWithoutNamingTheRequestTimeout() { using var harness = new FormatterHarness( Respond.Throw(() => new TaskCanceledException("The request was canceled due to HttpClient.Timeout.")), @@ -100,6 +116,7 @@ public async Task FormatAsync_TimeoutOfTheHttpClientOfTheCaller_FailsWithTimeout .ConfigureAwait(true); Assert.Equal(DaxFormatterFailureReason.Timeout, exception.Reason); + Assert.DoesNotContain("60 seconds", exception.Message, StringComparison.Ordinal); } [Fact] diff --git a/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs index 6862db7..a0f565a 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs @@ -66,6 +66,28 @@ public async Task ReadAsync_NullInPlaceOfResults_IsAnInvalidResponse(string body Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); } + [Fact] + public async Task ReadAsync_ResponseWithoutContent_IsAnInvalidResponse() + { + using var response = new HttpResponseMessage(HttpStatusCode.OK); + + var result = await ResponseReader.ReadAsync(response, 1, CancellationToken.None).ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.InvalidResponse, result.Reason); + } + + [Fact] + public async Task ReadAsync_JsonAfterAByteOrderMark_ReturnsTheResults() + { + byte[] body = [0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes(TwoResults)]; + using var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) }; + + var result = await ResponseReader.ReadAsync(response, 2, CancellationToken.None).ConfigureAwait(true); + + Assert.True(result.Succeeded); + Assert.Equal(2, result.Items!.Count); + } + [Fact] public async Task ReadAsync_NoContentStatus_IsAnInvalidResponse() { From bfbd1ff80dac0fd70f23194944c3244bf4753320 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 13:09:36 +0100 Subject: [PATCH 16/29] docs(dotnet): correct the typed client registration in the readme - register the client with a factory: AddHttpClient cannot choose between the two constructors that take an HttpClient - say that on .NET Framework the shared HttpClient has the connection limit of ServicePointManager, 2 by default - say that a literal null as second argument of FormatBatchAsync is ambiguous, and what to write in its place --- docs/design/client-api.md | 3 ++- dotnet/README.md | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/design/client-api.md b/docs/design/client-api.md index 3b39e20..26ae134 100644 --- a/docs/design/client-api.md +++ b/docs/design/client-api.md @@ -59,13 +59,14 @@ The client converts the [position that the service reports](rest-api.md#response - Retry: after a timeout, a network error and the statuses 408, 429, 500, 502, 503 and 504. Any other status and an invalid response fail at once. The wait starts at 0.8 seconds and doubles up to 60, varied by a quarter either way; a longer `Retry-After`, in seconds or as a date measured from the `Date` header of the same response, replaces it, and one longer than `RequestTimeout` fails the request at once. Each attempt sends the same body and the same request identifier. - The first request that fails after its retries stops the others, and the call fails with it. The message names the texts of that request by their indexes. - A request that timed out is not split in two: the service keeps working on an abandoned request, so smaller requests would add load when it is slow. -- Invalid responses: status 204, a body that is not the documented JSON, a number of results other than the number of texts sent, a null result. In a result, a null `errors` is no errors, and a null `formatted` without errors is an empty text; `formatted` is not read when there are errors. +- Invalid responses: status 204, a body that is not the documented JSON, a number of results other than the number of texts sent, a null result. A UTF-8 byte order mark before the JSON is skipped. In a result, a null `errors` is no errors, and a null `formatted` without errors is an empty text; `formatted` is not read when there are errors. ## Identity and transport - Each request has the [caller identity](rest-api.md#caller-identity) in its body, and the headers `User-Agent`, `DaxFormatter-Request-Id` (one for each request, the same in its retries) and `DaxFormatter-Operation-Id` (one for each call) ([headers](rest-api.md#endpoints)). - `User-Agent` is `/ Dax.Formatter/ ()`. The application name and version are cleaned into HTTP tokens, so `DAX Studio` becomes `DAX-Studio`; the body keeps them as they are. - Without an HTTP client from the caller, all the clients share one that lives as long as the process, has no timeout of its own and doesn't check certificate revocation; on .NET 10 it replaces its pooled connections every 5 minutes, so that a DNS change is seen ([guidelines](https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines)). Nothing is created before the first call. +- On .NET Framework the shared client is the plain default one, so it opens at most [`ServicePointManager.DefaultConnectionLimit`](https://learn.microsoft.com/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit) connections to the service, 2 unless the application changes it. A request beyond that waits for a connection while its timeout runs, which matters with `MaxConcurrentRequests` above 2 or with several calls at the same time. - An HTTP client from the caller is never changed or disposed. Its base address is ignored: every request has an absolute URI built from `Endpoint`. Its own timeout applies too, so the shorter one wins, and is reported as `Timeout`. - The server and database names of `ModelInfo` leave the client only as [hashes](rest-api.md#hashing-of-server-and-database-names). diff --git a/dotnet/README.md b/dotnet/README.md index 1cc1dfb..cd74144 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -175,7 +175,9 @@ Without an `HttpClient`, all the clients share one that lives as long as the pro var client = new DaxFormatterClient(httpClient); ``` -The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register the client as a typed client: `services.AddHttpClient()`. +The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register the client as a typed client with a factory, because more than one of its constructors takes an `HttpClient`: `services.AddHttpClient(httpClient => new DaxFormatterClient(httpClient))`. + +On .NET Framework the shared `HttpClient` opens at most [`ServicePointManager.DefaultConnectionLimit`](https://learn.microsoft.com/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit) connections to the service, which is 2 unless the application changes it. Raise that limit, or pass your own `HttpClient`, before you raise `MaxConcurrentRequests` or run several calls at the same time: a request that waits for a connection uses up its `RequestTimeout`. To replace the client in the tests of your application, derive from it and override `FormatAsync` and the `FormatBatchAsync` that takes strings: both are virtual, the one that takes items calls the one that takes strings, and the parameterless constructor does no work. `DaxFormatResult.Success` and `DaxFormatResult.Failure` create the results. @@ -204,6 +206,7 @@ What else changes: - The formatted text has no final line break. - For `DaxKind.Expression`, the position of an error refers to your text, not to the text with `[x] :=` before it. - A call with many texts no longer fails for its size: the client splits it. +- `FormatBatchAsync(texts, null)` doesn't compile, because a literal `null` fits both the options and the text selector of the other overload: leave the argument out, or write `options: null`. - 2.0 formats DAX only. In 1.x, `FormatAsync(string)` and `FormatAsync(DaxFormatterSingleRequest)` also formatted MDX. - The package no longer has a `net8.0` target: applications on .NET 8 and 9 use the .NET Standard 2.0 one. From 4bc2a82886e114a5eb9b687a09595d919656e9be Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 15:07:51 +0100 Subject: [PATCH 17/29] docs(dotnet): show one call for objects of different types The readme showed the batch call only with measures, which suggested one call for each type of object. - add a sample that formats measures and functions in one call, with items that carry the function that writes the result back - compile and run the sample in the readme tests --- dotnet/README.md | 32 +++++++++++ .../Readme/ReadmeSamples.cs | 53 +++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/dotnet/README.md b/dotnet/README.md index cd74144..dc1411d 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -59,6 +59,38 @@ Here `Measure` and `model` stand for the types of your application: any type wor - A blank text gets an empty formatted text, without a request. - `FormatBatchAsync` also takes plain strings: `await client.FormatBatchAsync(texts)`. +### Format objects of different types + +One call formats the objects of a model whatever their type, because `DaxKind.Expression` covers them all. Put them in one list, each with its DAX and a function that writes the formatted text back to it. + +```csharp +var items = new List<(string Expression, Action Update)>(); + +foreach (var measure in model.Measures) +{ + items.Add((measure.Expression, text => measure.Expression = text)); +} + +foreach (var function in model.Functions) +{ + items.Add((function.Expression, text => function.Expression = text)); +} + +var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + +var results = await client.FormatBatchAsync(items, item => item.Expression, options); + +foreach (var result in results) +{ + if (result.Succeeded) + { + result.Item.Update(result.FormattedText); + } +} +``` + +`Update` is not part of the client: it is the function you stored in the item, which the result gives back in `Item`. Only texts of the other kind need a call of their own, such as queries, which take `DaxKind.Auto`. + ### Options ```csharp diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs index cf9adc4..d0d5216 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -64,6 +64,44 @@ public async Task FormatBatchAsync_ModelObjectsSample_UpdatesTheMeasuresThatAreV Assert.Equal("DIVIDE ( [Sales Amount], [Total Cost] )", model.Measures[2].Expression); } + [Fact] + public async Task FormatBatchAsync_MixedObjectsSample_UpdatesTheObjectsOfEveryType() + { + var client = new DaxFormatterClient(); + var model = new Model(); + + #region MixedObjects + var items = new List<(string Expression, Action Update)>(); + + foreach (var measure in model.Measures) + { + items.Add((measure.Expression, text => measure.Expression = text)); + } + + foreach (var function in model.Functions) + { + items.Add((function.Expression, text => function.Expression = text)); + } + + var options = new DaxFormatOptions { Kind = DaxKind.Expression }; + + var results = await client.FormatBatchAsync(items, item => item.Expression, options); + + foreach (var result in results) + { + if (result.Succeeded) + { + result.Item.Update(result.FormattedText); + } + } + #endregion + + Assert.Equal("CALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )", model.Measures[0].Expression); + Assert.Equal("SUMX(Sales, Sales[Amount] *", model.Measures[1].Expression); + Assert.Equal( + "(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", model.Functions[0].Expression); + } + [Fact] public async Task FormatAsync_OptionsSample_SendsTheOptions() { @@ -236,5 +274,20 @@ private sealed class Model new Measure("Broken", "SUMX(Sales, Sales[Amount] *"), new Measure("Cost Ratio", "DIVIDE([Sales Amount], [Total Cost])"), ]; + + public List Functions { get; } = + [ + new Function("(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"), + ]; + } + + private sealed class Function + { + public Function(string expression) + { + Expression = expression; + } + + public string Expression { get; set; } } } From 958d7cacbc9520e14a41bd7e17135edf32221159 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 15:12:58 +0100 Subject: [PATCH 18/29] docs(dotnet): keep the package readme to the usage of the client The readme is for package users: the migration from 1.x, the limits of the service and the links to the design documents don't belong there. - remove the sections on migrating from 1.x and on the service limits - keep only the SQLBI Docs link in the additional documentation - drop the mentions of those sections from B-22 and ADR-0005 --- docs/backlog.md | 2 +- ...e-the-client-api-from-the-rest-contract.md | 2 +- dotnet/README.md | 39 ------------------- 3 files changed, 2 insertions(+), 41 deletions(-) diff --git a/docs/backlog.md b/docs/backlog.md index eadd831..80c47bb 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -29,4 +29,4 @@ Reports and requests from users stay in [GitHub Issues](https://github.com/sql-b - B-14 The MCP server says that `formatted` is null for invalid DAX, in the tool description in `typescript/packages/daxformatter-mcp/src/format-tool.ts` and in the comment of `formatted` in `src/daxformatter/types.ts`, while the service returns an empty string ([REST API, Response](design/rest-api.md#response)). Cost: an AI client that follows the tool description misses the empty string. Repay by fixing both texts, which raises the MCP server's version. - B-15 Releases are tied to `master` only by the branch guard of the release workflows: a run uses the workflow file of the commit it runs on ([Workflows](https://docs.github.com/en/actions/concepts/workflows-and-actions/workflows)), so a branch whose copy drops the guard runs with the repository secrets, and the nuget.org Trusted Publishing policy names the workflow file, not a branch. Cost: whoever can push a branch and run workflows can publish from it. Repay: remove the nuget.org policy for `release.yml`, the .NET release workflow's name before the move in `6df1bf0`; run each release job in a GitHub environment that only `master` can deploy to, which holds the release secrets and which the nuget.org policy names ([Trusted Publishing](https://learn.microsoft.com/en-us/nuget/nuget-org/trusted-publishing), [environments](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)). - B-16 Some files under `dotnet/` don't follow `.editorconfig`: a missing or unwanted byte order mark, no final newline, trailing whitespace, and tabs, including in `Dax.Formatter.sln`, which Visual Studio writes with tabs. Cost: saving one in an editor that applies `.editorconfig` puts changes unrelated to the edit in the diff. Repay with one commit that only normalizes these files, and a `[*.sln]` section with `indent_style = tab`. -- B-22 The service rejects three kinds of valid DAX with a syntax error: a function without parameters, a function parameter with a default value and, sent as the expression of a model object, an expression with `=>` inside a string or a comment ([client API](design/client-api.md#limits-of-the-service)). Cost: no client can format them, and each returns the syntax error to its caller. Repay in the service, which is outside this repository; then remove the limits from `client-api.md`, `rest-api.md` and the .NET package readme, and update the live test that pins them. +- B-22 The service rejects three kinds of valid DAX with a syntax error: a function without parameters, a function parameter with a default value and, sent as the expression of a model object, an expression with `=>` inside a string or a comment ([client API](design/client-api.md#limits-of-the-service)). Cost: no client can format them, and each returns the syntax error to its caller. Repay in the service, which is outside this repository; then remove the limits from `client-api.md` and `rest-api.md`, and update the live test that pins them. diff --git a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md index 45fa5a0..e984610 100644 --- a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md +++ b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md @@ -35,7 +35,7 @@ Chosen option: "A new API on a model of its own", because the work that every ca * Good, because a caller passes its objects and reads results: the header line, the match by index and the outcome check are no longer written in each tool. * Good, because a call with thousands of texts no longer depends on one request ([sql-bi/DaxFormatter#40](https://github.com/sql-bi/DaxFormatter/issues/40)). * Good, because the TypeScript and Python clients get a model to port, with test vectors that don't depend on a language. -* Bad, because every application on 1.x must change its code to move to 2.0; the package readme has a migration table. +* Bad, because every application on 1.x must change its code to move to 2.0. * Bad, because the client now knows some DAX: where strings, names and comments start and end, and what a function body looks like. A change of the DAX syntax there reaches the client. * Bad, because `Expression` depends on how the service writes its answer: the client sends a header line, expects it back, and removes it with the indentation that the service adds under a function header. A different answer is a failure, never a wrong text, and the live tests pin the answers. * Bad, because the client can't work around three limits of the service, which it returns as syntax errors ([`client-api.md`](../design/client-api.md#limits-of-the-service)). diff --git a/dotnet/README.md b/dotnet/README.md index dc1411d..d78b474 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -213,48 +213,9 @@ On .NET Framework the shared `HttpClient` opens at most [`ServicePointManager.De To replace the client in the tests of your application, derive from it and override `FormatAsync` and the `FormatBatchAsync` that takes strings: both are virtual, the one that takes items calls the one that takes strings, and the parameterless constructor does no work. `DaxFormatResult.Success` and `DaxFormatResult.Failure` create the results. -## Migrating from 1.x - -Version 2.0 replaces the whole API. The requests that 1.x exposed are gone: a call takes the text and the options, and returns results. - -| 1.x | 2.0 | -|---|---| -| `new DaxFormatterClient(application, version)` | `new DaxFormatterClient(new DaxFormatterClientOptions { ApplicationName = ..., ApplicationVersion = ... })` | -| `FormatAsync(string)`, `FormatAsync(DaxFormatterSingleRequest)` | `FormatAsync(text, options)` | -| `FormatAsync(IEnumerable)`, `FormatAsync(DaxFormatterMultipleRequest)` | `FormatBatchAsync(texts, options)`, or `FormatBatchAsync(items, textSelector, options)` | -| `[x] :=` written before an expression, and removed from the result | `DaxFormatOptions.Kind = DaxKind.Expression` | -| `MaxLineLength`, `SkipSpaceAfterFunctionName` | `DaxFormatOptions.LineStyle`, `DaxFormatOptions.SpacingStyle` | -| `ListSeparator`, `DecimalSeparator` | `DaxFormatOptions.SeparatorStyle` | -| `ServerName`, `DatabaseName`, `ServerVersion`, `DatabaseCompatibilityLevel` on the request | `DaxFormatOptions.ModelInfo`, where the compatibility level is a number | -| The enums `ServerType`, `ServerMode`, `ServerEdition`, `ServerLocation` | Strings; `DaxServerTypes` has the server types | -| `DaxFormatterResponse.Formatted`, empty when there are errors | `DaxFormatResult.FormattedText`, `null` when `Succeeded` is `false` | -| `DaxFormatterError` with nullable `Line` and `Column` | `DaxSyntaxError` | -| `HttpRequestException`, `TaskCanceledException` after 60 seconds | `DaxFormatterException` with a `Reason` | -| `IDaxFormatterClient` | Derive from `DaxFormatterClient`, whose methods are virtual | -| `Dispose()` | Nothing: the client is not disposable | - -What else changes: - -- The formatted text has no final line break. -- For `DaxKind.Expression`, the position of an error refers to your text, not to the text with `[x] :=` before it. -- A call with many texts no longer fails for its size: the client splits it. -- `FormatBatchAsync(texts, null)` doesn't compile, because a literal `null` fits both the options and the text selector of the other overload: leave the argument out, or write `options: null`. -- 2.0 formats DAX only. In 1.x, `FormatAsync(string)` and `FormatAsync(DaxFormatterSingleRequest)` also formatted MDX. -- The package no longer has a `net8.0` target: applications on .NET 8 and 9 use the .NET Standard 2.0 one. - -## Service limits - -The service, not the client, rejects these texts with a syntax error: - -- a function without parameters, such as `() => 1`; -- a function parameter with a default value, such as `(a, b = 1) => a + b`; -- with `DaxKind.Expression`, an expression that has `=>` inside a string or a comment. - ## Additional documentation - [SQLBI Docs](https://docs.sqlbi.com/dax-formatter/): the user documentation of DAX Formatter. -- [Client API](https://github.com/sql-bi/DaxFormatter/blob/master/docs/design/client-api.md): the behavior of the client in detail. -- [REST API](https://github.com/sql-bi/DaxFormatter/blob/master/docs/design/rest-api.md): the contract of the service that the client calls. ## Feedback From b831227b59acf847fff674a4238e1b8f2a3ab01e Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 17:06:19 +0100 Subject: [PATCH 19/29] refactor(dotnet): merge the client constructors that take an HttpClient Two public constructors took an HttpClient, so IHttpClientFactory could not pick one and services.AddHttpClient() threw. - replace them with DaxFormatterClient(HttpClient, options = null), where null means the default options; every existing call compiles - test the typed-client registration, with the options taken from the container, through Microsoft.Extensions.Http in the test project only - show the plain registration in the package readme --- dotnet/README.md | 2 +- .../src/Dax.Formatter/DaxFormatterClient.cs | 24 ++++------- .../Dax.Formatter.Tests.csproj | 1 + .../DaxFormatterClientTests.cs | 15 +++++-- .../DependencyInjectionTests.cs | 41 +++++++++++++++++++ .../PublicApi.approved.txt | 3 +- 6 files changed, 64 insertions(+), 22 deletions(-) create mode 100644 dotnet/tests/Dax.Formatter.Tests/DependencyInjectionTests.cs diff --git a/dotnet/README.md b/dotnet/README.md index d78b474..b9ff11f 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -207,7 +207,7 @@ Without an `HttpClient`, all the clients share one that lives as long as the pro var client = new DaxFormatterClient(httpClient); ``` -The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register the client as a typed client with a factory, because more than one of its constructors takes an `HttpClient`: `services.AddHttpClient(httpClient => new DaxFormatterClient(httpClient))`. +The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register it as a typed client: `services.AddHttpClient()`. The client then takes the `DaxFormatterClientOptions` registered in the container, if any. On .NET Framework the shared `HttpClient` opens at most [`ServicePointManager.DefaultConnectionLimit`](https://learn.microsoft.com/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit) connections to the service, which is 2 unless the application changes it. Raise that limit, or pass your own `HttpClient`, before you raise `MaxConcurrentRequests` or run several calls at the same time: a request that waits for a connection uses up its `RequestTimeout`. diff --git a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs index bf28809..3b6e12e 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs @@ -40,26 +40,18 @@ public DaxFormatterClient(DaxFormatterClientOptions options) /// Initializes a new instance of the class that sends its requests with /// the given . /// + /// + /// This is the only constructor that takes an , so that + /// services.AddHttpClient<DaxFormatterClient>() can create the client: the container passes + /// the options when it has them. + /// /// /// The to use. The caller owns it: the client never changes or disposes it, and /// ignores its . /// - public DaxFormatterClient(HttpClient httpClient) - : this(httpClient, new DaxFormatterClientOptions()) - { - } - - /// - /// Initializes a new instance of the class that sends its requests with - /// the given , with the given options. - /// - /// - /// The to use. The caller owns it: the client never changes or disposes it, and - /// ignores its . - /// - /// The options, which are copied. - public DaxFormatterClient(HttpClient httpClient, DaxFormatterClientOptions options) - : this(httpClient, options, TaskDelay.Instance, BatchLimits.Default) + /// The options, which are copied, or for the defaults. + public DaxFormatterClient(HttpClient httpClient, DaxFormatterClientOptions? options = null) + : this(httpClient, options ?? new DaxFormatterClientOptions(), TaskDelay.Instance, BatchLimits.Default) { } diff --git a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj index e070777..cdd4381 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs index b377b3e..5e4cef7 100644 --- a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs @@ -13,11 +13,20 @@ public class DaxFormatterClientTests [Fact] public void Constructor_NullArgument_Throws() { - using var httpClient = new HttpClient(); - Assert.Throws("httpClient", () => new DaxFormatterClient((HttpClient)null!)); Assert.Throws("options", () => new DaxFormatterClient((DaxFormatterClientOptions)null!)); - Assert.Throws("options", () => new DaxFormatterClient(httpClient, null!)); + } + + [Fact] + public async Task Constructor_HttpClientWithoutOptions_UsesTheDefaults() + { + using var handler = new FakeFormatterHandler(Respond.Echo); + using var httpClient = new HttpClient(handler); + var client = new DaxFormatterClient(httpClient, options: null); + + await client.FormatAsync("EVALUATE Sales"); + + Assert.Equal(new Uri("https://api.daxformatter.com/api/daxtextformatmulti"), handler.Requests[0].Uri); } [Fact] diff --git a/dotnet/tests/Dax.Formatter.Tests/DependencyInjectionTests.cs b/dotnet/tests/Dax.Formatter.Tests/DependencyInjectionTests.cs new file mode 100644 index 0000000..344aa3f --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DependencyInjectionTests.cs @@ -0,0 +1,41 @@ +using Dax.Formatter.Tests.Fakes; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Dax.Formatter.Tests; + +/// +/// Keeps a typed client of IHttpClientFactory: the factory can create it +/// only while one constructor alone takes an . +/// +public class DependencyInjectionTests +{ + [Fact] + public async Task AddHttpClient_TypedClient_SendsTheRequestsWithTheConfiguredHandler() + { + using var handler = new FakeFormatterHandler(Respond.Echo); + var services = new ServiceCollection(); + services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => handler); + using var provider = services.BuildServiceProvider(); + var client = provider.GetRequiredService(); + + await client.FormatAsync("EVALUATE Sales"); + + Assert.Single(handler.Requests); + } + + [Fact] + public async Task AddHttpClient_OptionsInTheContainer_CreatesTheClientWithThem() + { + using var handler = new FakeFormatterHandler(Respond.Echo); + var services = new ServiceCollection(); + services.AddSingleton(new DaxFormatterClientOptions { ApplicationName = "Contoso Model Tools" }); + services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => handler); + using var provider = services.BuildServiceProvider(); + var client = provider.GetRequiredService(); + + await client.FormatAsync("EVALUATE Sales"); + + Assert.Equal("Contoso Model Tools", handler.Requests[0].Json.GetProperty("callerApp").GetString()); + } +} diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt index 3e6a893..d5b6f6c 100644 --- a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt @@ -23,8 +23,7 @@ class Dax.Formatter.DaxFormatterClient System.Threading.Tasks.Task>> FormatBatchAsync(System.Collections.Generic.IEnumerable items, System.Func textSelector, Dax.Formatter.DaxFormatOptions options = default, System.IProgress progress = default, System.Threading.CancellationToken cancellationToken = default) constructor() constructor(Dax.Formatter.DaxFormatterClientOptions options) - constructor(System.Net.Http.HttpClient httpClient) - constructor(System.Net.Http.HttpClient httpClient, Dax.Formatter.DaxFormatterClientOptions options) + constructor(System.Net.Http.HttpClient httpClient, Dax.Formatter.DaxFormatterClientOptions options = default) virtual System.Threading.Tasks.Task FormatAsync(System.String text, Dax.Formatter.DaxFormatOptions options = default, System.Threading.CancellationToken cancellationToken = default) virtual System.Threading.Tasks.Task> FormatBatchAsync(System.Collections.Generic.IEnumerable texts, Dax.Formatter.DaxFormatOptions options = default, System.IProgress progress = default, System.Threading.CancellationToken cancellationToken = default) sealed class Dax.Formatter.DaxFormatterClientOptions From 3dbb4aac2ac0b4c7ee6b3786cbcf0f8c76ce9b11 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 17:08:00 +0100 Subject: [PATCH 20/29] feat(dotnet): expose the operation id and text indexes of a failed request The indexes of the texts of a failed request were only in the message, and the message counted the blank texts between them, which are never sent. The id of the call went to the service but not to the caller. - add OperationId and TextIndexes to DaxFormatterException, set by the client from the request that failed; TextIndexes is empty otherwise - widen the full constructor, which copies the indexes - keep the real indexes of its texts in each request --- dotnet/src/Dax.Formatter/Batching/BatchRun.cs | 2 +- dotnet/src/Dax.Formatter/Batching/Chunk.cs | 3 +++ .../Dax.Formatter/DaxFormatterException.cs | 23 ++++++++++++++++ .../Dax.Formatter/Transport/FormatRequest.cs | 25 +++++++++--------- .../Batching/BatchRunTests.cs | 15 +++++++++++ .../DaxFormatterExceptionTests.cs | 26 +++++++++++++++++-- .../PublicApi.approved.txt | 4 ++- 7 files changed, 81 insertions(+), 17 deletions(-) diff --git a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs index 4a4023e..a490d5c 100644 --- a/dotnet/src/Dax.Formatter/Batching/BatchRun.cs +++ b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs @@ -152,7 +152,7 @@ private async Task FormatChunkAsync(Chunk chunk, CancellationToken cancellationT private FormatRequest CreateRequest(Chunk chunk) { var body = _bodyWriter.Write(_plan.GetTextsToSend(chunk), _settings); - return new FormatRequest(body, chunk.Count, chunk.FirstIndex, chunk.LastIndex, _operationId); + return new FormatRequest(body, chunk.TextIndexes, _operationId); } private Task StopOthersAsync() diff --git a/dotnet/src/Dax.Formatter/Batching/Chunk.cs b/dotnet/src/Dax.Formatter/Batching/Chunk.cs index 745bff6..150ab6f 100644 --- a/dotnet/src/Dax.Formatter/Batching/Chunk.cs +++ b/dotnet/src/Dax.Formatter/Batching/Chunk.cs @@ -14,6 +14,9 @@ public Chunk(int[] textIndexes) public int Count => _textIndexes.Length; + /// Gets the indexes, in the texts of the call, of the texts of the request, in order. + public IReadOnlyList TextIndexes => _textIndexes; + public int FirstIndex => _textIndexes[0]; public int LastIndex => _textIndexes[_textIndexes.Length - 1]; diff --git a/dotnet/src/Dax.Formatter/DaxFormatterException.cs b/dotnet/src/Dax.Formatter/DaxFormatterException.cs index 61ca7b5..4daeda6 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterException.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterException.cs @@ -44,6 +44,10 @@ public DaxFormatterException(string message, Exception innerException) /// The HTTP status of the answer, when one arrived. /// The identifier that the client gave to the request. /// The identifier that the service gave to the request. + /// The identifier that the client gave to the call. + /// + /// The indexes, in the texts of the call, of the texts that the request carried, which are copied. + /// /// The exception that caused the failure, if any. public DaxFormatterException( string message, @@ -51,6 +55,8 @@ public DaxFormatterException( HttpStatusCode? statusCode, string? requestId, string? serviceRequestId, + string? operationId, + IEnumerable? textIndexes, Exception? innerException) : base(message, innerException) { @@ -58,6 +64,11 @@ public DaxFormatterException( StatusCode = statusCode; RequestId = requestId; ServiceRequestId = serviceRequestId; + OperationId = operationId; + if (textIndexes is not null) + { + TextIndexes = [.. textIndexes]; + } } /// @@ -81,4 +92,16 @@ public DaxFormatterException( /// answer, or when no answer arrived. /// public string? ServiceRequestId { get; } + + /// + /// Gets the identifier that the client gave to the call and sent in the DaxFormatter-Operation-Id + /// header of each of its requests, or when the client did not create the exception. + /// + public string? OperationId { get; } + + /// + /// Gets the indexes, in the texts of the call, of the texts that the failed request carried, in order, or + /// an empty list when they are not known. Blank texts are never sent, so they are never among them. + /// + public IReadOnlyList TextIndexes { get; } = []; } diff --git a/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs b/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs index cb101a6..f18a2a4 100644 --- a/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs +++ b/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs @@ -8,25 +8,20 @@ namespace Dax.Formatter.Transport; /// internal sealed class FormatRequest { - public FormatRequest(byte[] body, int textCount, int firstIndex, int lastIndex, Guid operationId) + public FormatRequest(byte[] body, IReadOnlyList textIndexes, Guid operationId) { Body = body; - TextCount = textCount; - FirstIndex = firstIndex; - LastIndex = lastIndex; + TextIndexes = textIndexes; OperationId = operationId; RequestId = Guid.NewGuid(); } public byte[] Body { get; } - public int TextCount { get; } + public int TextCount => TextIndexes.Count; - /// Gets the index, in the texts of the call, of the first text of the request. - public int FirstIndex { get; } - - /// Gets the index, in the texts of the call, of the last text of the request. - public int LastIndex { get; } + /// Gets the indexes, in the texts of the call, of the texts of the request, in order. + public IReadOnlyList TextIndexes { get; } /// Gets the identifier of the call, which its requests share. public Guid OperationId { get; } @@ -41,9 +36,11 @@ public DaxFormatterException CreateException( string? serviceRequestId, Exception? innerException) { - var texts = FirstIndex == LastIndex - ? FormattableString.Invariant($"the text at index {FirstIndex}") - : FormattableString.Invariant($"the texts at indexes {FirstIndex} to {LastIndex}"); + var first = TextIndexes[0]; + var last = TextIndexes[TextIndexes.Count - 1]; + var texts = first == last + ? FormattableString.Invariant($"the text at index {first}") + : FormattableString.Invariant($"the texts at indexes {first} to {last}"); var message = $"The DAX Formatter request for {texts} failed: {detail}."; return new DaxFormatterException( @@ -52,6 +49,8 @@ public DaxFormatterException CreateException( statusCode, RequestId.ToString(), serviceRequestId, + OperationId.ToString(), + TextIndexes, innerException); } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs index 53b391a..d5ead3a 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs @@ -75,6 +75,21 @@ public async Task FormatBatchAsync_OneRequestFails_StopsTheOthersAndThrowsItsFai Assert.Contains("the texts at indexes 2 to 3", exception.Message, StringComparison.Ordinal); } + [Fact] + public async Task FormatBatchAsync_FailedRequestAroundABlankText_ReportsTheTextsItCarriedAndTheCall() + { + string[] texts = ["a", " ", "c"]; + int[] sentIndexes = [0, 2]; + using var harness = new FormatterHarness(Respond.Status(HttpStatusCode.BadRequest), limits: s_twoTextsPerRequest); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatBatchAsync(texts)) + .ConfigureAwait(true); + + Assert.Equal(sentIndexes, exception.TextIndexes); + Assert.Equal(harness.Handler.Requests[0].GetHeader("DaxFormatter-Operation-Id"), exception.OperationId); + } + [Fact] public async Task FormatBatchAsync_OneRequestFails_DoesNotSendTheRemainingOnes() { diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs index 0b94635..aa902ff 100644 --- a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs @@ -11,11 +11,32 @@ public void Constructor_EveryDetail_KeepsThem() var inner = new InvalidOperationException("inner"); var exception = new DaxFormatterException( - "message", DaxFormatterFailureReason.HttpError, HttpStatusCode.BadGateway, "request", "service", inner); + "message", + DaxFormatterFailureReason.HttpError, + HttpStatusCode.BadGateway, + "request", + "service", + "operation", + [3, 5], + inner); Assert.Equal(("message", inner), (exception.Message, exception.InnerException)); Assert.Equal((DaxFormatterFailureReason.HttpError, HttpStatusCode.BadGateway), (exception.Reason, exception.StatusCode)); - Assert.Equal(("request", "service"), (exception.RequestId, exception.ServiceRequestId)); + Assert.Equal( + ("request", "service", "operation", "3,5"), + (exception.RequestId, exception.ServiceRequestId, exception.OperationId, string.Join(",", exception.TextIndexes))); + } + + [Fact] + public void Constructor_TextIndexes_KeepsACopy() + { + var indexes = new List { 3, 5 }; + var exception = new DaxFormatterException( + "message", DaxFormatterFailureReason.HttpError, null, null, null, null, indexes, null); + + indexes.Add(7); + + Assert.Equal(2, exception.TextIndexes.Count); } [Fact] @@ -25,6 +46,7 @@ public void Constructor_MessageOnly_HasNoDetails() Assert.Equal(DaxFormatterFailureReason.Unknown, exception.Reason); Assert.Equal((null, null, null), (exception.StatusCode, exception.RequestId, exception.ServiceRequestId)); + Assert.Equal((null, 0), (exception.OperationId, exception.TextIndexes.Count)); } [Fact] diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt index d5b6f6c..a352119 100644 --- a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt @@ -36,12 +36,14 @@ sealed class Dax.Formatter.DaxFormatterClientOptions constructor() sealed class Dax.Formatter.DaxFormatterException : System.Exception Dax.Formatter.DaxFormatterFailureReason Reason { get; } + System.Collections.Generic.IReadOnlyList TextIndexes { get; } System.Net.HttpStatusCode? StatusCode { get; } + System.String OperationId { get; } System.String RequestId { get; } System.String ServiceRequestId { get; } constructor() constructor(System.String message) - constructor(System.String message, Dax.Formatter.DaxFormatterFailureReason reason, System.Net.HttpStatusCode? statusCode, System.String requestId, System.String serviceRequestId, System.Exception innerException) + constructor(System.String message, Dax.Formatter.DaxFormatterFailureReason reason, System.Net.HttpStatusCode? statusCode, System.String requestId, System.String serviceRequestId, System.String operationId, System.Collections.Generic.IEnumerable textIndexes, System.Exception innerException) constructor(System.String message, System.Exception innerException) enum Dax.Formatter.DaxFormatterFailureReason HttpError = 3 From 64b5c091e291e190964d9a7b09552a3e41953f7f Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 17:08:10 +0100 Subject: [PATCH 21/29] docs(dotnet): say that the failure reason can gain values A caller that switches on DaxFormatterFailureReason must not break when a minor version adds a reason: the remarks say to handle an unknown value as Unknown. --- dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs index dd0e6e7..c852add 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs @@ -3,6 +3,9 @@ /// /// Why a call to the DAX Formatter service failed. /// +/// +/// A later minor version can add values: handle a value that you don't know as . +/// public enum DaxFormatterFailureReason { /// From e097e3285e2406aa09dbe32a66d869359809d3d1 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 17:09:57 +0100 Subject: [PATCH 22/29] docs: record how the client API grows Version 2.0 fixes the shape of the public API until 3.0, so the paths for the features in view are written down before it ships. - add ADR-0007: the batch takes the caller's items with a selector and returns a list in input order; the patterns not taken, with their pros and cons; how each later feature is added without breaking - say in client-api.md that enums can gain values, that the column index follows the string unit of each language, and what the exception reports about a failed request - add B-23, package validation once 2.0.0 is published --- docs/backlog.md | 3 +- ...e-the-client-api-from-the-rest-contract.md | 1 + ...lers-items-and-grow-it-only-by-addition.md | 161 ++++++++++++++++++ docs/design/client-api.md | 8 +- 4 files changed, 169 insertions(+), 4 deletions(-) create mode 100644 docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md diff --git a/docs/backlog.md b/docs/backlog.md index 80c47bb..a64b989 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,6 +1,6 @@ # Backlog -Next ID: B-23 +Next ID: B-24 Reports and requests from users stay in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues); an item here links its issue instead of copying it. @@ -19,6 +19,7 @@ Reports and requests from users stay in [GitHub Issues](https://github.com/sql-b - B-9 `concurrency` groups in both CI workflows, so that a newer push to a pull request cancels its older run. - B-17 The .NET client finds the text that makes a request fail: when the service fails on one text, the whole request fails and the call with it, and the exception names only the texts of that request by their indexes. Done when the client sends the texts of a failed request again in smaller requests, reports the one that fails, and [`client-api.md`](design/client-api.md) says how. - B-18 Measured limits for the requests of the .NET client: 250 texts and 250,000 characters for each request and 2 requests at a time are estimates ([client API](design/client-api.md#requests)). Done when the numbers come from measures on the service with real models, and `client-api.md` states them. +- B-23 Package validation for `Dax.Formatter` once 2.0.0 is on nuget.org: `PublicApiTests` shows every change of the public surface, but doesn't tell an addition from a breaking change ([ADR-0007](decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md)). Done when `Dax.Formatter.csproj` sets `EnablePackageValidation` and `PackageValidationBaselineVersion` to `2.0.0`, and a pack fails on a removed public member ([package validation](https://learn.microsoft.com/dotnet/fundamentals/apicompat/package-validation/overview)). - B-21 One version scheme for both packages when the MCP server leaves its beta: until then it stays on `0.2-beta` with the git height as its third number, while `Dax.Formatter` has a version written by hand ([ADR-0006](decisions/0006-write-the-dax-formatter-package-version-by-hand.md)). Done when a decision record says which scheme the MCP server follows from its first stable version. ## Open decisions diff --git a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md index e984610..3863826 100644 --- a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md +++ b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md @@ -76,4 +76,5 @@ Chosen option: "A new API on a model of its own", because the work that every ca - The arrow `=>` belongs to function definitions only: [FUNCTION statement](https://learn.microsoft.com/dax/function-statement-dax). - The shared `HttpClient`: [Guidelines for using HttpClient](https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines). - The version of the package: [ADR-0006](0006-write-the-dax-formatter-package-version-by-hand.md). +- How a batch takes the caller's objects, and how the API grows: [ADR-0007](0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md). - Revisit if the service gets an endpoint that takes the kind of a text, which would make the header line unnecessary, or if users ask for MDX again. diff --git a/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md b/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md new file mode 100644 index 0000000..6619419 --- /dev/null +++ b/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md @@ -0,0 +1,161 @@ +--- +status: accepted +date: 2026-11-22 +decision-makers: Alberto Spelta +--- + +# Keep the batch API on the caller's items and grow it only by addition + +## Context and Problem Statement + +The callers of `Dax.Formatter` format thousands of texts that belong to their own objects. In a model these are measures, calculated columns, calculation items and user-defined functions: objects of different types. One object can also carry several DAX texts: its expression, its format string expression, its detail rows expression. + +[ADR-0005](0005-decouple-the-client-api-from-the-rest-contract.md) gave version 2.0 a model of its own. It left open three things, which this record settles: + +- how a batch takes the caller's objects; +- how the results come back; +- how the public API grows after 2.0 ships without a new major version, in .NET and in the TypeScript and Python ports. + +## Decision Drivers + +* A caller never matches results with its objects by position. +* Objects of different types, and several texts of one object, fit in one call. +* What 2.0 ships can't change without a breaking change, so what comes later must be an addition. +* The shape exists in .NET, TypeScript and Python. + +## Considered Options + +For the input: + +* Texts only +* An input type of the library, with an identifier or a state for each text +* The caller's items with a text selector, next to texts +* A builder that queues texts and returns a handle or calls back for each one +* Implicit batching: one call for each text, which the client groups, with a task for each text + +For the output: + +* A list of results in the order of the input +* A collection type of the library with data about the call +* A stream of results in the order they complete + +## Decision Outcome + +Chosen options: "The caller's items with a text selector, next to texts" and "A list of results in the order of the input". The common case is one line, each result is tied to the caller's object, and the options not taken can still be added later, when a use appears. + +### The shape of 2.0 + +- `FormatBatchAsync(texts)` and `FormatBatchAsync(items, textSelector)` return an `IReadOnlyList` with one result for each input, in its order. The items version gives each result its item in `Item`. +- Objects of different types go in one call through a small type of the caller, which holds the text and what to do with the result. So do several texts of one object, with one item for each text. The package readme shows such a type. +- A batch is atomic: it returns every result, or throws `DaxFormatterException`. On a failure, `TextIndexes` says which texts the failed request carried and `OperationId` which call failed. +- A syntax error is a value in the result of its text. +- `Task` and `IProgress` serve long calls; there is no stream. + +### How the API grows + +Each of these is an addition, and none changes what 2.0 does: + +- **Settings for each text, such as a kind for each text:** + - a new input type, `DaxFormatInput`, with nullable settings; + - new overloads that take it, or an input selector. + + A setting of the text wins over the one of the call, and null takes the call's. A lambda that returns a string keeps binding to the existing overload. +- **Default format options on the client:** a property of `DaxFormatterClientOptions`, used when a call passes no options. They replace the options of the call; they never merge with them. +- **An operation identifier chosen by the caller:** a property of `DaxFormatOptions`. With null, each call keeps getting a new identifier. +- **Partial success:** + - only as an option the caller turns on; + - the call still throws, and the exception carries the results of the requests that succeeded; + - a result never gets a third state. +- **Warnings:** a list separate from `Errors`. +- **The end of the range, or a code, of a syntax error:** new properties of `DaxSyntaxError`, with a new constructor. +- **A stream of results:** a new method. An existing method never changes its return type. +- **New enum values:** + - the client rejects an input value it doesn't know; + - a caller handles an unknown `DaxFormatterFailureReason` as `Unknown`; + - in TypeScript and Python, the enums that come out of the client are open types. + +### What the API doesn't do + +- No option decides whether a call throws, such as a `ThrowOnAnyError`. +- No tuple and no implicit conversion in a public type. +- No style setting for each text: the service applies the styles to a whole request. + +### Consequences + +* Good, because the common call is one line and no caller matches results by index. +* Good, because each feature in view has a path that keeps 2.x compatible, in source and in binary. +* Bad, because a caller that mixes object types writes a small type of its own. +* Bad, because the list has no room for data about the call: what a caller needs from a failed call travels on the exception. + +### Confirmation + +- `PublicApiTests` shows every change of the public surface as a change of `PublicApi.approved.txt`. A pull request that changes that file is reviewed against this record. +- After the release of 2.0.0, package validation against that version fails the build on a breaking change ([backlog](../backlog.md)). + +## Pros and Cons of the Options + +### Texts only + +* Good, because it is the simplest call. +* Bad, because settings for each text need new overloads, and the caller matches results with its objects by index. Azure Translator 2.0 broke its API to add a target language for each text. + +### An input type of the library, with an identifier or a state for each text + +Examples: Azure `TextDocumentInput`, BigQuery `BigQueryInsertRow`, the nested requests of Google's batch methods. + +* Good, because settings for each text can be added as properties. +* Bad, because the common case wraps every text. +* Bad, because with an identifier the caller keeps a dictionary to find its objects again. [AIP-233](https://google.aip.dev/233) gives this cost as its reason to report failures by index. + +### The caller's items with a text selector, next to texts + +* Good, because the common call is one line, as with the selectors of LINQ and Azure Search's `KeyFieldAccessor`. +* Good, because each result carries the caller's object. +* Bad, because objects of different types need a common type, which the caller writes. + +### A builder that queues texts and returns a handle or calls back for each one + +Examples: Google's `BatchRequest.Queue`, Azure's `BlobBatch`. + +* Good, because objects of different types need no common type. +* Bad, because the call has two phases. +* Bad, because a handle can't be used before the batch is sent. +* Bad, because callbacks raise questions of exceptions and threads; the Framework Design Guidelines prefer events to callbacks. + +### Implicit batching: one call for each text, which the client groups, with a task for each text + +Examples: gax `Batcher`, Cosmos DB bulk mode, Firestore `BulkWriter`. + +* Good, because it serves streams without an end. +* Bad, because it needs a flush and a close. +* Bad, because tasks that nobody observes hide failures. Firestore for Node had unhandled rejections ([nodejs-firestore#1282](https://github.com/googleapis/nodejs-firestore/issues/1282)), and the Python client has no task for each write. + +### A collection type of the library with data about the call + +Example: Azure `AnalyzeSentimentResultCollection`. + +* Good, because it has room for data about the call and for lookups, and the [collection guidelines](https://learn.microsoft.com/dotnet/standard/design-guidelines/guidelines-for-collections) prefer a collection class to an interface as a return type. +* Bad, because there is no data about the call to put in it today. +* Bad, because TypeScript and Python use plain arrays and lists. +* Bad, because the test doubles of an application would have to build it. + +### A stream of results in the order they complete + +* Good, because the first results arrive before the call ends. +* Bad, because Microsoft moved the batch upsert of its vector stores from `IAsyncEnumerable` back to a task ([semantic-kernel#10692](https://github.com/microsoft/semantic-kernel/issues/10692)) and declined streaming for embeddings ([dotnet/extensions#5548](https://github.com/dotnet/extensions/issues/5548)). +* Bad, because on `netstandard2.0` it needs a new dependency. +* Bad, because `IProgress` already serves a progress bar. + +## More Information + +- The model: [ADR-0005](0005-decouple-the-client-api-from-the-rest-contract.md) and [`client-api.md`](../design/client-api.md). +- Compatibility: + - Google [AIP-180](https://google.aip.dev/180): a new field must keep the old behavior, and enums in responses are open. + - [AIP-233](https://google.aip.dev/233): a synchronous batch is atomic, and partial success is opt-in. + - The .NET [breaking change rules](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-rules.md): default parameter values are part of the contract. +- Exceptions: the [Framework Design Guidelines](https://learn.microsoft.com/dotnet/standard/design-guidelines/exception-throwing) on throwing. +- Throwing or returning the errors of each item: [google-cloud-dotnet#4199](https://github.com/googleapis/google-cloud-dotnet/issues/4199). +- Tuples and records: + - classes rather than tuples in public APIs ([dotnet/runtime#27939](https://github.com/dotnet/runtime/issues/27939)); + - a tuple becomes a record when it travels between methods ([Choose between tuples, records, structs, and classes](https://learn.microsoft.com/dotnet/csharp/fundamentals/tutorials/choosing-types)). +- Revisit when a consumer needs settings for each text, or the results of a call that failed in part. diff --git a/docs/design/client-api.md b/docs/design/client-api.md index 26ae134..eaa0d66 100644 --- a/docs/design/client-api.md +++ b/docs/design/client-api.md @@ -20,7 +20,9 @@ The model of a DAX Formatter client: what a caller gives it, what it returns, an - **Result** (`DaxFormatResult`): `OriginalText`, `Succeeded`, `FormattedText` (absent when `Succeeded` is false) and `Errors` (empty when it is true). A result of the batch operation that takes items also has `Item`, the caller's object. - **Syntax error** (`DaxSyntaxError`): `Line`, `Column`, `Message`, with value equality. - **Progress** (`DaxFormatProgressInfo`): `Completed` and `Total`, as numbers of texts. -- **Failure** (`DaxFormatterException`): `Reason` (`Timeout`, `NetworkError`, `HttpError`, `InvalidResponse`, or `Unknown` when the exception was not created by the client), `StatusCode`, `RequestId`, `ServiceRequestId`. +- **Failure** (`DaxFormatterException`): `Reason` (`Timeout`, `NetworkError`, `HttpError`, `InvalidResponse`, or `Unknown` when the exception was not created by the client), `StatusCode`, `RequestId`, `ServiceRequestId`, `OperationId`, and `TextIndexes`, the indexes of the texts that the failed request carried. +- **Enums** can gain values in a minor version. The client rejects an input value that it doesn't know; a caller handles an unknown failure reason as `Unknown`. In TypeScript and Python the enums that come out of the client are open types. +- How a batch takes the caller's objects, and how the model grows without breaking: [ADR-0007](../decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md). ## Outcomes @@ -42,7 +44,7 @@ The model of a DAX Formatter client: what a caller gives it, what it returns, an ## Error positions -`Line` and `Column` are zero-based and refer to the text that the caller gave. Lines are separated by `\n`. `Column` is an index into the UTF-16 code units of the line, and equals the length of the line, without its `\r`, when the error is at its end. +`Line` and `Column` are zero-based and refer to the text that the caller gave. Lines are separated by `\n`. `Column` is an index into the line in the unit that the strings of the language are indexed by: UTF-16 code units in .NET and TypeScript, code points in Python. It equals the length of the line, without its `\r`, when the error is at its end. The client converts the [position that the service reports](rest-api.md#response): @@ -57,7 +59,7 @@ The client converts the [position that the service reports](rest-api.md#response - At most `MaxConcurrentRequests` requests are in progress. Each result is stored at the index of its text. - Progress is reported after each request, and once before the first one for the blank texts. The count never decreases. - Retry: after a timeout, a network error and the statuses 408, 429, 500, 502, 503 and 504. Any other status and an invalid response fail at once. The wait starts at 0.8 seconds and doubles up to 60, varied by a quarter either way; a longer `Retry-After`, in seconds or as a date measured from the `Date` header of the same response, replaces it, and one longer than `RequestTimeout` fails the request at once. Each attempt sends the same body and the same request identifier. -- The first request that fails after its retries stops the others, and the call fails with it. The message names the texts of that request by their indexes. +- The first request that fails after its retries stops the others, and the call fails with it. The message names the first and the last index of the texts of that request; `TextIndexes` lists them all, without the blank texts, which are never sent. - A request that timed out is not split in two: the service keeps working on an abandoned request, so smaller requests would add load when it is slow. - Invalid responses: status 204, a body that is not the documented JSON, a number of results other than the number of texts sent, a null result. A UTF-8 byte order mark before the JSON is skipped. In a result, a null `errors` is no errors, and a null `formatted` without errors is an empty text; `formatted` is not read when there are errors. From ad28162b4f697f3eef9a845463ed1c9da38318ca Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 17:11:15 +0100 Subject: [PATCH 23/29] docs(dotnet): use a record in the readme sample for objects of different types The tuple of the sample had no name for the object, so the sample could not say which one has a syntax error, and C# guidance prefers a named type once the shape travels between methods. - declare sealed record ModelExpression(Name, Expression, Update) - report the name of an object whose text has a syntax error - say that an object with several DAX texts adds one item for each - add IsExternalInit to the tests, which records need on net472 --- dotnet/README.md | 20 ++++++++++++---- .../Polyfills/IsExternalInit.cs | 8 +++++++ .../Readme/ReadmeSamples.cs | 23 ++++++++++++++----- 3 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs diff --git a/dotnet/README.md b/dotnet/README.md index b9ff11f..da449f7 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -61,19 +61,25 @@ Here `Measure` and `model` stand for the types of your application: any type wor ### Format objects of different types -One call formats the objects of a model whatever their type, because `DaxKind.Expression` covers them all. Put them in one list, each with its DAX and a function that writes the formatted text back to it. +One call formats the objects of a model whatever their type, because `DaxKind.Expression` covers them all. Declare a small type that holds the name of an object, its DAX and a function that writes the formatted text back to it: ```csharp -var items = new List<(string Expression, Action Update)>(); +sealed record ModelExpression(string Name, string Expression, Action Update); +``` + +Then put every object in one list: + +```csharp +var items = new List(); foreach (var measure in model.Measures) { - items.Add((measure.Expression, text => measure.Expression = text)); + items.Add(new(measure.Name, measure.Expression, text => measure.Expression = text)); } foreach (var function in model.Functions) { - items.Add((function.Expression, text => function.Expression = text)); + items.Add(new(function.Name, function.Expression, text => function.Expression = text)); } var options = new DaxFormatOptions { Kind = DaxKind.Expression }; @@ -86,10 +92,14 @@ foreach (var result in results) { result.Item.Update(result.FormattedText); } + else + { + Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); + } } ``` -`Update` is not part of the client: it is the function you stored in the item, which the result gives back in `Item`. Only texts of the other kind need a call of their own, such as queries, which take `DaxKind.Auto`. +`Update` is not part of the client: it is the function stored in the item, which the result gives back in `Item`. An object with several DAX texts, such as a measure with a format string expression, adds one item for each text. Only texts of the other kind need a call of their own, such as queries, which take `DaxKind.Auto`. ### Options diff --git a/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs b/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs new file mode 100644 index 0000000..dd68c70 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs @@ -0,0 +1,8 @@ +#if !NET +namespace System.Runtime.CompilerServices; + +// The record of the readme samples needs it for its init accessors, and .NET Framework doesn't have it. +internal static class IsExternalInit +{ +} +#endif diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs index d0d5216..14103b8 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -71,16 +71,16 @@ public async Task FormatBatchAsync_MixedObjectsSample_UpdatesTheObjectsOfEveryTy var model = new Model(); #region MixedObjects - var items = new List<(string Expression, Action Update)>(); + var items = new List(); foreach (var measure in model.Measures) { - items.Add((measure.Expression, text => measure.Expression = text)); + items.Add(new(measure.Name, measure.Expression, text => measure.Expression = text)); } foreach (var function in model.Functions) { - items.Add((function.Expression, text => function.Expression = text)); + items.Add(new(function.Name, function.Expression, text => function.Expression = text)); } var options = new DaxFormatOptions { Kind = DaxKind.Expression }; @@ -93,15 +93,23 @@ public async Task FormatBatchAsync_MixedObjectsSample_UpdatesTheObjectsOfEveryTy { result.Item.Update(result.FormattedText); } + else + { + Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); + } } #endregion Assert.Equal("CALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )", model.Measures[0].Expression); - Assert.Equal("SUMX(Sales, Sales[Amount] *", model.Measures[1].Expression); Assert.Equal( "(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", model.Functions[0].Expression); + Assert.Equal("Broken", results.Single(result => !result.Succeeded).Item.Name); } + #region MixedObjectsType + sealed record ModelExpression(string Name, string Expression, Action Update); + #endregion + [Fact] public async Task FormatAsync_OptionsSample_SendsTheOptions() { @@ -277,17 +285,20 @@ private sealed class Model public List Functions { get; } = [ - new Function("(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"), + new Function("AddRate", "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"), ]; } private sealed class Function { - public Function(string expression) + public Function(string name, string expression) { + Name = name; Expression = expression; } + public string Name { get; } + public string Expression { get; set; } } } From f4001630995b292bfa6aad8e1c243506a730007c Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:24:38 +0100 Subject: [PATCH 24/29] feat(dotnet): describe the server of the model with enums - DaxModelInfo takes DaxServerType, DaxServerMode, DaxServerEdition and DaxServerLocation instead of strings, as in 1.x and in the TypeScript port; DaxServerTypes is gone. - Mode, edition and location have the names and values of the Analysis Services enums, StandardDeveloper editions included, so a caller converts a value of those libraries by its name. - The wire format doesn't change: the client sends the strings of the service, and rejects a value outside its enum. - ADR-0005 and the REST API document say so. --- ...e-the-client-api-from-the-rest-contract.md | 3 +- docs/design/rest-api.md | 6 +- dotnet/README.md | 2 +- .../Configuration/FormatSettings.cs | 49 +++++++++++-- dotnet/src/Dax.Formatter/DaxModelInfo.cs | 16 ++--- dotnet/src/Dax.Formatter/DaxServerEdition.cs | 56 +++++++++++++++ dotnet/src/Dax.Formatter/DaxServerLocation.cs | 14 ++++ dotnet/src/Dax.Formatter/DaxServerMode.cs | 20 ++++++ dotnet/src/Dax.Formatter/DaxServerType.cs | 31 ++++++++ dotnet/src/Dax.Formatter/DaxServerTypes.cs | 31 -------- .../Configuration/FormatSettingsTests.cs | 71 +++++++++++++++++++ .../Fixtures/FixtureOptions.cs | 16 +++-- .../Fixtures/request-bodies.json | 8 +-- .../Live/LiveServiceTests.cs | 8 +-- .../PublicApi.approved.txt | 51 +++++++++---- .../Readme/ReadmeSamples.cs | 2 +- 16 files changed, 309 insertions(+), 75 deletions(-) create mode 100644 dotnet/src/Dax.Formatter/DaxServerEdition.cs create mode 100644 dotnet/src/Dax.Formatter/DaxServerLocation.cs create mode 100644 dotnet/src/Dax.Formatter/DaxServerMode.cs create mode 100644 dotnet/src/Dax.Formatter/DaxServerType.cs delete mode 100644 dotnet/src/Dax.Formatter/DaxServerTypes.cs diff --git a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md index 3863826..3468512 100644 --- a/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md +++ b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md @@ -27,7 +27,7 @@ Chosen option: "A new API on a model of its own", because the work that every ca - The client splits a large call into requests, limits how many are in progress, retries the failures that can be temporary and reports progress. How much a request carries is an internal constant, not an option. - The client uses only the endpoint that takes several texts, which formats DAX only: the client doesn't format MDX. - The client doesn't convert line breaks: the service returns those inside strings and comments as they were sent, so converting all of them would change the content of strings. It doesn't halve a request that timed out: the service keeps working on a request that the client abandoned, so halving would double the load when the service is slow. -- The descriptions of the model, which the service uses for statistics, are strings, as in the TypeScript port; the server types that the service knows are constants. +- The descriptions of the model, which the service uses for statistics, are enums where the values form a known set, as in 1.x and in the TypeScript port: the type, mode, edition and location of the server. Mode, edition and location have the names and values of the enums of the Analysis Services client libraries, and the client sends the name of the member, so a caller converts a value of those libraries by its name. - The shape must exist in every target language and for every consumer of the .NET package: no `init`, `required` or record in public types, which a .NET Framework project on C# 7.3 can't use; no interface next to the client, whose methods are virtual; asynchronous methods only; no new dependency. The .NET package targets `netstandard2.0` and `net10.0`. ### Consequences @@ -40,6 +40,7 @@ Chosen option: "A new API on a model of its own", because the work that every ca * Bad, because `Expression` depends on how the service writes its answer: the client sends a header line, expects it back, and removes it with the indentation that the service adds under a function header. A different answer is a failure, never a wrong text, and the live tests pin the answers. * Bad, because the client can't work around three limits of the service, which it returns as syntax errors ([`client-api.md`](../design/client-api.md#limits-of-the-service)). * Bad, because applications that formatted MDX with the single-text methods of 1.x lose it. +* Bad, because a server value that the Analysis Services libraries add can't be sent until a minor version of the package adds it to its enum. ### Confirmation diff --git a/docs/design/rest-api.md b/docs/design/rest-api.md index 3731934..e08e070 100644 --- a/docs/design/rest-api.md +++ b/docs/design/rest-api.md @@ -66,9 +66,9 @@ Here `serverName` is the hash of `MyServer`. ## Enums -`serverType`, `serverMode`, `serverEdition` and `serverLocation` are strings. The TypeScript port has an enum for each; the .NET client takes any string, and has the values of `serverType` as the constants of `DaxServerTypes`. +`serverType`, `serverMode`, `serverEdition` and `serverLocation` are strings, which the service stores as they come. Both clients have an enum for each. For `serverMode`, `serverEdition` and `serverLocation` the .NET enums `DaxServerMode`, `DaxServerEdition` and `DaxServerLocation` send the name of the member, which is the name in the Analysis Services enums `ServerMode`, `ServerEdition` and `ServerLocation`. The TypeScript port doesn't have `StandardDeveloper` and `StandardDeveloper64`. -| `DaxServerTypes` constant, TypeScript `ServerType` member | `serverType` | +| .NET `DaxServerType` member, TypeScript `ServerType` member | `serverType` | |---|---| | `AnalysisServices` | `SSAS` | | `PowerBIDesktop` | `PBI Desktop` | @@ -82,7 +82,7 @@ Here `serverName` is the hash of `MyServer`. | Field | Values | |---|---| | `serverMode` | `Multidimensional`, `SharePoint`, `Tabular`, `Default` | -| `serverEdition` | `Standard`, `Standard64`, `Enterprise`, `Enterprise64`, `Developer`, `Developer64`, `Evaluation`, `Evaluation64`, `LocalCube`, `LocalCube64`, `BusinessIntelligence`, `BusinessIntelligence64`, `EnterpriseCore`, `EnterpriseCore64` | +| `serverEdition` | `Standard`, `Standard64`, `Enterprise`, `Enterprise64`, `Developer`, `Developer64`, `Evaluation`, `Evaluation64`, `LocalCube`, `LocalCube64`, `BusinessIntelligence`, `BusinessIntelligence64`, `EnterpriseCore`, `EnterpriseCore64`, `StandardDeveloper`, `StandardDeveloper64` | | `serverLocation` | `OnPremise`, `Azure` | ## Response diff --git a/dotnet/README.md b/dotnet/README.md index da449f7..d0564b5 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -112,7 +112,7 @@ var options = new DaxFormatOptions SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, ModelInfo = new DaxModelInfo { - ServerType = DaxServerTypes.PowerBIDesktop, + ServerType = DaxServerType.PowerBIDesktop, DatabaseName = "Contoso", }, }; diff --git a/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs b/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs index e900c97..44b7637 100644 --- a/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs +++ b/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs @@ -48,10 +48,41 @@ private FormatSettings(DaxFormatOptions options) ServerNameHash = model.ServerName is null ? null : NameHash.Compute(model.ServerName); DatabaseNameHash = model.DatabaseName is null ? null : NameHash.Compute(model.DatabaseName); - ServerType = model.ServerType; - ServerMode = model.ServerMode; - ServerEdition = model.ServerEdition; - ServerLocation = model.ServerLocation; + ServerType = model.ServerType switch + { + null => null, + DaxServerType.AnalysisServices => "SSAS", + DaxServerType.PowerBIDesktop => "PBI Desktop", + DaxServerType.PowerBIReportServer => "PBI Report Server", + DaxServerType.PowerPivot => "PowerPivot", + DaxServerType.Ssdt => "SSDT", + DaxServerType.AzureAnalysisServices => "AzureAS", + DaxServerType.PowerBIService => "PBI Service", + DaxServerType.Offline => "Offline", + _ => throw new ArgumentException(nameof(model.ServerType) + NotDefined, nameof(options)), + }; + + // For these the service takes the name of the member, which is also the name in Analysis Services. + ServerMode = model.ServerMode switch + { + null => null, + { } mode when IsDefined(mode) => mode.ToString(), + _ => throw new ArgumentException(nameof(model.ServerMode) + NotDefined, nameof(options)), + }; + + ServerEdition = model.ServerEdition switch + { + null => null, + { } edition when IsDefined(edition) => edition.ToString(), + _ => throw new ArgumentException(nameof(model.ServerEdition) + NotDefined, nameof(options)), + }; + + ServerLocation = model.ServerLocation switch + { + null => null, + { } location when IsDefined(location) => location.ToString(), + _ => throw new ArgumentException(nameof(model.ServerLocation) + NotDefined, nameof(options)), + }; ServerVersion = model.ServerVersion; DatabaseCompatibilityLevel = model.CompatibilityLevel?.ToString(CultureInfo.InvariantCulture); } @@ -87,4 +118,14 @@ public static FormatSettings From(DaxFormatOptions? options) { return new FormatSettings(options ?? new DaxFormatOptions()); } + + private static bool IsDefined(TEnum value) + where TEnum : struct, Enum + { +#if NET + return Enum.IsDefined(value); +#else + return Enum.IsDefined(typeof(TEnum), value); +#endif + } } diff --git a/dotnet/src/Dax.Formatter/DaxModelInfo.cs b/dotnet/src/Dax.Formatter/DaxModelInfo.cs index 56af669..b01a0ee 100644 --- a/dotnet/src/Dax.Formatter/DaxModelInfo.cs +++ b/dotnet/src/Dax.Formatter/DaxModelInfo.cs @@ -17,24 +17,24 @@ public sealed class DaxModelInfo public string? DatabaseName { get; set; } /// - /// Gets or sets the kind of server. has the values the service knows. + /// Gets or sets the kind of server. /// - public string? ServerType { get; set; } + public DaxServerType? ServerType { get; set; } /// - /// Gets or sets the mode of the Analysis Services server, such as Tabular. + /// Gets or sets the mode of the Analysis Services server. /// - public string? ServerMode { get; set; } + public DaxServerMode? ServerMode { get; set; } /// - /// Gets or sets the edition of the Analysis Services server, such as Enterprise64. + /// Gets or sets the edition of the Analysis Services server. /// - public string? ServerEdition { get; set; } + public DaxServerEdition? ServerEdition { get; set; } /// - /// Gets or sets where the server runs, such as OnPremise or Azure. + /// Gets or sets where the server runs. /// - public string? ServerLocation { get; set; } + public DaxServerLocation? ServerLocation { get; set; } /// /// Gets or sets the version of the server, such as 16.0.143.21. diff --git a/dotnet/src/Dax.Formatter/DaxServerEdition.cs b/dotnet/src/Dax.Formatter/DaxServerEdition.cs new file mode 100644 index 0000000..8b4aef2 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxServerEdition.cs @@ -0,0 +1,56 @@ +namespace Dax.Formatter; + +/// +/// The edition of the Analysis Services server, for . The members have the +/// names and values of Microsoft.AnalysisServices.ServerEdition. +/// +public enum DaxServerEdition +{ + /// The Standard edition. + Standard, + + /// The 64-bit Standard edition. + Standard64, + + /// The Enterprise edition. + Enterprise, + + /// The 64-bit Enterprise edition. + Enterprise64, + + /// The Developer edition. + Developer, + + /// The 64-bit Developer edition. + Developer64, + + /// The Evaluation edition. + Evaluation, + + /// The 64-bit Evaluation edition. + Evaluation64, + + /// A local cube. + LocalCube, + + /// A 64-bit local cube. + LocalCube64, + + /// The Business Intelligence edition. + BusinessIntelligence, + + /// The 64-bit Business Intelligence edition. + BusinessIntelligence64, + + /// The Enterprise Core edition. + EnterpriseCore, + + /// The 64-bit Enterprise Core edition. + EnterpriseCore64, + + /// The Standard Developer edition. + StandardDeveloper, + + /// The 64-bit Standard Developer edition. + StandardDeveloper64, +} diff --git a/dotnet/src/Dax.Formatter/DaxServerLocation.cs b/dotnet/src/Dax.Formatter/DaxServerLocation.cs new file mode 100644 index 0000000..d161530 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxServerLocation.cs @@ -0,0 +1,14 @@ +namespace Dax.Formatter; + +/// +/// Where the server runs, for . The members have the names and values of +/// Microsoft.AnalysisServices.ServerLocation. +/// +public enum DaxServerLocation +{ + /// A server on premises. + OnPremise, + + /// A server in Azure. + Azure, +} diff --git a/dotnet/src/Dax.Formatter/DaxServerMode.cs b/dotnet/src/Dax.Formatter/DaxServerMode.cs new file mode 100644 index 0000000..2ed9329 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxServerMode.cs @@ -0,0 +1,20 @@ +namespace Dax.Formatter; + +/// +/// The mode of the Analysis Services server, for . The members have the names +/// and values of Microsoft.AnalysisServices.ServerMode. +/// +public enum DaxServerMode +{ + /// The multidimensional mode. + Multidimensional, + + /// The SharePoint integration mode. + SharePoint, + + /// The tabular mode. + Tabular, + + /// The default mode of the server. + Default, +} diff --git a/dotnet/src/Dax.Formatter/DaxServerType.cs b/dotnet/src/Dax.Formatter/DaxServerType.cs new file mode 100644 index 0000000..4cf651a --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxServerType.cs @@ -0,0 +1,31 @@ +namespace Dax.Formatter; + +/// +/// The kind of server the model is on, for . +/// +public enum DaxServerType +{ + /// SQL Server Analysis Services. + AnalysisServices, + + /// Power BI Desktop. + PowerBIDesktop, + + /// Power BI Report Server. + PowerBIReportServer, + + /// Power Pivot for Excel. + PowerPivot, + + /// The integrated workspace of SQL Server Data Tools. + Ssdt, + + /// Azure Analysis Services. + AzureAnalysisServices, + + /// The Power BI service. + PowerBIService, + + /// A model that is not on a server, such as a file. + Offline, +} diff --git a/dotnet/src/Dax.Formatter/DaxServerTypes.cs b/dotnet/src/Dax.Formatter/DaxServerTypes.cs deleted file mode 100644 index a00e68a..0000000 --- a/dotnet/src/Dax.Formatter/DaxServerTypes.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace Dax.Formatter; - -/// -/// The values of that the service knows. -/// -public static class DaxServerTypes -{ - /// SQL Server Analysis Services. - public const string AnalysisServices = "SSAS"; - - /// Power BI Desktop. - public const string PowerBIDesktop = "PBI Desktop"; - - /// Power BI Report Server. - public const string PowerBIReportServer = "PBI Report Server"; - - /// Power Pivot for Excel. - public const string PowerPivot = "PowerPivot"; - - /// The integrated workspace of SQL Server Data Tools. - public const string Ssdt = "SSDT"; - - /// Azure Analysis Services. - public const string AzureAnalysisServices = "AzureAS"; - - /// The Power BI service. - public const string PowerBIService = "PBI Service"; - - /// A model that is not on a server, such as a file. - public const string Offline = "Offline"; -} diff --git a/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs b/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs index 565ad63..4fab689 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs @@ -29,6 +29,77 @@ public void From_ModelInfo_KeepsOnlyTheHashesOfTheNames() Assert.Equal("6341a49658aeebdfbcc648aea92b6005b393d3f89205cf56166c5626c80b9863", settings.DatabaseNameHash); } + [Theory] + [InlineData(DaxServerType.AnalysisServices, "SSAS")] + [InlineData(DaxServerType.PowerBIDesktop, "PBI Desktop")] + [InlineData(DaxServerType.PowerBIReportServer, "PBI Report Server")] + [InlineData(DaxServerType.PowerPivot, "PowerPivot")] + [InlineData(DaxServerType.Ssdt, "SSDT")] + [InlineData(DaxServerType.AzureAnalysisServices, "AzureAS")] + [InlineData(DaxServerType.PowerBIService, "PBI Service")] + [InlineData(DaxServerType.Offline, "Offline")] + public void From_ServerType_TakesTheValueOfTheService(DaxServerType serverType, string expected) + { + var options = new DaxFormatOptions { ModelInfo = new DaxModelInfo { ServerType = serverType } }; + + var settings = FormatSettings.From(options); + + Assert.Equal(expected, settings.ServerType); + } + + [Fact] + public void From_ServerEnumerations_TakeTheNamesOfTheMembers() + { + var options = new DaxFormatOptions + { + ModelInfo = new DaxModelInfo + { + ServerMode = DaxServerMode.SharePoint, + ServerEdition = DaxServerEdition.StandardDeveloper64, + ServerLocation = DaxServerLocation.Azure, + }, + }; + + var settings = FormatSettings.From(options); + + Assert.Equal( + ("SharePoint", "StandardDeveloper64", "Azure"), + (settings.ServerMode, settings.ServerEdition, settings.ServerLocation)); + } + + [Fact] + public void From_ModelInfoWithoutServerValues_SendsNone() + { + var options = new DaxFormatOptions { ModelInfo = new DaxModelInfo() }; + + var settings = FormatSettings.From(options); + + Assert.Equal( + (null, null, null, null), + (settings.ServerType, settings.ServerMode, settings.ServerEdition, settings.ServerLocation)); + } + + [Theory] + [InlineData(8, 0, 0, 0)] + [InlineData(0, -1, 0, 0)] + [InlineData(0, 0, 16, 0)] + [InlineData(0, 0, 0, 2)] + public void From_ServerValueOutsideItsEnumeration_Throws(int serverType, int serverMode, int serverEdition, int serverLocation) + { + var options = new DaxFormatOptions + { + ModelInfo = new DaxModelInfo + { + ServerType = (DaxServerType)serverType, + ServerMode = (DaxServerMode)serverMode, + ServerEdition = (DaxServerEdition)serverEdition, + ServerLocation = (DaxServerLocation)serverLocation, + }, + }; + + Assert.Throws("options", () => FormatSettings.From(options)); + } + [Fact] public void From_Options_CopiesTheValues() { diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs index 6bf6762..ed64808 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs @@ -23,10 +23,10 @@ public static DaxFormatOptions Read(JsonElement options) { ServerName = ReadString(model, "serverName"), DatabaseName = ReadString(model, "databaseName"), - ServerType = ReadString(model, "serverType"), - ServerMode = ReadString(model, "serverMode"), - ServerEdition = ReadString(model, "serverEdition"), - ServerLocation = ReadString(model, "serverLocation"), + ServerType = ReadOptionalEnum(model, "serverType"), + ServerMode = ReadOptionalEnum(model, "serverMode"), + ServerEdition = ReadOptionalEnum(model, "serverEdition"), + ServerLocation = ReadOptionalEnum(model, "serverLocation"), ServerVersion = ReadString(model, "serverVersion"), CompatibilityLevel = model.TryGetProperty("compatibilityLevel", out var level) ? level.GetInt32() : null, }; @@ -42,11 +42,17 @@ public static DaxKind ReadKind(JsonElement testCase) private static TEnum ReadEnum(JsonElement element, string name) where TEnum : struct, Enum + { + return ReadOptionalEnum(element, name) ?? default; + } + + private static TEnum? ReadOptionalEnum(JsonElement element, string name) + where TEnum : struct, Enum { var value = ReadString(element, name); if (value is null) { - return default; + return null; } return Enum.TryParse(value, ignoreCase: true, out var result) diff --git a/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json index 573ddc5..2f113f1 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json @@ -118,10 +118,10 @@ "modelInfo": { "serverName": "MyServerName1", "databaseName": "MyDatabaseName1", - "serverType": "SSAS", - "serverMode": "Tabular", - "serverEdition": "Enterprise64", - "serverLocation": "OnPremise", + "serverType": "analysisServices", + "serverMode": "tabular", + "serverEdition": "enterprise64", + "serverLocation": "onPremise", "serverVersion": "16.0.143.21", "compatibilityLevel": 1600 } diff --git a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs index 2c0af30..66f3ad9 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Live/LiveServiceTests.cs @@ -95,10 +95,10 @@ public async Task FormatAsync_SemicolonAndCommaWithEveryModelProperty_FormatsThe { ServerName = "MyServerName1", DatabaseName = "MyDatabaseName1", - ServerType = DaxServerTypes.AnalysisServices, - ServerMode = "Tabular", - ServerEdition = "Enterprise64", - ServerLocation = "OnPremise", + ServerType = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.OnPremise, ServerVersion = "16.0.143.21", CompatibilityLevel = 1600, }, diff --git a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt index a352119..12a52bb 100644 --- a/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt @@ -58,27 +58,52 @@ enum Dax.Formatter.DaxLineStyle LongLine = 0 ShortLine = 1 sealed class Dax.Formatter.DaxModelInfo + Dax.Formatter.DaxServerEdition? ServerEdition { get; set; } + Dax.Formatter.DaxServerLocation? ServerLocation { get; set; } + Dax.Formatter.DaxServerMode? ServerMode { get; set; } + Dax.Formatter.DaxServerType? ServerType { get; set; } System.Int32? CompatibilityLevel { get; set; } System.String DatabaseName { get; set; } - System.String ServerEdition { get; set; } - System.String ServerLocation { get; set; } - System.String ServerMode { get; set; } System.String ServerName { get; set; } - System.String ServerType { get; set; } System.String ServerVersion { get; set; } constructor() enum Dax.Formatter.DaxSeparatorStyle CommaAndPoint = 0 SemicolonAndComma = 1 -static class Dax.Formatter.DaxServerTypes - const System.String AnalysisServices = "SSAS" - const System.String AzureAnalysisServices = "AzureAS" - const System.String Offline = "Offline" - const System.String PowerBIDesktop = "PBI Desktop" - const System.String PowerBIReportServer = "PBI Report Server" - const System.String PowerBIService = "PBI Service" - const System.String PowerPivot = "PowerPivot" - const System.String Ssdt = "SSDT" +enum Dax.Formatter.DaxServerEdition + BusinessIntelligence = 10 + BusinessIntelligence64 = 11 + Developer = 4 + Developer64 = 5 + Enterprise = 2 + Enterprise64 = 3 + EnterpriseCore = 12 + EnterpriseCore64 = 13 + Evaluation = 6 + Evaluation64 = 7 + LocalCube = 8 + LocalCube64 = 9 + Standard = 0 + Standard64 = 1 + StandardDeveloper = 14 + StandardDeveloper64 = 15 +enum Dax.Formatter.DaxServerLocation + Azure = 1 + OnPremise = 0 +enum Dax.Formatter.DaxServerMode + Default = 3 + Multidimensional = 0 + SharePoint = 1 + Tabular = 2 +enum Dax.Formatter.DaxServerType + AnalysisServices = 0 + AzureAnalysisServices = 5 + Offline = 7 + PowerBIDesktop = 1 + PowerBIReportServer = 2 + PowerBIService = 6 + PowerPivot = 3 + Ssdt = 4 enum Dax.Formatter.DaxSpacingStyle NoSpaceAfterFunction = 1 SpaceAfterFunction = 0 diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs index 14103b8..2e2deac 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -124,7 +124,7 @@ public async Task FormatAsync_OptionsSample_SendsTheOptions() SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, ModelInfo = new DaxModelInfo { - ServerType = DaxServerTypes.PowerBIDesktop, + ServerType = DaxServerType.PowerBIDesktop, DatabaseName = "Contoso", }, }; From 79baa6af627ae37487276e5104c2bda8b3fe93e2 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:32:14 +0100 Subject: [PATCH 25/29] docs: say that the name hash must stay the one of 1.x The service counts distinct servers and databases by their hash across every client and version, so the hash of 2.0 must equal the one of 1.x. The fixture already holds the 1.x test vectors. --- docs/design/rest-api.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/design/rest-api.md b/docs/design/rest-api.md index e08e070..113f2d5 100644 --- a/docs/design/rest-api.md +++ b/docs/design/rest-api.md @@ -132,6 +132,7 @@ What the service does with a text: - An empty name is hashed too: `""` becomes `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. A missing name is not sent. - The .NET client hashes when it copies the options of a call, and keeps only the hashes. The TypeScript port hashes while it builds the request. - Both clients test the same vectors: the fixture `name-hashes.json` in .NET and `hash.test.ts` in TypeScript. +- The hash never changes: the service counts distinct names across every client and version, so a different hash would count the same server twice. `Dax.Formatter` 1.x computed it the same way, and its test vectors are the first four cases of `name-hashes.json`. ## Caller identity From ad8935f8bb259c31a44ead0c65ca51a418001d49 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:34:15 +0100 Subject: [PATCH 26/29] docs: shorten the name hash note and record its case debt - rest-api.md says only that the hash is the one of 1.x. - B-24: the hash depends on the case of the name. --- docs/backlog.md | 3 ++- docs/design/rest-api.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/backlog.md b/docs/backlog.md index a64b989..5ec267b 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,6 +1,6 @@ # Backlog -Next ID: B-24 +Next ID: B-25 Reports and requests from users stay in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues); an item here links its issue instead of copying it. @@ -30,4 +30,5 @@ Reports and requests from users stay in [GitHub Issues](https://github.com/sql-b - B-14 The MCP server says that `formatted` is null for invalid DAX, in the tool description in `typescript/packages/daxformatter-mcp/src/format-tool.ts` and in the comment of `formatted` in `src/daxformatter/types.ts`, while the service returns an empty string ([REST API, Response](design/rest-api.md#response)). Cost: an AI client that follows the tool description misses the empty string. Repay by fixing both texts, which raises the MCP server's version. - B-15 Releases are tied to `master` only by the branch guard of the release workflows: a run uses the workflow file of the commit it runs on ([Workflows](https://docs.github.com/en/actions/concepts/workflows-and-actions/workflows)), so a branch whose copy drops the guard runs with the repository secrets, and the nuget.org Trusted Publishing policy names the workflow file, not a branch. Cost: whoever can push a branch and run workflows can publish from it. Repay: remove the nuget.org policy for `release.yml`, the .NET release workflow's name before the move in `6df1bf0`; run each release job in a GitHub environment that only `master` can deploy to, which holds the release secrets and which the nuget.org policy names ([Trusted Publishing](https://learn.microsoft.com/en-us/nuget/nuget-org/trusted-publishing), [environments](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)). - B-16 Some files under `dotnet/` don't follow `.editorconfig`: a missing or unwanted byte order mark, no final newline, trailing whitespace, and tabs, including in `Dax.Formatter.sln`, which Visual Studio writes with tabs. Cost: saving one in an editor that applies `.editorconfig` puts changes unrelated to the edit in the diff. Repay with one commit that only normalizes these files, and a `[*.sln]` section with `indent_style = tab`. +- B-24 The hash of a server or database name is not normalized: the same name in different case gives different hashes. Cost: the same server is counted more than once. Repay: decide whether to normalize the name before hashing. - B-22 The service rejects three kinds of valid DAX with a syntax error: a function without parameters, a function parameter with a default value and, sent as the expression of a model object, an expression with `=>` inside a string or a comment ([client API](design/client-api.md#limits-of-the-service)). Cost: no client can format them, and each returns the syntax error to its caller. Repay in the service, which is outside this repository; then remove the limits from `client-api.md` and `rest-api.md`, and update the live test that pins them. diff --git a/docs/design/rest-api.md b/docs/design/rest-api.md index 113f2d5..c803930 100644 --- a/docs/design/rest-api.md +++ b/docs/design/rest-api.md @@ -132,7 +132,7 @@ What the service does with a text: - An empty name is hashed too: `""` becomes `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. A missing name is not sent. - The .NET client hashes when it copies the options of a call, and keeps only the hashes. The TypeScript port hashes while it builds the request. - Both clients test the same vectors: the fixture `name-hashes.json` in .NET and `hash.test.ts` in TypeScript. -- The hash never changes: the service counts distinct names across every client and version, so a different hash would count the same server twice. `Dax.Formatter` 1.x computed it the same way, and its test vectors are the first four cases of `name-hashes.json`. +- The hash is the same as in `Dax.Formatter` 1.x. ## Caller identity From 7e4eca0cd2beb0e782eda87e59df268d7a5193ab Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:42:40 +0100 Subject: [PATCH 27/29] chore(dotnet): mark the release as 2.0.0-beta.1 and shorten the readme - version.json holds 2.0.0-beta.1: the first release of 2.0 is a preview. - The package description is one line. - The readme keeps only installing, formatting a query and the measures of a model, the description of the model, the formatting options and the errors; it asks callers to fill ModelInfo. - The readme samples follow it; the polyfill that only the removed record sample needed is gone. --- ...lers-items-and-grow-it-only-by-addition.md | 2 +- dotnet/README.md | 196 +++------------- dotnet/src/Dax.Formatter/Dax.Formatter.csproj | 2 +- .../Polyfills/IsExternalInit.cs | 8 - .../Readme/ReadmeSamples.cs | 217 +++--------------- .../Readme/ReadmeService.cs | 2 - dotnet/version.json | 2 +- 7 files changed, 61 insertions(+), 368 deletions(-) delete mode 100644 dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs diff --git a/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md b/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md index 6619419..8b21f20 100644 --- a/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md +++ b/docs/decisions/0007-keep-the-batch-api-on-the-callers-items-and-grow-it-only-by-addition.md @@ -46,7 +46,7 @@ Chosen options: "The caller's items with a text selector, next to texts" and "A ### The shape of 2.0 - `FormatBatchAsync(texts)` and `FormatBatchAsync(items, textSelector)` return an `IReadOnlyList` with one result for each input, in its order. The items version gives each result its item in `Item`. -- Objects of different types go in one call through a small type of the caller, which holds the text and what to do with the result. So do several texts of one object, with one item for each text. The package readme shows such a type. +- Objects of different types go in one call through a small type of the caller, which holds the text and what to do with the result. So do several texts of one object, with one item for each text. - A batch is atomic: it returns every result, or throws `DaxFormatterException`. On a failure, `TextIndexes` says which texts the failed request carried and `OperationId` which call failed. - A syntax error is a value in the result of its text. - `Task` and `IProgress` serve long calls; there is no stream. diff --git a/dotnet/README.md b/dotnet/README.md index d0564b5..218ca17 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -1,16 +1,14 @@ # Dax.Formatter [![CI](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml/badge.svg)](https://github.com/sql-bi/DaxFormatter/actions/workflows/dotnet-ci.yml) -`Dax.Formatter` is the .NET client of [DAX Formatter](https://www.daxformatter.com), the service by SQLBI that formats DAX code following the [rules for DAX code formatting](https://www.sqlbi.com/articles/rules-for-dax-code-formatting/) and reports its syntax errors. One call formats one text or the thousands of measures of a model. +`Dax.Formatter` is the .NET client of [DAX Formatter](https://www.daxformatter.com), the service by SQLBI that formats DAX code and reports its syntax errors. -## Getting started - -Install the package, which targets .NET Standard 2.0 and .NET 10: +## Install ```bash dotnet add package Dax.Formatter ``` -Create a client and format a query. The types are in the `Dax.Formatter` namespace. +## Format a query ```csharp var client = new DaxFormatterClient(); @@ -22,15 +20,11 @@ Console.WriteLine(result.FormattedText); // FILTER ( Customer, Customer[Country] = "Italy" ) ``` -- The client is thread-safe: create one and reuse it for the life of the application. -- The DAX text goes to the service, which formats it. Nothing else about the model leaves the machine, unless you fill `DaxModelInfo`, whose server and database names are sent only as hashes. -- Every method is asynchronous and takes a `CancellationToken`. - -## Usage +Create one client and reuse it: it is thread-safe. -### Format the objects of a model +## Format the measures of a model -Pass your own objects and a function that returns the DAX of each one. Every result carries its object in `Item`, so nothing has to be matched by position. +Pass your objects and a function that returns the DAX of each one. Each result carries its object in `Item`. ```csharp var options = new DaxFormatOptions { Kind = DaxKind.Expression }; @@ -51,182 +45,54 @@ foreach (var result in results) } ``` -Here `Measure` and `model` stand for the types of your application: any type works. - -- `DaxKind.Expression` says that each text is the DAX of one model object without its name: a measure, a calculated column, a calculated table, a calculation item or the body of a user-defined function. The formatted text has no name either. -- `DaxKind.Auto`, the default, sends the text as it is. Use it for a query and for a text that carries its own name, such as `[Margin] := [Sales] - [Cost]`. Don't use it for the DAX of a model object: without a name, the service can take an expression such as `Customer[Name] = "A"` for a definition named `Customer[Name]`. -- The client splits a large call into several requests and sends a few of them at a time. The results come back in the order of the input, all of them or an exception. -- A blank text gets an empty formatted text, without a request. -- `FormatBatchAsync` also takes plain strings: `await client.FormatBatchAsync(texts)`. +- Use `DaxKind.Expression` for the DAX of a model object: a measure, a calculated column or table, a calculation item, a user-defined function. Use the default, `DaxKind.Auto`, for queries. +- One call takes thousands of texts. The results come back in the order of the input. -### Format objects of different types +## Describe your model -One call formats the objects of a model whatever their type, because `DaxKind.Expression` covers them all. Declare a small type that holds the name of an object, its DAX and a function that writes the formatted text back to it: +DAX Formatter is free. Tell it where your DAX comes from: it helps SQLBI see how the service is used and where to improve it. ```csharp -sealed record ModelExpression(string Name, string Expression, Action Update); -``` - -Then put every object in one list: - -```csharp -var items = new List(); - -foreach (var measure in model.Measures) -{ - items.Add(new(measure.Name, measure.Expression, text => measure.Expression = text)); -} - -foreach (var function in model.Functions) -{ - items.Add(new(function.Name, function.Expression, text => function.Expression = text)); -} - -var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - -var results = await client.FormatBatchAsync(items, item => item.Expression, options); - -foreach (var result in results) +var options = new DaxFormatOptions { - if (result.Succeeded) - { - result.Item.Update(result.FormattedText); - } - else + ModelInfo = new DaxModelInfo { - Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); - } -} + ServerName = "MyServer", + DatabaseName = "Contoso", + ServerType = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.OnPremise, + ServerVersion = "16.0.143.21", + CompatibilityLevel = 1600, + }, +}; ``` -`Update` is not part of the client: it is the function stored in the item, which the result gives back in `Item`. An object with several DAX texts, such as a measure with a format string expression, adds one item for each text. Only texts of the other kind need a call of their own, such as queries, which take `DaxKind.Auto`. +- `ModelInfo` doesn't change the formatting: it is used only for anonymous statistics. +- `ServerName` and `DatabaseName` leave your machine only as SHA-256 hashes, never as names. +- `ServerMode`, `ServerEdition` and `ServerLocation` have the names of the TOM enums: convert them by name, such as `Enum.Parse(server.Edition.ToString())`. -### Options +## Formatting options ```csharp var options = new DaxFormatOptions { - Kind = DaxKind.Expression, LineStyle = DaxLineStyle.ShortLine, SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, - ModelInfo = new DaxModelInfo - { - ServerType = DaxServerType.PowerBIDesktop, - DatabaseName = "Contoso", - }, }; - -DaxFormatResult result = await client.FormatAsync("DIVIDE([Sales Amount]; 1,5)", options); ``` - `LineStyle`: `LongLine` (default) keeps an expression on one line while it fits, `ShortLine` puts each argument on its own line. - `SpacingStyle`: `SpaceAfterFunction` (default) writes `SUM ( x )`, `NoSpaceAfterFunction` writes `SUM( x )`. -- `SeparatorStyle`: the separators that your DAX uses. `CommaAndPoint` (default) is `DIVIDE ( 1.5, 2 )`, `SemicolonAndComma` is `DIVIDE ( 1,5; 2 )`. -- `ModelInfo` is optional and doesn't change the formatting: the service uses it for anonymous usage statistics. `ServerName` and `DatabaseName` are sent as SHA-256 hashes, never as names. - -### Syntax errors - -A syntax error is not an exception: it is the result of that text. - -```csharp -DaxFormatResult result = await client.FormatAsync("SUMX(Sales, Sales[Amount] *", options); - -if (!result.Succeeded) -{ - foreach (DaxSyntaxError error in result.Errors) - { - Console.WriteLine($"Line {error.Line + 1}, column {error.Column + 1}: {error.Message}"); - } -} -``` - -- `Succeeded` is `false`, `FormattedText` is `null`, and `Errors` has at least one error. -- `Line` and `Column` are zero-based and refer to `OriginalText`, the text you passed: lines are separated by `\n`, and `Column` is an index into the UTF-16 characters of the line, so a tab counts as one. An error at the end of the text has the length of the last line as its column. - -### Functions - -With `DaxKind.Expression`, the body of a [user-defined function](https://learn.microsoft.com/dax/best-practices/dax-user-defined-functions) is formatted like any other expression. The client recognizes it by its parameter list followed by `=>`. - -```csharp -var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - -DaxFormatResult result = await client.FormatAsync( - "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)", options); - -Console.WriteLine(result.FormattedText); -// ( -// amount : NUMERIC, -// rate : NUMERIC -// ) => -// amount * ( 1 + rate ) -``` - -### Progress and cancellation - -```csharp -var progress = new Progress( - info => Console.WriteLine($"{info.Completed} of {info.Total} expressions formatted")); - -IReadOnlyList results = - await client.FormatBatchAsync(expressions, options, progress, cancellationToken); -``` - -`Completed` counts texts, grows as the requests of the call complete, and never decreases. A cancelled call throws `OperationCanceledException`. - -### Failures of the service - -When the service or the network fails, the call throws `DaxFormatterException` and returns no result. - -```csharp -try -{ - IReadOnlyList results = await client.FormatBatchAsync(expressions); - Console.WriteLine($"{results.Count} expressions formatted"); -} -catch (DaxFormatterException exception) -{ - Console.WriteLine($"{exception.Reason}: {exception.Message}"); - Console.WriteLine($"Request {exception.RequestId}, status {exception.StatusCode}"); -} -``` - -- `Reason` is `Timeout`, `NetworkError`, `HttpError` or `InvalidResponse`. The message names the texts of the failed request by their indexes. -- Before it gives up, the client tries again after a timeout, a network error and the statuses 408, 429, 500, 502, 503 and 504, with a growing wait, and it honors `Retry-After`. -- `RequestId` is the identifier that the client sent in the `DaxFormatter-Request-Id` header; `ServiceRequestId` is the one in the answer, when an answer arrived. Quote both when you report a problem. - -### Client options and HttpClient - -```csharp -var client = new DaxFormatterClient(new DaxFormatterClientOptions -{ - ApplicationName = "Contoso Model Tools", - ApplicationVersion = "1.4.0", - RequestTimeout = TimeSpan.FromSeconds(120), - MaxRetries = 3, - MaxConcurrentRequests = 4, -}); -``` - -- `ApplicationName` and `ApplicationVersion` tell the service which application calls it, for usage statistics. They default to the name and the file version of the entry assembly. -- `RequestTimeout` (60 seconds) is the wait for the answer to one request; `MaxRetries` (2) is how many times a request is sent again; `MaxConcurrentRequests` (2) is how many requests of one call are in progress at the same time. - -Without an `HttpClient`, all the clients share one that lives as long as the process and doesn't check certificate revocation. To control the handler, the proxy or the certificate checks, pass your own: - -```csharp -var client = new DaxFormatterClient(httpClient); -``` - -The client never changes or disposes an `HttpClient` it is given, and ignores its `BaseAddress`. If its `Timeout` is shorter than `RequestTimeout`, the shorter one wins. With `IHttpClientFactory`, register it as a typed client: `services.AddHttpClient()`. The client then takes the `DaxFormatterClientOptions` registered in the container, if any. - -On .NET Framework the shared `HttpClient` opens at most [`ServicePointManager.DefaultConnectionLimit`](https://learn.microsoft.com/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit) connections to the service, which is 2 unless the application changes it. Raise that limit, or pass your own `HttpClient`, before you raise `MaxConcurrentRequests` or run several calls at the same time: a request that waits for a connection uses up its `RequestTimeout`. - -To replace the client in the tests of your application, derive from it and override `FormatAsync` and the `FormatBatchAsync` that takes strings: both are virtual, the one that takes items calls the one that takes strings, and the parameterless constructor does no work. `DaxFormatResult.Success` and `DaxFormatResult.Failure` create the results. +- `SeparatorStyle`: `CommaAndPoint` (default) for `DIVIDE ( 1.5, 2 )`, `SemicolonAndComma` for `DIVIDE ( 1,5; 2 )`. -## Additional documentation +## Errors -- [SQLBI Docs](https://docs.sqlbi.com/dax-formatter/): the user documentation of DAX Formatter. +- A syntax error doesn't throw: `Succeeded` is `false`, and `Errors` lists each error with its `Message` and its zero-based `Line` and `Column`. +- When the service or the network fails, after a few retries the call throws `DaxFormatterException`. ## Feedback -Report bugs and request features in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues). Report security vulnerabilities privately, as the [security policy](https://github.com/sql-bi/DaxFormatter/blob/master/SECURITY.md) explains. +Report bugs and request features in [GitHub Issues](https://github.com/sql-bi/DaxFormatter/issues). diff --git a/dotnet/src/Dax.Formatter/Dax.Formatter.csproj b/dotnet/src/Dax.Formatter/Dax.Formatter.csproj index 2658148..962c757 100644 --- a/dotnet/src/Dax.Formatter/Dax.Formatter.csproj +++ b/dotnet/src/Dax.Formatter/Dax.Formatter.csproj @@ -12,7 +12,7 @@ SQLBI Alberto Spelta, Marco Russo Dax Formatter client libraries - Client library for the DAX Formatter service (daxformatter.com): formats DAX queries, measures, columns and functions, one or thousands in a call, and reports their syntax errors. + Client library for the DAX Formatter service (daxformatter.com). Dax.Formatter DAX;FORMATTER;SQLBI;TABULAR;SSAS package-icon.png diff --git a/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs b/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs deleted file mode 100644 index dd68c70..0000000 --- a/dotnet/tests/Dax.Formatter.Tests/Polyfills/IsExternalInit.cs +++ /dev/null @@ -1,8 +0,0 @@ -#if !NET -namespace System.Runtime.CompilerServices; - -// The record of the readme samples needs it for its init accessors, and .NET Framework doesn't have it. -internal static class IsExternalInit -{ -} -#endif diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs index 2e2deac..78f7383 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -1,7 +1,4 @@ -using System.Net; -using System.Net.Http; -using Dax.Formatter.Tests.Fakes; -using Xunit; +using Xunit; namespace Dax.Formatter.Tests.Readme; @@ -65,51 +62,39 @@ public async Task FormatBatchAsync_ModelObjectsSample_UpdatesTheMeasuresThatAreV } [Fact] - public async Task FormatBatchAsync_MixedObjectsSample_UpdatesTheObjectsOfEveryType() + public async Task FormatAsync_ModelInfoSample_SendsTheDescriptionOfTheModel() { var client = new DaxFormatterClient(); - var model = new Model(); - - #region MixedObjects - var items = new List(); - - foreach (var measure in model.Measures) - { - items.Add(new(measure.Name, measure.Expression, text => measure.Expression = text)); - } - - foreach (var function in model.Functions) - { - items.Add(new(function.Name, function.Expression, text => function.Expression = text)); - } - - var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - - var results = await client.FormatBatchAsync(items, item => item.Expression, options); - foreach (var result in results) + #region ModelInfo + var options = new DaxFormatOptions { - if (result.Succeeded) - { - result.Item.Update(result.FormattedText); - } - else + ModelInfo = new DaxModelInfo { - Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); - } - } + ServerName = "MyServer", + DatabaseName = "Contoso", + ServerType = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.OnPremise, + ServerVersion = "16.0.143.21", + CompatibilityLevel = 1600, + }, + }; #endregion - Assert.Equal("CALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )", model.Measures[0].Expression); + await client.FormatAsync("EVALUATE ModelInfo", options); + + var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0] == "EVALUATE ModelInfo").Json; + Assert.Equal( + ("SSAS", "Tabular", "Enterprise64", "OnPremise"), + (body.GetProperty("serverType").GetString(), body.GetProperty("serverMode").GetString(), + body.GetProperty("serverEdition").GetString(), body.GetProperty("serverLocation").GetString())); Assert.Equal( - "(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", model.Functions[0].Expression); - Assert.Equal("Broken", results.Single(result => !result.Succeeded).Item.Name); + "5e3e900585e7834b034d4f17187e521b3c7b7de0d1637f79de4b63717d4f0783", + body.GetProperty("serverName").GetString()); } - #region MixedObjectsType - sealed record ModelExpression(string Name, string Expression, Action Update); - #endregion - [Fact] public async Task FormatAsync_OptionsSample_SendsTheOptions() { @@ -118,149 +103,19 @@ public async Task FormatAsync_OptionsSample_SendsTheOptions() #region Options var options = new DaxFormatOptions { - Kind = DaxKind.Expression, LineStyle = DaxLineStyle.ShortLine, SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, - ModelInfo = new DaxModelInfo - { - ServerType = DaxServerType.PowerBIDesktop, - DatabaseName = "Contoso", - }, }; - - DaxFormatResult result = await client.FormatAsync("DIVIDE([Sales Amount]; 1,5)", options); #endregion - var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0].EndsWith("1,5)", StringComparison.Ordinal)).Json; - Assert.True(result.Succeeded); + await client.FormatAsync("EVALUATE Options", options); + + var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0] == "EVALUATE Options").Json; Assert.Equal((1, true), (body.GetProperty("maxLineLength").GetInt32(), body.GetProperty("skipSpaceAfterFunctionName").GetBoolean())); Assert.Equal((";", ","), (body.GetProperty("listSeparator").GetString(), body.GetProperty("decimalSeparator").GetString())); } - [Fact] - public async Task FormatAsync_SyntaxErrorsSample_ReadsThePositionOfTheError() - { - var client = new DaxFormatterClient(); - var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - - #region SyntaxErrors - DaxFormatResult result = await client.FormatAsync("SUMX(Sales, Sales[Amount] *", options); - - if (!result.Succeeded) - { - foreach (DaxSyntaxError error in result.Errors) - { - Console.WriteLine($"Line {error.Line + 1}, column {error.Column + 1}: {error.Message}"); - } - } - #endregion - - Assert.Equal((0, 27), (result.Errors[0].Line, result.Errors[0].Column)); - } - - [Fact] - public async Task FormatAsync_FunctionsSample_FormatsTheBodyOfTheFunction() - { - var client = new DaxFormatterClient(); - - #region Functions - var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - - DaxFormatResult result = await client.FormatAsync( - "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)", options); - - Console.WriteLine(result.FormattedText); - // ( - // amount : NUMERIC, - // rate : NUMERIC - // ) => - // amount * ( 1 + rate ) - #endregion - - Assert.Equal( - "(\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n) =>\r\namount * ( 1 + rate )", result.FormattedText); - } - - [Fact] - public async Task FormatBatchAsync_ProgressSample_ReturnsEveryResult() - { - var client = new DaxFormatterClient(); - var options = new DaxFormatOptions { Kind = DaxKind.Expression }; - var expressions = Enumerable.Range(1, 600).Select(number => "[Sales] * " + number).ToList(); - using var cancellation = new CancellationTokenSource(); - var cancellationToken = cancellation.Token; - - #region Progress - var progress = new Progress( - info => Console.WriteLine($"{info.Completed} of {info.Total} expressions formatted")); - - IReadOnlyList results = - await client.FormatBatchAsync(expressions, options, progress, cancellationToken); - #endregion - - Assert.Equal(expressions, results.Select(result => result.FormattedText)); - } - - [Fact] - public async Task FormatBatchAsync_FailuresSample_CatchesTheFailureOfTheService() - { - using var handler = new FakeFormatterHandler(Respond.Status(HttpStatusCode.BadRequest)); - using var httpClient = new HttpClient(handler); - var client = new DaxFormatterClient(httpClient); - string[] expressions = ["[Sales] * 2"]; - - #region Failures - try - { - IReadOnlyList results = await client.FormatBatchAsync(expressions); - Console.WriteLine($"{results.Count} expressions formatted"); - } - catch (DaxFormatterException exception) - { - Console.WriteLine($"{exception.Reason}: {exception.Message}"); - Console.WriteLine($"Request {exception.RequestId}, status {exception.StatusCode}"); - } - #endregion - - Assert.Single(handler.Requests); - } - - [Fact] - public async Task Constructor_ClientOptionsSample_IdentifiesTheApplication() - { - #region ClientOptions - var client = new DaxFormatterClient(new DaxFormatterClientOptions - { - ApplicationName = "Contoso Model Tools", - ApplicationVersion = "1.4.0", - RequestTimeout = TimeSpan.FromSeconds(120), - MaxRetries = 3, - MaxConcurrentRequests = 4, - }); - #endregion - - await client.FormatAsync("EVALUATE Tools"); - - var body = ReadmeService.Handler.Requests.Last(request => request.Dax[0] == "EVALUATE Tools").Json; - Assert.Equal("Contoso Model Tools", body.GetProperty("callerApp").GetString()); - } - - [Fact] - public async Task Constructor_HttpClientSample_SendsTheRequestsWithIt() - { - using var handler = new FakeFormatterHandler(Respond.Echo); - using var httpClient = new HttpClient(handler); - - #region HttpClient - var client = new DaxFormatterClient(httpClient); - #endregion - - await client.FormatAsync("EVALUATE Sales"); - - Assert.Single(handler.Requests); - } - private sealed class Measure { public Measure(string name, string expression) @@ -282,23 +137,5 @@ private sealed class Model new Measure("Broken", "SUMX(Sales, Sales[Amount] *"), new Measure("Cost Ratio", "DIVIDE([Sales Amount], [Total Cost])"), ]; - - public List Functions { get; } = - [ - new Function("AddRate", "(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"), - ]; - } - - private sealed class Function - { - public Function(string name, string expression) - { - Name = name; - Expression = expression; - } - - public string Name { get; } - - public string Expression { get; set; } } } diff --git a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs index 3607fbe..b70e98c 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeService.cs @@ -18,8 +18,6 @@ internal static class ReadmeService "[x] :=\r\nCALCULATE ( SUM ( Sales[Amount] ), Sales[Quantity] > 0 )\r\n", ["[x] :=\nDIVIDE([Sales Amount], [Total Cost])"] = "[x] :=\r\nDIVIDE ( [Sales Amount], [Total Cost] )\r\n", - ["FUNCTION x =\n(amount : NUMERIC, rate : NUMERIC) => amount * (1 + rate)"] = - "FUNCTION x = (\r\n amount : NUMERIC,\r\n rate : NUMERIC\r\n ) =>\r\n amount * ( 1 + rate )\r\n", }; // The service reports the end of the input as the line after the last one. diff --git a/dotnet/version.json b/dotnet/version.json index b3ca6f6..12042a8 100644 --- a/dotnet/version.json +++ b/dotnet/version.json @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", - "version": "2.0.0", + "version": "2.0.0-beta.1", "assemblyVersion": { "precision": "major" }, From 26284eac4bf078ec7087bde45495e2aebf9af030 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:49:48 +0100 Subject: [PATCH 28/29] docs(dotnet): reword the request to describe the model --- dotnet/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dotnet/README.md b/dotnet/README.md index 218ca17..0d5d225 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -50,7 +50,7 @@ foreach (var result in results) ## Describe your model -DAX Formatter is free. Tell it where your DAX comes from: it helps SQLBI see how the service is used and where to improve it. +Optionally, describe the model your DAX comes from. The data is anonymized, and helps SQLBI understand how DAX Formatter is used and improve it. ```csharp var options = new DaxFormatOptions @@ -69,7 +69,7 @@ var options = new DaxFormatOptions }; ``` -- `ModelInfo` doesn't change the formatting: it is used only for anonymous statistics. +- `ModelInfo` doesn't change the formatting. - `ServerName` and `DatabaseName` leave your machine only as SHA-256 hashes, never as names. - `ServerMode`, `ServerEdition` and `ServerLocation` have the names of the TOM enums: convert them by name, such as `Enum.Parse(server.Edition.ToString())`. From b19103b7955290c3f1f861f8085aa0875b077751 Mon Sep 17 00:00:00 2001 From: Alberto Spelta Date: Sun, 22 Nov 2026 18:51:25 +0100 Subject: [PATCH 29/29] docs(dotnet): name the target frameworks in the readme --- dotnet/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dotnet/README.md b/dotnet/README.md index 0d5d225..e53cc9d 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -4,6 +4,8 @@ ## Install +The package targets .NET Standard 2.0 and .NET 10. + ```bash dotnet add package Dax.Formatter ```