diff --git a/docs/backlog.md b/docs/backlog.md index 9345862..5ec267b 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,6 +1,6 @@ # Backlog -Next ID: B-17 +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. @@ -8,20 +8,27 @@ 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-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 +- 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-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/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..3468512 --- /dev/null +++ b/docs/decisions/0005-decouple-the-client-api-from-the-rest-contract.md @@ -0,0 +1,81 @@ +--- +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 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 + +* 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. +* 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. +* 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 + +- `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). +- 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/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. 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..8b21f20 --- /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. +- 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/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..eaa0d66 --- /dev/null +++ b/docs/design/client-api.md @@ -0,0 +1,88 @@ +# 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`, `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 + +- 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 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): + +- 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 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. + +## 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). + +## 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..c803930 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, 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`. -| .NET `ServerType` and TypeScript `ServerType` member | Wire value | +| .NET `DaxServerType` member, 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`, `StandardDeveloper`, `StandardDeveloper64` | +| `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,9 @@ 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. +- The hash is the same as in `Dax.Formatter` 1.x. ## Caller identity @@ -123,13 +140,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. diff --git a/dotnet/README.md b/dotnet/README.md index 82120b7..e53cc9d 100644 --- a/dotnet/README.md +++ b/dotnet/README.md @@ -1,87 +1,100 @@ +# 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 and reports its syntax errors. -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. +## Install -# 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). +The package targets .NET Standard 2.0 and .NET 10. -# 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]" ); +```bash +dotnet add package Dax.Formatter ``` -# DaxFormatterMultipleRequest -Use the `DaxFormatterMultipleRequest` class to send multiple DAX expressions in a single API call. + +## Format a query + ```csharp -var formatter = new DaxFormatterClient(); -var request = new DaxFormatterMultipleRequest -{ - 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, -}; +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" ) +``` + +Create one client and reuse it: it is thread-safe. -// 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]))" ); +## Format the measures of a model -// Send the request and wait the result -var responses = await formatter.FormatAsync(request); +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 }; -// Process the result -foreach (var response in responses) +IReadOnlyList> results = + await client.FormatBatchAsync(model.Measures, measure => measure.Expression, options); + +foreach (var result in results) { - Console.WriteLine(response.Formatted); + if (result.Succeeded) + { + result.Item.Expression = result.FormattedText; + } + else + { + Console.WriteLine($"{result.Item.Name}: {result.Errors[0].Message}"); + } } ``` -# DaxFormatterSingleRequest -Use the `DaxFormatterSingleRequest` class to send one DAX expressions in a single API call. + +- 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. + +## Describe your model + +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 formatter = new DaxFormatterClient(); -var request = new DaxFormatterSingleRequest +var options = new DaxFormatOptions { - 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, + ModelInfo = new DaxModelInfo + { + ServerName = "MyServer", + DatabaseName = "Contoso", + ServerType = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.OnPremise, + ServerVersion = "16.0.143.21", + CompatibilityLevel = 1600, + }, }; - -// Send the request and wait the result -var response = await formatter.FormatAsync(request); +``` + +- `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())`. -// Display the result -Console.WriteLine(response.Formatted); +## Formatting options + +```csharp +var options = new DaxFormatOptions +{ + LineStyle = DaxLineStyle.ShortLine, + SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, + SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, +}; ``` + +- `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`: `CommaAndPoint` (default) for `DIVIDE ( 1.5, 2 )`, `SemicolonAndComma` for `DIVIDE ( 1,5; 2 )`. + +## Errors + +- 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). 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/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..13ee636 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchPlan.cs @@ -0,0 +1,57 @@ +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]; + } + + /// 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/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..a490d5c --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/BatchRun.cs @@ -0,0 +1,167 @@ +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) when (_stop.IsCancellationRequested) + { + // 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 + { + 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); + } + + private FormatRequest CreateRequest(Chunk chunk) + { + var body = _bodyWriter.Write(_plan.GetTextsToSend(chunk), _settings); + return new FormatRequest(body, chunk.TextIndexes, _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..150ab6f --- /dev/null +++ b/dotnet/src/Dax.Formatter/Batching/Chunk.cs @@ -0,0 +1,26 @@ +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; + + /// 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]; + + /// 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/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/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..9b0269a --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/CallerIdentity.cs @@ -0,0 +1,131 @@ +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))); + } + + var libraryVersion = ToPackageVersion(ThisAssembly.AssemblyInformationalVersion); + + products.Add(new ProductInfoHeaderValue(LibraryName, ToToken(libraryVersion))); + products.Add(new ProductInfoHeaderValue(ToComment(RuntimeInformation.FrameworkDescription))); + + return products; + } + + /// + /// 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 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]; + + return parts.Length > 1 ? core + "-" + parts[1] : core; + } + + 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..44b7637 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Configuration/FormatSettings.cs @@ -0,0 +1,131 @@ +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 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); + } + + 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()); + } + + 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/Dax.Formatter.csproj b/dotnet/src/Dax.Formatter/Dax.Formatter.csproj index a32b764..962c757 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). 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/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/DaxFormatterClient.cs b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs index 54e18e9..3b6e12e 100644 --- a/dotnet/src/Dax.Formatter/DaxFormatterClient.cs +++ b/dotnet/src/Dax.Formatter/DaxFormatterClient.cs @@ -1,73 +1,244 @@ -namespace Dax.Formatter +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 { - 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 Lazy _formatter; + + /// + /// Initializes a new instance of the class with the default options. It + /// uses an that all such instances share. + /// + public DaxFormatterClient() + : this(new DaxFormatterClientOptions()) + { + } + + /// + /// 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) { - private readonly DaxFormatterHttpClient _formatter; + } + + /// + /// 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 . + /// + /// 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) + { + } - public DaxFormatterClient(string? application = null, string? version = null) + 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) { - if (application == null || version == null) + 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 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; - } + var message = FormattableString.Invariant( + $"The text selector returned null for the item at index {index}."); + throw new ArgumentException(message, nameof(textSelector)); } - _formatter = new DaxFormatterHttpClient(application, version); + texts[index] = text; } - public async Task FormatAsync(string expression, CancellationToken cancellationToken = default) - { - var request = DaxFormatterSingleRequest.CreateFrom(expression); - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); + // The options are checked here so that a wrong value throws now, like the other arguments. + _ = FormatSettings.From(options); - return response; - } + return FormatItemsAsync(copy, texts, options, progress, cancellationToken); + } - public async Task> FormatAsync(IEnumerable expressions, CancellationToken cancellationToken = default) - { - var request = DaxFormatterMultipleRequest.CreateFrom(expressions); - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); + private static HttpClient Required(HttpClient httpClient) + { + ArgumentNullException.ThrowIfNull(httpClient); + return httpClient; + } - return response; - } + 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]; + } - public async Task FormatAsync(DaxFormatterSingleRequest request, CancellationToken cancellationToken = default) + private async Task> FormatManyAsync( + string[] texts, + FormatSettings settings, + IProgress? progress, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (texts.Length == 0) { - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - return response; + return []; } - public async Task> FormatAsync(DaxFormatterMultipleRequest request, CancellationToken cancellationToken = default) + 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) { - var response = await _formatter.FormatAsync(request, cancellationToken).ConfigureAwait(false); - return response; + throw new InvalidOperationException("FormatBatchAsync must return one result for each text."); } - #region IDisposable - - public void Dispose() + var paired = new DaxFormatResult[items.Length]; + for (var index = 0; index < items.Length; index++) { - _formatter.Dispose(); + paired[index] = new DaxFormatResult(items[index], results[index]); } - #endregion + return paired; } } 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..4daeda6 --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterException.cs @@ -0,0 +1,107 @@ +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 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, + DaxFormatterFailureReason reason, + HttpStatusCode? statusCode, + string? requestId, + string? serviceRequestId, + string? operationId, + IEnumerable? textIndexes, + Exception? innerException) + : base(message, innerException) + { + Reason = reason; + StatusCode = statusCode; + RequestId = requestId; + ServiceRequestId = serviceRequestId; + OperationId = operationId; + if (textIndexes is not null) + { + TextIndexes = [.. textIndexes]; + } + } + + /// + /// 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; } + + /// + /// 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/DaxFormatterFailureReason.cs b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs new file mode 100644 index 0000000..c852add --- /dev/null +++ b/dotnet/src/Dax.Formatter/DaxFormatterFailureReason.cs @@ -0,0 +1,35 @@ +namespace Dax.Formatter; + +/// +/// 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 +{ + /// + /// 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..b01a0ee --- /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. + /// + public DaxServerType? ServerType { get; set; } + + /// + /// Gets or sets the mode of the Analysis Services server. + /// + public DaxServerMode? ServerMode { get; set; } + + /// + /// Gets or sets the edition of the Analysis Services server. + /// + public DaxServerEdition? ServerEdition { get; set; } + + /// + /// Gets or sets where the server runs. + /// + public DaxServerLocation? 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/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/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/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/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/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/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/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/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..f18a2a4 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/FormatRequest.cs @@ -0,0 +1,56 @@ +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, IReadOnlyList textIndexes, Guid operationId) + { + Body = body; + TextIndexes = textIndexes; + OperationId = operationId; + RequestId = Guid.NewGuid(); + } + + public byte[] Body { get; } + + public int TextCount => TextIndexes.Count; + + /// 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; } + + /// 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 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( + message, + reason, + statusCode, + RequestId.ToString(), + serviceRequestId, + OperationId.ToString(), + TextIndexes, + 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..c32aa7e --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/FormatterTransport.cs @@ -0,0 +1,93 @@ +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 const string JsonMediaType = "application/json"; + + private static readonly MediaTypeWithQualityHeaderValue s_json = new(JsonMediaType); + + 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 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) + { + 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(JsonMediaType) { 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..44d5a1c --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/ResponseReader.cs @@ -0,0 +1,97 @@ +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 = Parse(content); + } + 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 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 + 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/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..ef06d7f --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/RetryingSender.cs @@ -0,0 +1,63 @@ +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, result.Detail, attempt); + } + + await _delay.WaitAsync(delay, cancellationToken).ConfigureAwait(false); + attempt++; + } + } + + private static DaxFormatterException CreateException( + FormatRequest request, + AttemptResult failure, + string detail, + int attempts) + { + 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..d16de48 --- /dev/null +++ b/dotnet/src/Dax.Formatter/Transport/SharedHttpClient.cs @@ -0,0 +1,54 @@ +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() + { + // 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 + { + 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/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/Batching/BatchPlannerTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs new file mode 100644 index 0000000..fcdf9f9 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchPlannerTests.cs @@ -0,0 +1,110 @@ +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")] + [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)); + } + + [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() + { + 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); + } +} 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..d5ead3a --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/BatchRunTests.cs @@ -0,0 +1,219 @@ +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() + { + // 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); + + 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) + { + // 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); + + 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() + { + // Once the three requests are in progress, the one that starts with "c" fails and the others never answer. + Responder failOne = (request, cancellationToken) => + { + var answer = request.Dax[0] == "c" ? Respond.Status(HttpStatusCode.BadRequest) : Respond.Hang; + return answer(request, cancellationToken); + }; + var responder = Respond.OnceArrived(3, failOne); + 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_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() + { + 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_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() + { + 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); + } + + [Fact] + public async Task FormatBatchAsync_BlankTexts_CountsThemBeforeTheFirstRequest() + { + 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); + } + + // 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/Batching/ProgressReporterTests.cs b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs new file mode 100644 index 0000000..bdbbe98 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Batching/ProgressReporterTests.cs @@ -0,0 +1,52 @@ +using Dax.Formatter.Batching; +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 void Report_FromSeveralThreads_NeverReportsFewerTextsThanBefore() + { + var progress = new ListProgress(); + var reporter = new ProgressReporter(progress, total: 2000); + + Parallel.For(0, 2000, _ => reporter.Report(1)); + + Assert.Equal(Enumerable.Range(1, 2000), progress.Reports.Select(report => report.Completed)); + } +} 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..8d34605 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/CallerIdentityTests.cs @@ -0,0 +1,86 @@ +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]+(-[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] + 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..4fab689 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Configuration/FormatSettingsTests.cs @@ -0,0 +1,131 @@ +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); + } + + [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() + { + 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 356ae63..cdd4381 100644 --- a/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj +++ b/dotnet/tests/Dax.Formatter.Tests/Dax.Formatter.Tests.csproj @@ -1,12 +1,13 @@  - net472;net8.0;net10.0 + net472;net10.0 false $(NoWarn);CA1707;CA1515 + @@ -23,4 +24,15 @@ + + + + + + + + + + + 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/DaxFormatterClientTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs index a82fe5f..5e4cef7 100644 --- a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterClientTests.cs @@ -1,223 +1,290 @@ -namespace Dax.Formatter.Tests +using System.Collections; +using System.Net.Http; +using Dax.Formatter.Tests.Fakes; +using Xunit; + +namespace Dax.Formatter.Tests; + +public class DaxFormatterClientTests { - using Dax.Formatter.Models; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Xunit; + private static readonly DaxFormatOptions s_expression = new() { Kind = DaxKind.Expression }; + private static readonly DaxFormatOptions s_invalidOptions = new() { LineStyle = (DaxLineStyle)7 }; - public class DaxFormatterClientFixture + [Fact] + public void Constructor_NullArgument_Throws() { - public DaxFormatterClient Client { get; private set; } + Assert.Throws("httpClient", () => new DaxFormatterClient((HttpClient)null!)); + Assert.Throws("options", () => new DaxFormatterClient((DaxFormatterClientOptions)null!)); + } - public DaxFormatterClientFixture() => Client = new DaxFormatterClient(application: "Dax.Formatter.Tests", version: "develop"); + [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); } - public class DaxFormatterClientTests : IClassFixture + [Fact] + public void Constructor_OptionOutOfRange_Throws() { - private readonly DaxFormatterClientFixture _fixture; + var options = new DaxFormatterClientOptions { MaxConcurrentRequests = 0 }; - public DaxFormatterClientTests(DaxFormatterClientFixture formatter) - { - _fixture = formatter; - } + Assert.Throws("options", () => new DaxFormatterClient(options)); + } - [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; + [Fact] + public void FormatAsync_NullText_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); - var response = await _fixture.Client.FormatAsync(request); - Assert.NotNull(response); + Assert.Throws("text", () => { _ = harness.Client.FormatAsync(null!); }); + } - var actualExpression = response.Formatted; - Assert.Equal(expectedExpression, actualExpression); - } + [Fact] + public void FormatAsync_OptionOutsideItsEnumeration_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); - [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; + Assert.Throws("options", () => { _ = harness.Client.FormatAsync("1", s_invalidOptions); }); + } - var response = await _fixture.Client.FormatAsync(request); - Assert.NotNull(response); + [Fact] + public void FormatBatchAsync_NullTexts_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); - var actualExpression = response.Formatted; - Assert.Equal(expectedExpression, actualExpression); - } + Assert.Throws( + "texts", () => { _ = harness.Client.FormatBatchAsync((IEnumerable)null!); }); + } - [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); + [Fact] + public void FormatBatchAsync_NullText_ThrowsWithItsIndex() + { + using var harness = new FormatterHarness(Respond.Echo); - AssertSingleSucceded(response, expectedExpression); - } + var exception = Assert.Throws( + "texts", () => { _ = harness.Client.FormatBatchAsync(["a", "b", null!, null!]); }); - [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); + Assert.Contains("index 2", exception.Message, StringComparison.Ordinal); + Assert.Empty(harness.Handler.Requests); + } - AssertSingleFails(response, expectedErrorLine, expectedErrorColumn); - } + [Fact] + public void FormatBatchAsync_NullItemsOrSelector_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1, 2]; - [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); + Assert.Throws( + "items", () => { _ = harness.Client.FormatBatchAsync((IEnumerable)null!, item => "1"); }); + Assert.Throws( + "textSelector", () => { _ = harness.Client.FormatBatchAsync(items, (Func)null!); }); + } - AssertSingleSucceded(response, expectedExpression); - } + [Fact] + public void FormatBatchAsync_SelectorReturnsNull_ThrowsWithTheIndexOfTheItem() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1, 2, 3]; - [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); + var exception = Assert.Throws( + "textSelector", () => { _ = harness.Client.FormatBatchAsync(items, item => item == 2 ? null! : "1"); }); - AssertSingleFails(response, expectedErrorLine, expectedErrorColumn); - } + Assert.Contains("index 1", exception.Message, StringComparison.Ordinal); + } - [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); + [Fact] + public void FormatBatchAsync_ItemsWithOptionOutsideItsEnumeration_ThrowsBeforeReturningATask() + { + using var harness = new FormatterHarness(Respond.Echo); + int[] items = [1]; - AssertMultipleSucceded(response, expectedExpression, repeat); - } + Assert.Throws( + "options", () => { _ = harness.Client.FormatBatchAsync(items, item => "1", s_invalidOptions); }); + } - [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); + [Fact] + public async Task FormatAsync_Query_ReturnsItFormattedWithoutTheFinalLineBreak() + { + using var harness = new FormatterHarness(Respond.Echo); - AssertMultipleFails(response, repeat, expectedErrorLine, expectedErrorColumn); - } + var result = await harness.Client.FormatAsync("EVALUATE\nSales").ConfigureAwait(true); - [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); + Assert.True(result.Succeeded); + Assert.Equal(("EVALUATE\nSales", "EVALUATE\r\nSales"), (result.OriginalText, result.FormattedText)); + } - AssertParallelSingleSucceded(responses, expectedExpression, repeat); - } + [Fact] + public async Task FormatAsync_Expression_ReturnsItWithoutTheHeader() + { + using var harness = new FormatterHarness(Respond.Echo); - [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); + var result = await harness.Client.FormatAsync("SUM ( Sales[Amount] )", s_expression).ConfigureAwait(true); - AssertParallelSingleSucceded(responses, expectedExpression, repeat); - } + Assert.Equal("[x] :=\nSUM ( Sales[Amount] )", Assert.Single(harness.Handler.Requests[0].Dax)); + Assert.Equal("SUM ( Sales[Amount] )", result.FormattedText); + } - 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); - } + [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); - 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); - } + var result = await harness.Client.FormatAsync(text, s_expression).ConfigureAwait(true); - 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); + Assert.StartsWith("FUNCTION x =\n", harness.Handler.Requests[0].Dax[0], StringComparison.Ordinal); + Assert.Equal(expected, result.FormattedText); + } - var errors = responses.SelectMany((r) => r.Errors!); - Assert.Empty(errors); + [Fact] + public async Task FormatAsync_SyntaxError_ReturnsItAsAResultWithItsPositionInTheText() + { + using var harness = new FormatterHarness(Respond.Echo); - var formattedExpressions = responses.Select((r) => r.Formatted).Distinct(); - Assert.Single(formattedExpressions); + var result = await harness.Client.FormatAsync("1 +\n\t2 +* 3", s_expression).ConfigureAwait(true); - var actualExpression = formattedExpressions.Single(); - Assert.Equal(expectedExpression, actualExpression); - } + Assert.False(result.Succeeded); + Assert.Null(result.FormattedText); + Assert.Equal(new DaxSyntaxError(1, 3, EchoService.ErrorMessage), Assert.Single(result.Errors)); + } - private static void AssertMultipleFails(IReadOnlyList responses, int repeat, int expectedErrorLine, int expectedErrorColumn) + [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[] { - Assert.NotNull(responses); - Assert.Equal(repeat, responses.Count); - Assert.DoesNotContain(responses, (r) => r.Errors is null); + new KeyValuePair("Sales", "SUM ( Sales[Amount] )"), + new KeyValuePair("Broken", "1 +* 2"), + new KeyValuePair("Cost", "SUM ( Sales[Cost] )"), + }; - var errors = responses.SelectMany((r) => r.Errors!).ToList(); - Assert.Equal(repeat, errors.Count); + var results = await harness.Client + .FormatBatchAsync(measures, measure => measure.Value, s_expression) + .ConfigureAwait(true); - var errorLines = errors.Select((e) => e.Line).Distinct(); - Assert.Single(errorLines); + Assert.Equal(measures, results.Select(result => result.Item)); + Assert.Equal(["SUM ( Sales[Amount] )", null, "SUM ( Sales[Cost] )"], results.Select(result => result.FormattedText)); + } - var actualErrorLine = errorLines.Single(); - Assert.Equal(expectedErrorLine, actualErrorLine); + [Fact] + public async Task FormatBatchAsync_TextsThatCanBeReadOnce_ReadsThemOnce() + { + using var harness = new FormatterHarness(Respond.Echo); + var texts = new CountingEnumerable(["EVALUATE A", "EVALUATE B"]); - var errorColumns = errors.Select((e) => e.Column).Distinct(); - Assert.Single(errorColumns); + var results = await harness.Client.FormatBatchAsync(texts).ConfigureAwait(true); - var actualErrorColumn = errorColumns.Single(); - Assert.Equal(expectedErrorColumn, actualErrorColumn); + 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; - var formattedExpressions = responses.Select((r) => r.Formatted).Distinct(); - Assert.Single(formattedExpressions); + 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)); + } + } - var actualExpression = formattedExpressions.Single(); - Assert.Equal(string.Empty, actualExpression); + private sealed class CountingEnumerable : IEnumerable + { + private readonly string[] _texts; + + public CountingEnumerable(string[] texts) + { + _texts = texts; } - private static void AssertParallelSingleSucceded(DaxFormatterResponse?[] responses, string expectedExpression, int repeat) + public int Enumerations { get; private set; } + + public IEnumerator GetEnumerator() { - Assert.NotNull(responses); - Assert.Equal(repeat, responses.Length); + Enumerations++; + return ((IEnumerable)_texts).GetEnumerator(); + } - foreach (var response in responses) - AssertSingleSucceded(response, expectedExpression); + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); } } } diff --git a/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs new file mode 100644 index 0000000..aa902ff --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/DaxFormatterExceptionTests.cs @@ -0,0 +1,69 @@ +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", + "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", "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] + 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)); + Assert.Equal((null, 0), (exception.OperationId, exception.TextIndexes.Count)); + } + + [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!)); + } +} 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/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/Fakes/EchoService.cs b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs new file mode 100644 index 0000000..6f47cc6 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/EchoService.cs @@ -0,0 +1,114 @@ +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(); + } + + /// Gets the answer for one text. + public static JsonObject AnswerOne(string text) + { + var marker = text.IndexOf(ErrorMarker, StringComparison.Ordinal); + if (marker < 0) + { + 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"] = formatted, + ["errors"] = new JsonArray(), + }; + } + + /// 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 error = new JsonObject + { + ["line"] = line, + ["column"] = column, + ["message"] = ErrorMessage, + }; + + return new JsonObject + { + ["formatted"] = string.Empty, + ["errors"] = new JsonArray(error), + }; + } + + // 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..691f951 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/RecordedRequest.cs @@ -0,0 +1,56 @@ +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(); + ExpectContinue = request.Headers.ExpectContinue; + + 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; } + + /// + /// 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()!)]; + + 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..c8d4198 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fakes/Respond.cs @@ -0,0 +1,113 @@ +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()); + } + + /// + /// 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) => + { + if (request.Number == count - 1) + { + arrived.TrySetResult(true); + } + + await arrived.Task.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/FixtureFile.cs b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs new file mode 100644 index 0000000..a5b4e08 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureFile.cs @@ -0,0 +1,49 @@ +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.ArrayEnumerator Cases(string fileName) + { + using var stream = OpenResource("Fixtures/" + fileName); + using var document = JsonDocument.Parse(stream); + return document.RootElement.Clone().GetProperty("cases").EnumerateArray(); + } + + /// 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); + } + + private 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); + } +} 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..ed64808 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Fixtures/FixtureOptions.cs @@ -0,0 +1,67 @@ +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 = 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, + }; + } + + return result; + } + + public static DaxKind ReadKind(JsonElement testCase) + { + return ReadEnum(testCase, "kind"); + } + + 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 null; + } + + 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/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/Fixtures/request-bodies.json b/dotnet/tests/Dax.Formatter.Tests/Fixtures/request-bodies.json new file mode 100644 index 0000000..2f113f1 --- /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": "analysisServices", + "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/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..66f3ad9 --- /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 = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.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.Cases(Fixture) + .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))); + } +} 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/PublicApi.approved.txt b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt new file mode 100644 index 0000000..12a52bb --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/PublicApi.approved.txt @@ -0,0 +1,117 @@ +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, 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 + 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.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.String operationId, System.Collections.Generic.IEnumerable textIndexes, 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 + 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 ServerName { get; set; } + System.String ServerVersion { get; set; } + constructor() +enum Dax.Formatter.DaxSeparatorStyle + CommaAndPoint = 0 + SemicolonAndComma = 1 +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 +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/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..78f7383 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Readme/ReadmeSamples.cs @@ -0,0 +1,141 @@ +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_ModelInfoSample_SendsTheDescriptionOfTheModel() + { + var client = new DaxFormatterClient(); + + #region ModelInfo + var options = new DaxFormatOptions + { + ModelInfo = new DaxModelInfo + { + ServerName = "MyServer", + DatabaseName = "Contoso", + ServerType = DaxServerType.AnalysisServices, + ServerMode = DaxServerMode.Tabular, + ServerEdition = DaxServerEdition.Enterprise64, + ServerLocation = DaxServerLocation.OnPremise, + ServerVersion = "16.0.143.21", + CompatibilityLevel = 1600, + }, + }; + #endregion + + 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( + "5e3e900585e7834b034d4f17187e521b3c7b7de0d1637f79de4b63717d4f0783", + body.GetProperty("serverName").GetString()); + } + + [Fact] + public async Task FormatAsync_OptionsSample_SendsTheOptions() + { + var client = new DaxFormatterClient(); + + #region Options + var options = new DaxFormatOptions + { + LineStyle = DaxLineStyle.ShortLine, + SpacingStyle = DaxSpacingStyle.NoSpaceAfterFunction, + SeparatorStyle = DaxSeparatorStyle.SemicolonAndComma, + }; + #endregion + + 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())); + } + + 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..b70e98c --- /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", + }; + + // 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 results = new JsonArray(); + foreach (var text in dax) + { + results.Add(AnswerOne(text)); + } + + 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/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())); + } +} 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..1d3ae6b --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Results/ResultMapperTests.cs @@ -0,0 +1,106 @@ +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] + [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); + } +} 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); - } - } -} 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..c390b93 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/FormatterTransportTests.cs @@ -0,0 +1,137 @@ +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.False(request.ExpectContinue); + } + + [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_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.")), + options => options.MaxRetries = 0); + + var exception = await Assert + .ThrowsAsync(() => harness.Client.FormatAsync("EVALUATE Sales")) + .ConfigureAwait(true); + + Assert.Equal(DaxFormatterFailureReason.Timeout, exception.Reason); + Assert.DoesNotContain("60 seconds", exception.Message, StringComparison.Ordinal); + } + + [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/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..a0f565a --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/ResponseReaderTests.cs @@ -0,0 +1,124 @@ +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_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() + { + 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..4849352 --- /dev/null +++ b/dotnet/tests/Dax.Formatter.Tests/Transport/RetryPolicyTests.cs @@ -0,0 +1,141 @@ +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); + var failure = Busy(retryAfterSeconds: seconds); + + 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); + var failure = Busy(retryAfterSeconds: 0); + + 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); + var failure = Busy(retryAfterSeconds: 61); + + 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 AttemptResult Busy(int retryAfterSeconds) + { + using var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(retryAfterSeconds)); + + return AttemptResult.Rejected(DaxFormatterFailureReason.HttpError, "detail", response); + } +} 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/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); + } +} 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); + } +} 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)); + } +} diff --git a/dotnet/version.json b/dotnet/version.json index f6fb214..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": "1.2", + "version": "2.0.0-beta.1", "assemblyVersion": { "precision": "major" },