repo
stringclasses
17 values
instance_id
stringlengths
10
43
base_commit
stringlengths
40
40
patch
stringlengths
530
154k
test_patch
stringlengths
377
76.4k
problem_statement
stringlengths
97
33k
hints_text
stringlengths
3
18.4k
created_at
stringdate
2020-06-16 21:09:47
2025-04-20 13:41:07
version
stringclasses
4 values
FAIL_TO_PASS
stringlengths
2
3.71k
PASS_TO_PASS
stringlengths
2
5.8k
ardalis/CleanArchitecture
ardalis__cleanarchitecture-546
8073cf3eb58654d67baeab966e530ae69e4a9378
diff --git a/src/Clean.Architecture.Web/ApiModels/ProjectDTO.cs b/src/Clean.Architecture.Web/ApiModels/ProjectDTO.cs index 373e25fdb..c5342328c 100644 --- a/src/Clean.Architecture.Web/ApiModels/ProjectDTO.cs +++ b/src/Clean.Architecture.Web/ApiModels/ProjectDTO.cs @@ -15,7 +15,7 @@ public ProjectDTO(int id, string name, List<ToDoItemDTO>? items = null) : base(n // Creation DTOs should not include an ID if the ID will be generated by the back end public class CreateProjectDTO { - protected CreateProjectDTO(string name) + public CreateProjectDTO(string name) { Name = name; }
diff --git a/tests/Clean.Architecture.FunctionalTests/ControllerApis/ApiProjectsControllerList.cs b/tests/Clean.Architecture.FunctionalTests/ControllerApis/ApiProjectsControllerList.cs index f8d5de85c..df65af509 100644 --- a/tests/Clean.Architecture.FunctionalTests/ControllerApis/ApiProjectsControllerList.cs +++ b/tests/Clean.Architecture.FunctionalTests/ControllerApis/ApiProjectsControllerList.cs @@ -1,6 +1,8 @@ -using Ardalis.HttpClientTestExtensions; +using System.Text; +using Ardalis.HttpClientTestExtensions; using Clean.Architecture.Web; using Clean.Architecture.Web.ApiModels; +using Newtonsoft.Json; using Xunit; namespace Clean.Architecture.FunctionalTests.ControllerApis; @@ -23,4 +25,13 @@ public async Task ReturnsOneProject() Assert.Single(result); Assert.Contains(result, i => i.Name == SeedData.TestProject1.Name); } + + [Fact] + public async Task CreateProject() + { + string projectName = "Test Project 2"; + var result = await _client.PostAndDeserializeAsync<ProjectDTO>("/api/projects", new StringContent(JsonConvert.SerializeObject(new CreateProjectDTO(projectName)), Encoding.UTF8, "application/json")); + Assert.NotNull(result); + Assert.Equal(projectName, result.Name); + } }
Attempting to create a new project through the API results in an error regarding the 'CreateProjectDTO' interface. <!-- ⚠️⚠️ Do Not Delete This! bug_report_template ⚠️⚠️ --> <!-- 🔎 Search existing issues to avoid creating duplicates. --> It's not possible to create a new project using the endpoint `[POST]/api/Projects`. When trying, it gives an error: `Could not create an instance of type Clean.Architecture.Web.ApiModels.CreateProjectDTO. Type is an interface or abstract class and cannot be instantiated. Path 'name', line 2, position 9.` ![image](https://user-images.githubusercontent.com/4308648/235479002-f7865f0d-8a6d-43e4-9931-a045ceae50ba.png) ![image](https://user-images.githubusercontent.com/4308648/235478859-5259c8f3-e2be-4ecf-998f-3003e741b650.png) ![image](https://user-images.githubusercontent.com/4308648/235477952-2d846910-391b-470f-8b8e-cb4517abd24a.png)
null
2023-05-01T16:18:24Z
0.1
['Clean.Architecture.FunctionalTests.ControllerApis.ProjectCreate.CreateProject']
['Clean.Architecture.FunctionalTests.ControllerApis.ProjectCreate.ReturnsOneProject']
ardalis/CleanArchitecture
ardalis__cleanarchitecture-530
f041a4e1eee6438a7249e4ff687969b5ce728c62
diff --git a/Directory.Packages.props b/Directory.Packages.props index 402b2d6ab..a4e72e15f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -16,6 +16,7 @@ <PackageVersion Include="FastEndpoints.ApiExplorer" Version="2.0.1" /> <PackageVersion Include="FastEndpoints.Swagger" Version="5.5.0" /> <PackageVersion Include="FastEndpoints.Swagger.Swashbuckle" Version="2.0.1" /> + <PackageVersion Include="FluentAssertions" Version="6.10.0" /> <PackageVersion Include="MediatR" Version="12.0.1" /> <PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.4" /> <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.4" /> diff --git a/src/Clean.Architecture.Core/ProjectAggregate/Specifications/ContributorByIdSpec.cs b/src/Clean.Architecture.Core/ContributorAggregate/Specifications/ContributorByIdSpec.cs similarity index 68% rename from src/Clean.Architecture.Core/ProjectAggregate/Specifications/ContributorByIdSpec.cs rename to src/Clean.Architecture.Core/ContributorAggregate/Specifications/ContributorByIdSpec.cs index e7e561691..2529afe63 100644 --- a/src/Clean.Architecture.Core/ProjectAggregate/Specifications/ContributorByIdSpec.cs +++ b/src/Clean.Architecture.Core/ContributorAggregate/Specifications/ContributorByIdSpec.cs @@ -1,7 +1,6 @@ using Ardalis.Specification; -using Clean.Architecture.Core.ContributorAggregate; -namespace Clean.Architecture.Core.ProjectAggregate.Specifications; +namespace Clean.Architecture.Core.ContributorAggregate.Specifications; public class ContributorByIdSpec : Specification<Contributor>, ISingleResultSpecification { diff --git a/src/Clean.Architecture.Core/Interfaces/IDeleteContributorService.cs b/src/Clean.Architecture.Core/Interfaces/IDeleteContributorService.cs index 7f9434d87..54fe303ab 100644 --- a/src/Clean.Architecture.Core/Interfaces/IDeleteContributorService.cs +++ b/src/Clean.Architecture.Core/Interfaces/IDeleteContributorService.cs @@ -1,8 +1,10 @@ -using Ardalis.Result; +using Ardalis.Result; namespace Clean.Architecture.Core.Interfaces; public interface IDeleteContributorService { - public Task<Result> DeleteContributor(int contributorId); + // This service and method exist to provide a place in which to fire domain events + // when deleting this aggregate root entity + public Task<Result> DeleteContributor(int contributorId); } diff --git a/src/Clean.Architecture.Web/Endpoints/ContributorEndpoints/GetById.cs b/src/Clean.Architecture.Web/Endpoints/ContributorEndpoints/GetById.cs index 8b35be410..042c99fa4 100644 --- a/src/Clean.Architecture.Web/Endpoints/ContributorEndpoints/GetById.cs +++ b/src/Clean.Architecture.Web/Endpoints/ContributorEndpoints/GetById.cs @@ -1,5 +1,5 @@ using Clean.Architecture.Core.ContributorAggregate; -using Clean.Architecture.Core.ProjectAggregate.Specifications; +using Clean.Architecture.Core.ContributorAggregate.Specifications; using Clean.Architecture.SharedKernel.Interfaces; using FastEndpoints; diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.CreateToDoItemRequest.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.CreateToDoItemRequest.cs new file mode 100644 index 000000000..e0b11f085 --- /dev/null +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.CreateToDoItemRequest.cs @@ -0,0 +1,19 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc; + +namespace Clean.Architecture.Web.Endpoints.ProjectEndpoints; + +public class CreateToDoItemRequest +{ + public const string Route = "/Projects/{ProjectId:int}/ToDoItems"; + public static string BuildRoute(int projectId) => Route.Replace("{ProjectId:int}", projectId.ToString()); + + [Required] + [FromRoute] + public int ProjectId { get; set; } + + [Required] + public string? Title { get; set; } + public string? Description { get; set; } + public int? ContributorId { get; set; } +} diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.cs new file mode 100644 index 000000000..55c2c9c50 --- /dev/null +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/CreateToDoItem.cs @@ -0,0 +1,54 @@ +using Ardalis.ApiEndpoints; +using Clean.Architecture.Core.ProjectAggregate; +using Clean.Architecture.Core.ProjectAggregate.Specifications; +using Clean.Architecture.SharedKernel.Interfaces; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.Annotations; + +namespace Clean.Architecture.Web.Endpoints.ProjectEndpoints; + +public class CreateToDoItem : EndpointBaseAsync + .WithRequest<CreateToDoItemRequest> + .WithActionResult +{ + private readonly IRepository<Project> _repository; + + public CreateToDoItem(IRepository<Project> repository) + { + _repository = repository; + } + + [HttpPost(CreateToDoItemRequest.Route)] + [SwaggerOperation( + Summary = "Creates a new ToDo Item for a Project", + Description = "Creates a new ToDo Item for a Project", + OperationId = "Project.CreateToDoItem", + Tags = new[] { "ProjectEndpoints" }) + ] + public override async Task<ActionResult> HandleAsync( + CreateToDoItemRequest request, + CancellationToken cancellationToken = new()) + { + var spec = new ProjectByIdWithItemsSpec(request.ProjectId); + var entity = await _repository.FirstOrDefaultAsync(spec, cancellationToken); + if (entity == null) + { + return NotFound(); + } + + var newItem = new ToDoItem() + { + Title = request.Title!, + Description = request.Description! + }; + + if(request.ContributorId.HasValue) + { + newItem.AddContributor(request.ContributorId.Value); + } + entity.AddItem(newItem); + await _repository.UpdateAsync(entity); + + return Created(GetProjectByIdRequest.BuildRoute(request.ProjectId), null); + } +} diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/GetById.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/GetById.cs index e681c1308..8a396d72b 100644 --- a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/GetById.cs +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/GetById.cs @@ -40,7 +40,12 @@ public override async Task<ActionResult<GetProjectByIdResponse>> HandleAsync( ( id: entity.Id, name: entity.Name, - items: entity.Items.Select(item => new ToDoItemRecord(item.Id, item.Title, item.Description, item.IsDone)) + items: entity.Items.Select( + item => new ToDoItemRecord(item.Id, + item.Title, + item.Description, + item.IsDone, + item.ContributorId)) .ToList() ); diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ListIncomplete.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ListIncomplete.cs index f061b203e..fdcefe195 100644 --- a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ListIncomplete.cs +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ListIncomplete.cs @@ -43,7 +43,8 @@ public override async Task<ActionResult<ListIncompleteResponse>> HandleAsync( item => new ToDoItemRecord(item.Id, item.Title, item.Description, - item.IsDone))); + item.IsDone, + item.ContributorId))); } else if (result.Status == Ardalis.Result.ResultStatus.Invalid) { diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ToDoItemRecord.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ToDoItemRecord.cs index 694a76697..f351ebea9 100644 --- a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ToDoItemRecord.cs +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/ToDoItemRecord.cs @@ -1,3 +1,3 @@ namespace Clean.Architecture.Web.Endpoints.ProjectEndpoints; -public record ToDoItemRecord(int Id, string Title, string Description, bool IsDone); +public record ToDoItemRecord(int Id, string Title, string Description, bool IsDone, int? ContributorId); diff --git a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/Update.cs b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/Update.cs index 9deab11de..f063dfd47 100644 --- a/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/Update.cs +++ b/src/Clean.Architecture.Web/Endpoints/ProjectEndpoints/Update.cs @@ -20,7 +20,7 @@ public Update(IRepository<Project> repository) [HttpPut(UpdateProjectRequest.Route)] [SwaggerOperation( Summary = "Updates a Project", - Description = "Updates a Project with a longer description", + Description = "Updates a Project. Only supports changing the name.", OperationId = "Projects.Update", Tags = new[] { "ProjectEndpoints" }) ]
diff --git a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectCreate.cs b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectCreate.cs new file mode 100644 index 000000000..e122bbfac --- /dev/null +++ b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectCreate.cs @@ -0,0 +1,68 @@ +using Ardalis.HttpClientTestExtensions; +using Clean.Architecture.Web.Endpoints.ProjectEndpoints; +using Xunit; +using FluentAssertions; +using Clean.Architecture.Web; + +namespace Clean.Architecture.FunctionalTests.ApiEndpoints; + +[Collection("Sequential")] +public class ProjectCreate : IClassFixture<CustomWebApplicationFactory<Program>> +{ + private readonly HttpClient _client; + + public ProjectCreate(CustomWebApplicationFactory<Program> factory) + { + _client = factory.CreateClient(); + } + + [Fact] + public async Task ReturnsOneProject() + { + string testName = Guid.NewGuid().ToString(); + var request = new CreateProjectRequest() { Name = testName }; + var content = StringContentHelpers.FromModelAsJson(request); + + var result = await _client.PostAndDeserializeAsync<CreateProjectResponse>( + CreateProjectRequest.Route, content); + + result.Name.Should().Be(testName); + result.Id.Should().BeGreaterThan(0); + } +} + +[Collection("Sequential")] +public class ProjectAddToDoItem : IClassFixture<CustomWebApplicationFactory<Program>> +{ + private readonly HttpClient _client; + + public ProjectAddToDoItem(CustomWebApplicationFactory<Program> factory) + { + _client = factory.CreateClient(); + } + + [Fact] + public async Task AddsItemAndReturnsRouteToProject() + { + string toDoTitle = Guid.NewGuid().ToString(); + int testProjectId = SeedData.TestProject1.Id; + var request = new CreateToDoItemRequest() { + Title = toDoTitle, + ProjectId = testProjectId, + Description = toDoTitle + }; + var content = StringContentHelpers.FromModelAsJson(request); + + var result = await _client.PostAsync(CreateToDoItemRequest.BuildRoute(testProjectId), content); + + // useful for debugging error responses: + // var stringContent = await result.Content.ReadAsStringAsync(); + + string expectedRoute = GetProjectByIdRequest.BuildRoute(testProjectId); + result.Headers.Location!.ToString().Should().Be(expectedRoute); + + var updatedProject = await _client.GetAndDeserializeAsync<GetProjectByIdResponse>(expectedRoute); + + updatedProject.Items.Should().ContainSingle(item => item.Title == toDoTitle); + } +} diff --git a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectList.cs b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectList.cs index 5064edb3e..9c1ea80d1 100644 --- a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectList.cs +++ b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ProjectList.cs @@ -1,4 +1,5 @@ using Ardalis.HttpClientTestExtensions; +using Clean.Architecture.Core.ProjectAggregate; using Clean.Architecture.Web; using Clean.Architecture.Web.Endpoints.ProjectEndpoints; using Xunit; diff --git a/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj b/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj index 5f25a3c7e..655190bf3 100644 --- a/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj +++ b/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj @@ -8,6 +8,7 @@ </PropertyGroup> <ItemGroup> + <PackageReference Include="FluentAssertions" /> <PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="xunit" /> <PackageReference Include="xunit.runner.visualstudio">
Please show how you would create new ToDoItems <!-- ⚠️⚠️ Do Not Delete This! feature_request_template ⚠️⚠️ --> <!-- Please search existing issues to avoid creating duplicates. --> <!-- Describe the feature you'd like. --> In this template, you aggregate ToDoItems within the ProjectAggregate. However, you also stop short of showing how you would, via API, author new ToDoItem instances. I think it would be beneficial to show how you would create these new child items of a project. I think it would be wonderful to see: - How you would define this in an ApiEndpoint. - How you would incorporate this within the ProjectAggregate. - How you would codify a Many-to-Many relationship as opposed to the One-To-Many relationship between Project and ToDoItem. - Is this implied by the Project <-> Contributor relationship? - What if the Contributor to a Project had a title within that Project? Senior Contributor vs Junior Contributor? If that were the case what ApiEndpoint would the management of that be within your example domain? Thanks for such a great template!
null
2023-04-09T15:39:56Z
0.1
['Clean.Architecture.FunctionalTests.ApiEndpoints.ProjectAddToDoItem.AddsItemAndReturnsRouteToProject', 'Clean.Architecture.FunctionalTests.ApiEndpoints.ProjectCreate.ReturnsOneProject']
[]
jellyfin/jellyfin
jellyfin__jellyfin-12621
987dbe98c8ab55c5c8eb563820e54453c835cdde
diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 51f29cf0887..12bc22a6ac0 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -141,7 +141,9 @@ private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, { if (group.Key) { - videos.InsertRange(0, group.OrderByDescending(x => x.Files[0].FileNameWithoutExtension.ToString(), new AlphanumericComparator())); + videos.InsertRange(0, group + .OrderByDescending(x => ResolutionRegex().Match(x.Files[0].FileNameWithoutExtension.ToString()).Value, new AlphanumericComparator()) + .ThenBy(x => x.Files[0].FileNameWithoutExtension.ToString(), new AlphanumericComparator())); } else {
diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index 183ec898485..3005a4416c0 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -356,6 +356,45 @@ public void TestMultiVersion12() Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - Theatrical Release.mkv", result[0].AlternateVersions[4].Path); } + [Fact] + public void TestMultiVersion13() + { + var files = new[] + { + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - Theatrical Release.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - Directors Cut.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 2160p.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Directors Cut.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 2160p Remux.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Theatrical Release.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 720p.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Remux.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 720p Directors Cut.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p High Bitrate.mkv", + "/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016).mkv", + }; + + var result = VideoListResolver.Resolve( + files.Select(i => VideoResolver.Resolve(i, false, _namingOptions)).OfType<VideoFileInfo>().ToList(), + _namingOptions).ToList(); + + Assert.Single(result); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016).mkv", result[0].Files[0].Path); + Assert.Equal(11, result[0].AlternateVersions.Count); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 2160p.mkv", result[0].AlternateVersions[0].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 2160p Remux.mkv", result[0].AlternateVersions[1].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p.mkv", result[0].AlternateVersions[2].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Directors Cut.mkv", result[0].AlternateVersions[3].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p High Bitrate.mkv", result[0].AlternateVersions[4].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Remux.mkv", result[0].AlternateVersions[5].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 1080p Theatrical Release.mkv", result[0].AlternateVersions[6].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 720p.mkv", result[0].AlternateVersions[7].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - 720p Directors Cut.mkv", result[0].AlternateVersions[8].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - Directors Cut.mkv", result[0].AlternateVersions[9].Path); + Assert.Equal("/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) - Theatrical Release.mkv", result[0].AlternateVersions[10].Path); + } + [Fact] public void Resolve_GivenFolderNameWithBracketsAndHyphens_GroupsBasedOnFolderName() {
Sort versions in ascending order when resolution is the same Change movie version to sort in ascending order when resolution is the same **Issues** Fixes #12618 Versions are sorted in reverse alphabetical order when filename includes resolution When multiple files share the same resolution in their filenames, they are sorted in reverse alphabetical order. https://github.com/jellyfin/jellyfin/blob/54f663b0f3c4a9cc5a4f44d1afcb6e1de03c0503/Emby.Naming/Video/VideoListResolver.cs#L144 ![Screenshot from 2024-09-09 10-50-18](https://github.com/user-attachments/assets/a81fb785-3521-4b8d-8964-41e516c22220) <br><br> Since the resolutions are sorted based on the MediaInfo, it should be sufficient to change `OrderByDescending` to just `OrderBy` . ```c# videos.InsertRange(0, group.OrderBy(x => x.Files[0].FileNameWithoutExtension.ToString(), new AlphanumericComparator())); ``` <br> Making this change resolves the issue, and resolutions are sorted alphabetical, with higher resolutions listed first, regardless of whether the resolution is included in the filename. ![Screenshot from 2024-09-09 10-46-21](https://github.com/user-attachments/assets/db23c97a-0895-404c-b172-07a0d475341f) Server: 10.9.11
Please provide the media info of all 3 files Those were all the same file, just renamed. I'll also upload with different resolutions in a bit. ``` General Unique ID : 34727860135091814094139690058492232674 (0x1A2057B2EBC11E00F924498B258D43E2) Complete name : /media/max/testmedia/Multiple Versions/Big Buck Bunny (2008)/Big Buck Bunny (2008) - 2160p Director's cut.mkv Format : Matroska Format version : Version 4 File size : 604 MiB Duration : 10 min 34 s Overall bit rate : 7 980 kb/s Frame rate : 30.000 FPS Movie name : Big Buck Bunny, Sunflower version Encoded date : 2024-06-23 14:51:05 UTC Writing application : mkvmerge v85.0 ('Shame For You') 64-bit Writing library : libebml v1.4.5 + libmatroska v1.7.1 Comment : Creative Commons Attribution 3.0 - http://bbb3d.renderfarming.net Video ID : 1 Format : AVC Format/Info : Advanced Video Codec Format profile : High@L5.1 Format settings : CABAC / 4 Ref Frames Format settings, CABAC : Yes Format settings, Reference frames : 4 frames Codec ID : V_MPEG4/ISO/AVC Duration : 10 min 34 s Bit rate : 7 500 kb/s Width : 3 840 pixels Height : 2 160 pixels Display aspect ratio : 16:9 Frame rate mode : Constant Frame rate : 30.000 FPS Color space : YUV Chroma subsampling : 4:2:0 Bit depth : 8 bits Scan type : Progressive Bits/(Pixel*Frame) : 0.030 Stream size : 567 MiB (94%) Writing library : x264 core 120 ``` Example with different resolution, current behavior: ![Screenshot from 2024-09-09 14-58-44](https://github.com/user-attachments/assets/5e48ddc0-7e80-4028-8c6e-681798ab531d) <br><br> With proposed changed in code: ![Screenshot from 2024-09-09 14-58-39](https://github.com/user-attachments/assets/105a85d7-c34e-4f82-b0c6-92847ff75404) <br> Only two files tested here one 2160p media info above and 1080p info below. All versions are just copies. ``` General Complete name : /media/max/testmedia/Multiple Versions/Big Buck Bunny (2008)/Big Buck Bunny (2008) - Alpha teneightyp.mp4 Format : MPEG-4 Format profile : Base Media Codec ID : isom (isom/avc1) File size : 263 MiB Duration : 10 min 34 s Overall bit rate : 3 481 kb/s Frame rate : 30.000 FPS Movie name : Big Buck Bunny, Sunflower version Performer : Blender Foundation 2008, Janus Bager Kristensen 2013 Composer : Sacha Goedegebure Genre : Animation Encoded date : 2013-12-16 17:44:39 UTC Tagged date : 2013-12-16 17:44:39 UTC Comment : Creative Commons Attribution 3.0 - http://bbb3d.renderfarming.net com : Jan Morgenstern Video ID : 1 Format : AVC Format/Info : Advanced Video Codec Format profile : High@L4.1 Format settings : CABAC / 4 Ref Frames Format settings, CABAC : Yes Format settings, Reference frames : 4 frames Codec ID : avc1 Codec ID/Info : Advanced Video Coding Duration : 10 min 34 s Bit rate : 3 000 kb/s Maximum bit rate : 16.7 Mb/s Width : 1 920 pixels Height : 1 080 pixels Display aspect ratio : 16:9 Frame rate mode : Constant Frame rate : 30.000 FPS Color space : YUV Chroma subsampling : 4:2:0 Bit depth : 8 bits Scan type : Progressive Bits/(Pixel*Frame) : 0.048 Stream size : 227 MiB (86%) Writing library : x264 core 115 ```
2024-09-09T20:27:19Z
0.1
['Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion13']
['Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion4', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion10', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion11', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion5', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.Resolve_GivenFolderNameWithBracketsAndHyphens_GroupsBasedOnFolderName', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion9', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestLetterFolders', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion6', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestEmptyList', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersionLimit2', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiEdition2', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion12', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion8', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiEdition1', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion7', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersionLimit', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiEdition3', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.TestMultiVersion3', 'Jellyfin.Naming.Tests.Video.MultiVersionTests.Resolve_GivenUnclosedBrackets_DoesNotGroup']
jellyfin/jellyfin
jellyfin__jellyfin-12558
2fe13f54eaf87eefefd27f4ccb2ace1371f5e886
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 8bd4fb4f382..f16558d1e7c 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1180,28 +1180,29 @@ private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem ite return info; } - private string GetMediaSourceName(BaseItem item) + internal string GetMediaSourceName(BaseItem item) { var terms = new List<string>(); var path = item.Path; if (item.IsFileProtocol && !string.IsNullOrEmpty(path)) { + var displayName = System.IO.Path.GetFileNameWithoutExtension(path); if (HasLocalAlternateVersions) { - var displayName = System.IO.Path.GetFileNameWithoutExtension(path) - .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase) - .TrimStart(new char[] { ' ', '-' }); - - if (!string.IsNullOrEmpty(displayName)) + var containingFolderName = System.IO.Path.GetFileName(ContainingFolderPath); + if (displayName.Length > containingFolderName.Length && displayName.StartsWith(containingFolderName, StringComparison.OrdinalIgnoreCase)) { - terms.Add(displayName); + var name = displayName.AsSpan(containingFolderName.Length).TrimStart([' ', '-']); + if (!name.IsWhiteSpace()) + { + terms.Add(name.ToString()); + } } } if (terms.Count == 0) { - var displayName = System.IO.Path.GetFileNameWithoutExtension(path); terms.Add(displayName); } }
diff --git a/tests/Jellyfin.Controller.Tests/Entities/BaseItemTests.cs b/tests/Jellyfin.Controller.Tests/Entities/BaseItemTests.cs index f3ada59dbcd..6171f12e472 100644 --- a/tests/Jellyfin.Controller.Tests/Entities/BaseItemTests.cs +++ b/tests/Jellyfin.Controller.Tests/Entities/BaseItemTests.cs @@ -1,4 +1,7 @@ using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.MediaInfo; +using Moq; using Xunit; namespace Jellyfin.Controller.Tests.Entities; @@ -14,4 +17,30 @@ public class BaseItemTests [InlineData("1test 2", "0000000001test 0000000002")] public void BaseItem_ModifySortChunks_Valid(string input, string expected) => Assert.Equal(expected, BaseItem.ModifySortChunks(input)); + + [Theory] + [InlineData("/Movies/Ted/Ted.mp4", "/Movies/Ted/Ted - Unrated Edition.mp4", "Ted", "Unrated Edition")] + [InlineData("/Movies/Deadpool 2 (2018)/Deadpool 2 (2018).mkv", "/Movies/Deadpool 2 (2018)/Deadpool 2 (2018) - Super Duper Cut.mkv", "Deadpool 2 (2018)", "Super Duper Cut")] + public void GetMediaSourceName_Valid(string primaryPath, string altPath, string name, string altName) + { + var mediaSourceManager = new Mock<IMediaSourceManager>(); + mediaSourceManager.Setup(x => x.GetPathProtocol(It.IsAny<string>())) + .Returns((string x) => MediaProtocol.File); + BaseItem.MediaSourceManager = mediaSourceManager.Object; + + var video = new Video() + { + Path = primaryPath + }; + + var videoAlt = new Video() + { + Path = altPath, + }; + + video.LocalAlternateVersions = [videoAlt.Path]; + + Assert.Equal(name, video.GetMediaSourceName(video)); + Assert.Equal(altName, video.GetMediaSourceName(videoAlt)); + } }
Movie Version Name Changes Based on Title of Movie ### This issue respects the following points: - [X] This is a **bug**, not a question or a configuration issue; Please visit our forum or chat rooms first to troubleshoot with volunteers, before creating a report. The links can be found [here](https://jellyfin.org/contact/). - [X] This issue is **not** already reported on [GitHub](https://github.com/jellyfin/jellyfin/issues?q=is%3Aopen+is%3Aissue) _(I've searched it)_. - [X] I'm using an up to date version of Jellyfin Server stable, unstable or master; We generally do not support previous older versions. If possible, please update to the latest version before opening an issue. - [X] I agree to follow Jellyfin's [Code of Conduct](https://jellyfin.org/docs/general/community-standards.html#code-of-conduct). - [X] This report addresses only a single issue; If you encounter multiple issues, kindly create separate reports for each one. ### Description of the bug When a movie has multiple versions available, version names will be modified in a way where if the title of the movie appears in the version name, the title will be removed. This causes issues with certain version names. ### Reproduction steps 1. Prepare two video files, name one "[movie_name] - [version 1]" and the other "[movie_name] - [version 2]" 2. Create a folder in your movies folder named "[movie_name]" 3. Move the two video files to the newly created folder ### What is the current _bug_ behavior? If [movie_name] appears anywhere within the text of [version 1] and/or [version 2], then [movie_name] will be removed from the version name. Hypothetical Example: file names "Rap - 1. Holy crap dude!"; "Rap - 2. Wrapping paper" results in version names display on Jellyfin "1. Holy c dude!"; "2. Wping paper" Real Example: file names "Ted - 1. Theatrical Version"; "Ted - 2. Unrated Version" results in version names display on Jellyfin "1. Theatrical Version"; "2. Unra Version" ### What is the expected _correct_ behavior? If [movie_name] appears anywhere within the text of [version 1] and/or [version 2], the version name does not change. Hypothetical Example: file names "Rap - 1. Holy crap dude!"; "Rap - 2. Wrapping paper" results in version names display on Jellyfin "1. Holy crap dude!"; "2. Wrapping paper" Real Example: file names "Ted - 1. Theatrical Version"; "Ted - 2. Unrated Version" results in version names display on Jellyfin "1. Theatrical Version"; "2. Unrated Version" ### Jellyfin Server version Older* ### Specify commit id _No response_ ### Specify unstable release number _No response_ ### Specify version number 10.9.7 ### Specify the build version Release ### Environment ```markdown - OS: Windows 10 - Linux Kernel: none - Virtualization: Docker? (using package for Synology available on synocommunity.com) - Clients: Browser, Windows, Mac OS, Android, iPhone - Browser: Chrome 127.0.6533.88 - FFmpeg Version: 6.0.1 - Playback Method: N/A - Hardware Acceleration: none - GPU Model: N/A - Plugins: none - Reverse Proxy: none - Base URL: none - Networking: Host - Storage: local & remote NAS ``` ### Jellyfin logs ```shell N/A ``` ### FFmpeg logs _No response_ ### Client / Browser logs _No response_ ### Relevant screenshots or videos ![ted_unra1](https://github.com/user-attachments/assets/4e6f4c0e-4b46-40db-8935-43cebd18c86a) ![ted_unra2](https://github.com/user-attachments/assets/9edd696c-ec00-4966-b8c9-1c7d97f2da84) ### Additional information _No response_
null
2024-08-31T12:02:58Z
0.1
['Jellyfin.Controller.Tests.Entities.BaseItemTests.GetMediaSourceName_Valid']
['Jellyfin.Controller.Tests.Entities.BaseItemTests.BaseItem_ModifySortChunks_Valid']
jellyfin/jellyfin
jellyfin__jellyfin-12550
2fe13f54eaf87eefefd27f4ccb2ace1371f5e886
diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 37e24141429..76bc4f49d83 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -180,10 +180,7 @@ public override List<string> GetUserDataKeys() } public string FindSeriesPresentationUniqueKey() - { - var series = Series; - return series is null ? null : series.PresentationUniqueKey; - } + => Series?.PresentationUniqueKey; public string FindSeasonName() { diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 4af000557e6..120cb2b2dd5 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -430,8 +430,6 @@ public static QueryResult<BaseItem> PostFilterAndSort( InternalItemsQuery query, ILibraryManager libraryManager) { - var user = query.User; - // This must be the last filter if (!query.AdjacentTo.IsNullOrEmpty()) { diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 788ecbae2d0..cd0efa774f1 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -1207,7 +1207,8 @@ public void GenerateConcatConfig(MediaSourceInfo source, string concatFilePath) } // Generate concat configuration entries for each file and write to file - using StreamWriter sw = new StreamWriter(concatFilePath); + Directory.CreateDirectory(Path.GetDirectoryName(concatFilePath)); + using StreamWriter sw = new FormattingStreamWriter(concatFilePath, CultureInfo.InvariantCulture); foreach (var path in files) { var mediaInfoResult = GetMediaInfo( diff --git a/src/Jellyfin.Extensions/FormattingStreamWriter.cs b/src/Jellyfin.Extensions/FormattingStreamWriter.cs new file mode 100644 index 00000000000..40e3c5a68f6 --- /dev/null +++ b/src/Jellyfin.Extensions/FormattingStreamWriter.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; + +namespace Jellyfin.Extensions; + +/// <summary> +/// A custom StreamWriter which supports setting a IFormatProvider. +/// </summary> +public class FormattingStreamWriter : StreamWriter +{ + private readonly IFormatProvider _formatProvider; + + /// <summary> + /// Initializes a new instance of the <see cref="FormattingStreamWriter"/> class. + /// </summary> + /// <param name="stream">The stream to write to.</param> + /// <param name="formatProvider">The format provider to use.</param> + public FormattingStreamWriter(Stream stream, IFormatProvider formatProvider) + : base(stream) + { + _formatProvider = formatProvider; + } + + /// <summary> + /// Initializes a new instance of the <see cref="FormattingStreamWriter"/> class. + /// </summary> + /// <param name="path">The complete file path to write to.</param> + /// <param name="formatProvider">The format provider to use.</param> + public FormattingStreamWriter(string path, IFormatProvider formatProvider) + : base(path) + { + _formatProvider = formatProvider; + } + + /// <inheritdoc /> + public override IFormatProvider FormatProvider + => _formatProvider; +}
diff --git a/tests/Jellyfin.Extensions.Tests/FormattingStreamWriterTests.cs b/tests/Jellyfin.Extensions.Tests/FormattingStreamWriterTests.cs new file mode 100644 index 00000000000..06e3c272130 --- /dev/null +++ b/tests/Jellyfin.Extensions.Tests/FormattingStreamWriterTests.cs @@ -0,0 +1,23 @@ +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading; +using Xunit; + +namespace Jellyfin.Extensions.Tests; + +public static class FormattingStreamWriterTests +{ + [Fact] + public static void Shuffle_Valid_Correct() + { + Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false); + using (var ms = new MemoryStream()) + using (var txt = new FormattingStreamWriter(ms, CultureInfo.InvariantCulture)) + { + txt.Write("{0}", 3.14159); + txt.Close(); + Assert.Equal("3.14159", Encoding.UTF8.GetString(ms.ToArray())); + } + } +}
Error processing request. FfmpegException ### This issue respects the following points: - [X] This is a **bug**, not a question or a configuration issue; Please visit our forum or chat rooms first to troubleshoot with volunteers, before creating a report. The links can be found [here](https://jellyfin.org/contact/). - [X] This issue is **not** already reported on [GitHub](https://github.com/jellyfin/jellyfin/issues?q=is%3Aopen+is%3Aissue) _(I've searched it)_. - [X] I'm using an up to date version of Jellyfin Server stable, unstable or master; We generally do not support previous older versions. If possible, please update to the latest version before opening an issue. - [X] I agree to follow Jellyfin's [Code of Conduct](https://jellyfin.org/docs/general/community-standards.html#code-of-conduct). - [X] This report addresses only a single issue; If you encounter multiple issues, kindly create separate reports for each one. ### Description of the bug Nach dem Update auf 10.9.9 bekomme ich beim Abspielen von MKV Dateien folgende Fehler. Egal ob ich mit oder ohne Hartwardecoder Arbeite. Neu Installation Deinstallation mit Neuinstallation. Neuanlage der Bibliothek hat nicht geholfen. Ich habe hier schon über alle gesucht auch ähnliche Fehler gefunden nur nicht für Windows System. Dem entsprechend bin ich überfragt was ich tun kann. Entschuldigt mein Schlechtes Englisch. Danke schon mal für die Hilfe. After updating to 10.9.9 I get the following errors when playing MKV files. Regardless of whether I work with or without a hardware decoder. Reinstallation Uninstallation with reinstallation. Reinstalling the library did not help. I have already searched for similar errors here, but not for Windows systems. So I am not sure what I can do. Sorry for my bad English. Thanks for the help. ### Reproduction steps Play a MKV Titele ### What is the current _bug_ behavior? Title is not playing ### What is the expected _correct_ behavior? Play the Title ### Jellyfin Server version 10.9.9+ ### Specify commit id _No response_ ### Specify unstable release number _No response_ ### Specify version number _No response_ ### Specify the build version 10.9.9 ### Environment ```markdown Intel i5-4800k Nvidia 1080Ti 32GB-Ram SSD 1tb Windows 10. Clients Firefox Android, Firestick Chrome 6.0.1-Jellyfin ``` ### Jellyfin logs ```shell [2024-08-12 11:07:44.381 +02:00] [ERR] [66] Jellyfin.Api.Middleware.ExceptionMiddleware: Error processing request. URL "GET" "/videos/6ba68b9e-5575-aea5-03fa-95d37f39e021/hls1/main/-1.mp4". MediaBrowser.Common.FfmpegException: FFmpeg exited with code 1 at MediaBrowser.MediaEncoding.Transcoding.TranscodeManager.StartFfMpeg(StreamState state, String outputPath, String commandLineArguments, Guid userId, TranscodingJobType transcodingJobType, CancellationTokenSource cancellationTokenSource, String workingDirectory) at Jellyfin.Api.Controllers.DynamicHlsController.GetDynamicSegment(StreamingRequestDto streamingRequest, Int32 segmentId) at Jellyfin.Api.Controllers.DynamicHlsController.GetHlsVideoSegment(Guid itemId, String playlistId, Int32 segmentId, String container, Int64 runtimeTicks, Int64 actualSegmentLengthTicks, Nullable`1 static, String params, String tag, String deviceProfileId, String playSessionId, String segmentContainer, Nullable`1 segmentLength, Nullable`1 minSegments, String mediaSourceId, String deviceId, String audioCodec, Nullable`1 enableAutoStreamCopy, Nullable`1 allowVideoStreamCopy, Nullable`1 allowAudioStreamCopy, Nullable`1 breakOnNonKeyFrames, Nullable`1 audioSampleRate, Nullable`1 maxAudioBitDepth, Nullable`1 audioBitRate, Nullable`1 audioChannels, Nullable`1 maxAudioChannels, String profile, String level, Nullable`1 framerate, Nullable`1 maxFramerate, Nullable`1 copyTimestamps, Nullable`1 startTimeTicks, Nullable`1 width, Nullable`1 height, Nullable`1 maxWidth, Nullable`1 maxHeight, Nullable`1 videoBitRate, Nullable`1 subtitleStreamIndex, Nullable`1 subtitleMethod, Nullable`1 maxRefFrames, Nullable`1 maxVideoBitDepth, Nullable`1 requireAvc, Nullable`1 deInterlace, Nullable`1 requireNonAnamorphic, Nullable`1 transcodingMaxAudioChannels, Nullable`1 cpuCoreLimit, String liveStreamId, Nullable`1 enableMpegtsM2TsMode, String videoCodec, String subtitleCodec, String transcodeReasons, Nullable`1 audioStreamIndex, Nullable`1 videoStreamIndex, Nullable`1 context, Dictionary`2 streamOptions) at lambda_method1218(Closure, Object) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Jellyfin.Api.Middleware.ServerStartupMessageMiddleware.Invoke(HttpContext httpContext, IServerApplicationHost serverApplicationHost, ILocalizationManager localizationManager) at Jellyfin.Api.Middleware.WebSocketHandlerMiddleware.Invoke(HttpContext httpContext, IWebSocketManager webSocketManager) at Jellyfin.Api.Middleware.IPBasedAccessValidationMiddleware.Invoke(HttpContext httpContext, INetworkManager networkManager) at Jellyfin.Api.Middleware.LanFilteringMiddleware.Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Jellyfin.Api.Middleware.QueryStringDecodingMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.ReDoc.ReDocMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Jellyfin.Api.Middleware.RobotsRedirectionMiddleware.Invoke(HttpContext httpContext) at Jellyfin.Api.Middleware.LegacyEmbyRouteRewriteMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.InvokeCore(HttpContext context) at Jellyfin.Api.Middleware.ResponseTimeMiddleware.Invoke(HttpContext context, IServerConfigurationManager serverConfigurationManager) at Jellyfin.Api.Middleware.ExceptionMiddleware.Invoke(HttpContext context) ``` ### FFmpeg logs ```shell {"Protocol":0,"Id":"6ba68b9e5575aea503fa95d37f39e021","Path":"I:\\Pittis Blue Ray Filmarchiv\\The 6th Day","EncoderPath":null,"EncoderProtocol":null,"Type":0,"Container":"ts","Size":3999946752,"Name":"The 6th Day/Bluray","IsRemote":false,"ETag":"543b6ca4c9f21c87d81daf7a932499c0","RunTimeTicks":74144069333,"ReadAtNativeFramerate":false,"IgnoreDts":false,"IgnoreIndex":false,"GenPtsInput":false,"SupportsTranscoding":true,"SupportsDirectStream":false,"SupportsDirectPlay":true,"IsInfiniteStream":false,"RequiresOpening":false,"OpenToken":null,"RequiresClosing":false,"LiveStreamId":null,"BufferMs":null,"RequiresLooping":false,"SupportsProbing":true,"VideoType":3,"IsoType":null,"Video3DFormat":null,"MediaStreams":[{"Codec":"h264","CodecTag":null,"Language":null,"ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":1,"VideoRangeType":1,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":null,"LocalizedForced":null,"LocalizedExternal":null,"LocalizedHearingImpaired":null,"DisplayTitle":"1080p H264 SDR","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":9061327,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":1080,"Width":1920,"AverageFrameRate":23.976025,"RealFrameRate":23.976025,"Profile":null,"Type":1,"AspectRatio":null,"Index":0,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"AC3","CodecTag":null,"Language":"ger","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":"Standard","LocalizedForced":null,"LocalizedExternal":"Extern","LocalizedHearingImpaired":null,"DisplayTitle":"Ger - Dolby Digital - 6 ch","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":448000,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":6,"SampleRate":48000,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":0,"AspectRatio":null,"Index":1,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"AC3","CodecTag":null,"Language":"eng","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":"Standard","LocalizedForced":null,"LocalizedExternal":"Extern","LocalizedHearingImpaired":null,"DisplayTitle":"Englisch - Dolby Digital - 6 ch","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":448000,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":6,"SampleRate":48000,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":0,"AspectRatio":null,"Index":2,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"AC3","CodecTag":null,"Language":"rus","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":"Standard","LocalizedForced":null,"LocalizedExternal":"Extern","LocalizedHearingImpaired":null,"DisplayTitle":"Russisch - Dolby Digital - 6 ch","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":448000,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":6,"SampleRate":48000,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":0,"AspectRatio":null,"Index":3,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"TrueHD","CodecTag":null,"Language":"ger","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":"Standard","LocalizedForced":null,"LocalizedExternal":"Extern","LocalizedHearingImpaired":null,"DisplayTitle":"Ger - TRUEHD - 6 ch","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":6,"SampleRate":48000,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":0,"AspectRatio":null,"Index":4,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"PGS","CodecTag":null,"Language":"ger","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":"Undefiniert","LocalizedDefault":"Standard","LocalizedForced":"Erzwungen","LocalizedExternal":"Extern","LocalizedHearingImpaired":"H\u00F6rgesch\u00E4digt","DisplayTitle":"Ger - PGS","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":2,"AspectRatio":null,"Index":5,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"PGS","CodecTag":null,"Language":"eng","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":"Undefiniert","LocalizedDefault":"Standard","LocalizedForced":"Erzwungen","LocalizedExternal":"Extern","LocalizedHearingImpaired":"H\u00F6rgesch\u00E4digt","DisplayTitle":"Englisch - PGS","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":2,"AspectRatio":null,"Index":6,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null},{"Codec":"PGS","CodecTag":null,"Language":"rus","ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":null,"CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":"Undefiniert","LocalizedDefault":"Standard","LocalizedForced":"Erzwungen","LocalizedExternal":"Extern","LocalizedHearingImpaired":"H\u00F6rgesch\u00E4digt","DisplayTitle":"Russisch - PGS","NalLengthSize":null,"IsInterlaced":false,"IsAVC":null,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":2,"AspectRatio":null,"Index":7,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":null,"IsAnamorphic":null}],"MediaAttachments":[],"Formats":[],"Bitrate":11045327,"Timestamp":2,"RequiredHttpHeaders":{},"TranscodingUrl":null,"TranscodingSubProtocol":0,"TranscodingContainer":null,"AnalyzeDurationMs":null,"DefaultAudioStreamIndex":null,"DefaultSubtitleStreamIndex":null} ffmpeg -analyzeduration 200M -probesize 1G -f concat -safe 0 -i "C:\ProgramData\Jellyfin\Server\cache\transcodes\6ba68b9e5575aea503fa95d37f39e021.concat" -map_metadata -1 -map_chapters -1 -threads 0 -map 0:0 -map 0:1 -map -0:s -codec:v:0 libx264 -preset medium -crf 23 -maxrate 9061327 -bufsize 18122654 -profile:v:0 high -level 51 -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none -force_key_frames:0 "expr:gte(t,n_forced*3)" -sc_threshold:v:0 0 -vf "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709,scale=trunc(min(max(iw\,ih*a)\,min(1920\,1080*a))/2)*2:trunc(min(max(iw/a\,ih)\,min(1920/a\,1080))/2)*2,format=yuv420p" -codec:a:0 libfdk_aac -ac 2 -ab 256000 -af "volume=2" -copyts -avoid_negative_ts disabled -max_muxing_queue_size 2048 -f hls -max_delay 5000000 -hls_time 3 -hls_segment_type fmp4 -hls_fmp4_init_filename "C:\ProgramData\Jellyfin\Server\cache\transcodes\f9c9739596bf17dfcf2da4cbb365bddb-1.mp4" -start_number 0 -hls_segment_filename "C:\ProgramData\Jellyfin\Server\cache\transcodes\f9c9739596bf17dfcf2da4cbb365bddb%d.mp4" -hls_playlist_type vod -hls_list_size 0 -y "C:\ProgramData\Jellyfin\Server\cache\transcodes\f9c9739596bf17dfcf2da4cbb365bddb.m3u8" ffmpeg version 6.0.1-Jellyfin Copyright (c) 2000-2023 the FFmpeg developers built with gcc 13-win32 (GCC) configuration: --prefix=/opt/ffmpeg --arch=x86_64 --target-os=mingw32 --cross-prefix=x86_64-w64-mingw32- --pkg-config=pkg-config --pkg-config-flags=--static --extra-version=Jellyfin --disable-ffplay --disable-debug --disable-doc --disable-sdl2 --disable-ptx-compression --disable-w32threads --enable-pthreads --enable-shared --enable-lto --enable-gpl --enable-version3 --enable-schannel --enable-iconv --enable-libxml2 --enable-zlib --enable-lzma --enable-gmp --enable-chromaprint --enable-libfreetype --enable-libfribidi --enable-libfontconfig --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libopenmpt --enable-libwebp --enable-libvpx --enable-libzimg --enable-libx264 --enable-libx265 --enable-libsvtav1 --enable-libdav1d --enable-libfdk-aac --enable-opencl --enable-dxva2 --enable-d3d11va --enable-amf --enable-libvpl --enable-ffnvcodec --enable-cuda --enable-cuda-llvm --enable-cuvid --enable-nvdec --enable-nvenc libavutil 58. 2.100 / 58. 2.100 libavcodec 60. 3.100 / 60. 3.100 libavformat 60. 3.100 / 60. 3.100 libavdevice 60. 1.100 / 60. 1.100 libavfilter 9. 3.100 / 9. 3.100 libswscale 7. 1.100 / 7. 1.100 libswresample 4. 10.100 / 4. 10.100 libpostproc 57. 1.100 / 57. 1.100 [concat @ 00000230306ea140] Line 2: invalid duration '3531,444544' C:\ProgramData\Jellyfin\Server\cache\transcodes\6ba68b9e5575aea503fa95d37f39e021.concat: Invalid argument ``` ### Client / Browser logs _No response_ ### Relevant screenshots or videos _No response_ ### Additional information _No response_
So the tdlr is the concat file writes the duration float wrong due to internationalization. Down there is the detailed issue description + fix: ### Please describe your bug All DVD structured folders aka VIDEO_TS aren't played because ffmpeg exits before. This is because of wrong generated concat files in C:\Users\XXX\AppData\Local\jellyfin\cache\transcodes. **example content of such a concat file before it gets deleted:** > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_1.VOB' > duration 925,696 > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_2.VOB' > duration 881,056 > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_3.VOB' > duration 924,64 > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_4.VOB' > duration 855,168 > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_5.VOB' > duration 879,2 > file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_6.VOB' > duration 966,56 **1. Problem:** as one can see the duraction is represented in numbers using a comma which ffmpeg can't use because of the wrong formatting. if i turn all the commas into dots and save the file afterwards the ffmpeg command works. I think my generated concat file uses commas because in germany these floats are represented with commas and not with dots like in the us. **EDIT (this should be the fix in the sourcecode):** Seems like the issue is in the `MediEncoder.cs` File at public void `GenerateConcatConfig(MediaSourceInfo source, string concatFilePath)` The line `var duration = TimeSpan.FromTicks(mediaInfoResult.RunTimeTicks.Value).TotalSeconds;` doesn't format the TimeSpan properly so other internationalizations don't represent the TimeSpan diffrently. **So the fixed code would be:** ` sw.WriteLine("duration {0}", duration.ToString(new System.Globalization.NumberFormatInfo { NumberDecimalSeparator = "." })); EDIT2 : just delete the duration line entirely? ` ---pls fix this for me its my second time using github and im to dumb to pull--- **2. Problem:** the concat file doesn't include the last vob file every time. **The video folder has the follwoing files inside (using the dir command):** > 04.05.2015 21:34 12.288 VIDEO_TS.BUP > 04.05.2015 21:34 12.288 VIDEO_TS.IFO > 03.06.2024 12:50 8.370 VIDEO_TS.nfo > 04.05.2015 21:34 67.584 VTS_01_0.BUP > 04.05.2015 21:34 67.584 VTS_01_0.IFO > 04.05.2015 21:34 1.073.256.448 VTS_01_1.VOB > 04.05.2015 21:34 1.073.195.008 VTS_01_2.VOB > 04.05.2015 21:34 1.073.276.928 VTS_01_3.VOB > 04.05.2015 21:34 1.073.356.800 VTS_01_4.VOB > 04.05.2015 21:34 1.073.539.072 VTS_01_5.VOB > 04.05.2015 21:34 1.073.453.056 VTS_01_6.VOB > 04.05.2015 21:34 807.540.736 VTS_01_7.VOB so the last few minutes of the film are missing. If i add another line after the last one of the concat file with _file 'C:\Movies\WHOAMI\VIDEO_TS\VTS_01_7.VOB'_ the whole movie is displayed. ### Reproduction Steps 1. Install Windows in German 2. Install Jellyfin Windows via Installer in German too 3. Include Media which has the DVD structure (VIDEO_TS) 4. Play that Media and get an error 5. Check the temporary concat file which gets created ### Jellyfin Version 10.9.0 ### if other: 10.9.4 ### Environment ```markdown - OS: Windows10 - Linux Kernel:- - Virtualization:- - Clients:- - Browser:Firefox (latest) - FFmpeg Version:ffmpeg version 6.0.1-Jellyfin - Playback Method:Browser - Hardware Acceleration: tested with software and intel quick sync. Not hw acc related. - GPU Model:- - Plugins:- - Reverse Proxy:- - Base URL:localhost - Networking:- - Storage: local C drive ``` ### Jellyfin logs ```shell [2024-06-03 20:40:09.779 +02:00] [ERR] [55] Jellyfin.Api.Middleware.ExceptionMiddleware: Error processing request. URL "GET" "/videos/4d32af64-eb44-4677-6a7e-2df132b2e4a7/hls1/main/0.ts". MediaBrowser.Common.FfmpegException: FFmpeg exited with code 1 at MediaBrowser.MediaEncoding.Transcoding.TranscodeManager.StartFfMpeg(StreamState state, String outputPath, String commandLineArguments, Guid userId, TranscodingJobType transcodingJobType, CancellationTokenSource cancellationTokenSource, String workingDirectory) at Jellyfin.Api.Controllers.DynamicHlsController.GetDynamicSegment(StreamingRequestDto streamingRequest, Int32 segmentId) at Jellyfin.Api.Controllers.DynamicHlsController.GetHlsVideoSegment(Guid itemId, String playlistId, Int32 segmentId, String container, Int64 runtimeTicks, Int64 actualSegmentLengthTicks, Nullable`1 static, String params, String tag, String deviceProfileId, String playSessionId, String segmentContainer, Nullable`1 segmentLength, Nullable`1 minSegments, String mediaSourceId, String deviceId, String audioCodec, Nullable`1 enableAutoStreamCopy, Nullable`1 allowVideoStreamCopy, Nullable`1 allowAudioStreamCopy, Nullable`1 breakOnNonKeyFrames, Nullable`1 audioSampleRate, Nullable`1 maxAudioBitDepth, Nullable`1 audioBitRate, Nullable`1 audioChannels, Nullable`1 maxAudioChannels, String profile, String level, Nullable`1 framerate, Nullable`1 maxFramerate, Nullable`1 copyTimestamps, Nullable`1 startTimeTicks, Nullable`1 width, Nullable`1 height, Nullable`1 maxWidth, Nullable`1 maxHeight, Nullable`1 videoBitRate, Nullable`1 subtitleStreamIndex, Nullable`1 subtitleMethod, Nullable`1 maxRefFrames, Nullable`1 maxVideoBitDepth, Nullable`1 requireAvc, Nullable`1 deInterlace, Nullable`1 requireNonAnamorphic, Nullable`1 transcodingMaxAudioChannels, Nullable`1 cpuCoreLimit, String liveStreamId, Nullable`1 enableMpegtsM2TsMode, String videoCodec, String subtitleCodec, String transcodeReasons, Nullable`1 audioStreamIndex, Nullable`1 videoStreamIndex, Nullable`1 context, Dictionary`2 streamOptions) at lambda_method1078(Closure, Object) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger) at Jellyfin.Api.Middleware.ServerStartupMessageMiddleware.Invoke(HttpContext httpContext, IServerApplicationHost serverApplicationHost, ILocalizationManager localizationManager) at Jellyfin.Api.Middleware.WebSocketHandlerMiddleware.Invoke(HttpContext httpContext, IWebSocketManager webSocketManager) at Jellyfin.Api.Middleware.IPBasedAccessValidationMiddleware.Invoke(HttpContext httpContext, INetworkManager networkManager) at Jellyfin.Api.Middleware.LanFilteringMiddleware.Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Jellyfin.Api.Middleware.QueryStringDecodingMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.ReDoc.ReDocMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Jellyfin.Api.Middleware.RobotsRedirectionMiddleware.Invoke(HttpContext httpContext) at Jellyfin.Api.Middleware.LegacyEmbyRouteRewriteMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.InvokeCore(HttpContext context) at Jellyfin.Api.Middleware.ResponseTimeMiddleware.Invoke(HttpContext context, IServerConfigurationManager serverConfigurationManager) at Jellyfin.Api.Middleware.ExceptionMiddleware.Invoke(HttpContext context) ``` ### FFmpeg logs ```shell {"Protocol":0,"Id":"4d32af64eb4446776a7e2df132b2e4a7","Path":"C:\\Movies\\WHOAMI","EncoderPath":null,"EncoderProtocol":null,"Type":0,"Container":"ts","Size":1073256448,"Name":"WHOAMI/DVD","IsRemote":false,"ETag":"543b6ca4c9f21c87d81daf7a932499c0","RunTimeTicks":54323200000,"ReadAtNativeFramerate":false,"IgnoreDts":false,"IgnoreIndex":false,"GenPtsInput":false,"SupportsTranscoding":true,"SupportsDirectStream":false,"SupportsDirectPlay":true,"IsInfiniteStream":false,"RequiresOpening":false,"OpenToken":null,"RequiresClosing":false,"LiveStreamId":null,"BufferMs":null,"RequiresLooping":false,"SupportsProbing":true,"VideoType":2,"IsoType":null,"Video3DFormat":null,"MediaStreams":[{"Codec":"dvd_nav_packet","CodecTag":null,"Language":null,"ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":"1/90000","CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":null,"LocalizedForced":null,"LocalizedExternal":null,"LocalizedHearingImpaired":null,"DisplayTitle":null,"NalLengthSize":null,"IsInterlaced":false,"IsAVC":false,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":4,"AspectRatio":null,"Index":0,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":0,"IsAnamorphic":null},{"Codec":"mpeg2video","CodecTag":null,"Language":null,"ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":"1/90000","CodecTimeBase":null,"Title":null,"VideoRange":1,"VideoRangeType":1,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":null,"LocalizedForced":null,"LocalizedExternal":null,"LocalizedHearingImpaired":null,"DisplayTitle":"480p MPEG2VIDEO SDR","NalLengthSize":null,"IsInterlaced":false,"IsAVC":false,"ChannelLayout":null,"BitRate":9275238,"BitDepth":8,"RefFrames":1,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":480,"Width":720,"AverageFrameRate":25,"RealFrameRate":25,"Profile":"Main","Type":1,"AspectRatio":"16:9","Index":1,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":"yuv420p","Level":8,"IsAnamorphic":false},{"Codec":"ac3","CodecTag":null,"Language":null,"ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":"1/90000","CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":null,"LocalizedDefault":null,"LocalizedForced":null,"LocalizedExternal":null,"LocalizedHearingImpaired":null,"DisplayTitle":"Dolby Digital - 5.1","NalLengthSize":null,"IsInterlaced":false,"IsAVC":false,"ChannelLayout":"5.1","BitRate":448000,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":6,"SampleRate":48000,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":null,"Width":null,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":0,"AspectRatio":null,"Index":2,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":0,"IsAnamorphic":null},{"Codec":"DVDSUB","CodecTag":null,"Language":null,"ColorRange":null,"ColorSpace":null,"ColorTransfer":null,"ColorPrimaries":null,"DvVersionMajor":null,"DvVersionMinor":null,"DvProfile":null,"DvLevel":null,"RpuPresentFlag":null,"ElPresentFlag":null,"BlPresentFlag":null,"DvBlSignalCompatibilityId":null,"Comment":null,"TimeBase":"1/90000","CodecTimeBase":null,"Title":null,"VideoRange":0,"VideoRangeType":0,"VideoDoViTitle":null,"AudioSpatialFormat":0,"LocalizedUndefined":"Undefiniert","LocalizedDefault":"Standard","LocalizedForced":"Erzwungen","LocalizedExternal":"Extern","LocalizedHearingImpaired":"H\u00F6rgesch\u00E4digt","DisplayTitle":"Undefiniert - DVDSUB","NalLengthSize":null,"IsInterlaced":false,"IsAVC":false,"ChannelLayout":null,"BitRate":null,"BitDepth":null,"RefFrames":null,"PacketLength":null,"Channels":null,"SampleRate":null,"IsDefault":false,"IsForced":false,"IsHearingImpaired":false,"Height":0,"Width":0,"AverageFrameRate":null,"RealFrameRate":null,"Profile":null,"Type":2,"AspectRatio":null,"Index":3,"Score":null,"IsExternal":false,"DeliveryMethod":null,"DeliveryUrl":null,"IsExternalUrl":null,"IsTextSubtitleStream":false,"SupportsExternalStream":false,"Path":null,"PixelFormat":null,"Level":0,"IsAnamorphic":null}],"MediaAttachments":[],"Formats":[],"Bitrate":9723238,"Timestamp":0,"RequiredHttpHeaders":{},"TranscodingUrl":null,"TranscodingSubProtocol":0,"TranscodingContainer":null,"AnalyzeDurationMs":null,"DefaultAudioStreamIndex":null,"DefaultSubtitleStreamIndex":null} ffmpeg -analyzeduration 200M -probesize 1G -f mpegts -noautorotate -f concat -safe 0 -i "C:\Users\Edge\AppData\Local\Jellyfin\cache\transcodes\4d32af64eb4446776a7e2df132b2e4a7.concat" -map_metadata -1 -map_chapters -1 -threads 0 -map 0:1 -map 0:2 -map -0:s -codec:v:0 libx264 -preset veryfast -crf 23 -maxrate 9275238 -bufsize 18550476 -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none -force_key_frames:0 "expr:gte(t,n_forced*3)" -sc_threshold:v:0 0 -vf "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709,scale=trunc(min(max(iw\,ih*a)\,min(720\,480*a))/2)*2:trunc(min(max(iw/a\,ih)\,min(720/a\,480))/2)*2,format=yuv420p" -codec:a:0 libfdk_aac -ac 2 -ab 256000 -af "volume=2" -copyts -avoid_negative_ts disabled -max_muxing_queue_size 2048 -f hls -max_delay 5000000 -hls_time 3 -hls_segment_type mpegts -start_number 0 -hls_segment_filename "C:\Users\XXX\AppData\Local\Jellyfin\cache\transcodes\2056fc15280d3f2207a9d75a5e96666b%d.ts" -hls_playlist_type vod -hls_list_size 0 -y "C:\Users\XXX\AppData\Local\Jellyfin\cache\transcodes\2056fc15280d3f2207a9d75a5e96666b.m3u8" ffmpeg version 6.0.1-Jellyfin Copyright (c) 2000-2023 the FFmpeg developers built with gcc 13-win32 (GCC) configuration: --prefix=/opt/ffmpeg --arch=x86_64 --target-os=mingw32 --cross-prefix=x86_64-w64-mingw32- --pkg-config=pkg-config --pkg-config-flags=--static --extra-version=Jellyfin --disable-ffplay --disable-debug --disable-doc --disable-sdl2 --disable-ptx-compression --disable-w32threads --enable-pthreads --enable-shared --enable-lto --enable-gpl --enable-version3 --enable-schannel --enable-iconv --enable-libxml2 --enable-zlib --enable-lzma --enable-gmp --enable-chromaprint --enable-libfreetype --enable-libfribidi --enable-libfontconfig --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libopenmpt --enable-libwebp --enable-libvpx --enable-libzimg --enable-libx264 --enable-libx265 --enable-libsvtav1 --enable-libdav1d --enable-libfdk-aac --enable-opencl --enable-dxva2 --enable-d3d11va --enable-amf --enable-libvpl --enable-ffnvcodec --enable-cuda --enable-cuda-llvm --enable-cuvid --enable-nvdec --enable-nvenc libavutil 58. 2.100 / 58. 2.100 libavcodec 60. 3.100 / 60. 3.100 libavformat 60. 3.100 / 60. 3.100 libavdevice 60. 1.100 / 60. 1.100 libavfilter 9. 3.100 / 9. 3.100 libswscale 7. 1.100 / 7. 1.100 libswresample 4. 10.100 / 4. 10.100 libpostproc 57. 1.100 / 57. 1.100 [concat @ 00000195b7f47a80] Line 2: invalid duration '925,696' C:\Users\XXX\AppData\Local\Jellyfin\cache\transcodes\4d32af64eb4446776a7e2df132b2e4a7.concat: Invalid argument ``` ### Please attach any browser or client logs here _No response_ ### Please attach any screenshots here _No response_ ### Code of Conduct - [X] I agree to follow this project's Code of Conduct can you try to grab that concat file it is complaining about and upload it here?
2024-08-30T15:19:39Z
0.1
['Jellyfin.Extensions.Tests.FormattingStreamWriterTests.Shuffle_Valid_Correct']
[]
gui-cs/Terminal.Gui
gui-cs__terminal-gui-3195
c8e54bba099763a593a3dd3427b795ab5b22dd0f
diff --git a/Terminal.Gui/Views/Button.cs b/Terminal.Gui/Views/Button.cs index c5995f838d..0c90c13b8e 100644 --- a/Terminal.Gui/Views/Button.cs +++ b/Terminal.Gui/Views/Button.cs @@ -129,6 +129,10 @@ void Initialize (ustring text, bool is_default) /// Gets or sets whether the <see cref="Button"/> is the default action to activate in a dialog. /// </summary> /// <value><c>true</c> if is default; otherwise, <c>false</c>.</value> + /// <remarks> + /// If is <see langword="true"/> the current focused view + /// will remain focused if the window is not closed. + /// </remarks> public bool IsDefault { get => is_default; set { @@ -219,7 +223,7 @@ bool ExecuteColdKey (KeyEvent ke) bool AcceptKey () { - if (!HasFocus) { + if (!IsDefault && !HasFocus) { SetFocus (); } OnClicked (); diff --git a/UnitTests/Views/ButtonTests.cs b/UnitTests/Views/ButtonTests.cs index 0202db0e3b..5ef99cfa80 100644 --- a/UnitTests/Views/ButtonTests.cs +++ b/UnitTests/Views/ButtonTests.cs @@ -585,5 +585,21 @@ public void Pos_Center_Layout_AutoSize_False () TestHelpers.AssertDriverContentsWithFrameAre (expected, output); } + + [Fact, AutoInitShutdown] + public void IsDefault_True_Does_Not_Get_The_Focus_On_Enter_Key () + { + var wasClicked = false; + var view = new View { CanFocus = true }; + var btn = new Button { Text = "Ok", IsDefault = true }; + btn.Clicked += () => wasClicked = true; + Application.Top.Add (view, btn); + Application.Begin (Application.Top); + Assert.True (view.HasFocus); + + Application.Top.ProcessColdKey (new KeyEvent (Key.Enter, new KeyModifiers ())); + Assert.True (view.HasFocus); + Assert.True (wasClicked); + } } }
diff --git a/testenvironments.json b/testenvironments.json index 898ac827de..25324739d6 100644 --- a/testenvironments.json +++ b/testenvironments.json @@ -10,6 +10,11 @@ "type": "wsl", "wslDistribution": "Ubuntu" }, + { + "name": "WSL-Ubuntu-20.04", + "type": "wsl", + "wslDistribution": "Ubuntu-20.04" + }, { "name": "WSL-Debian", "type": "wsl",
Pressing the ENTER key in a TextField should not move the focus **Describe the bug** Pressing the ENTER key in a TextField should not move the focus away from the TextField. **To Reproduce** Steps to reproduce the behavior: 1. Use the example at https://github.com/gui-cs/Terminal.Gui#sample-usage-in-c 2. Press the ENTER key (in the username TextField, which should be focused by default). 3. See that the cursor/focus is not in the TextField anymore **Expected behavior** I expected the focus to remain in the TextField where I've pressed the ENTER key.
That is the expected behavior if the button is set as default. If you set `IsDefault = false`, then the `Textfield` wouldn't loss the focus. With `IsDefault = false`, pressing the ENTER key in the `TextField` would still trigger the default button action? If not, I do not want to do that, as that looses the ability to trigger the default button action. IMHO, the expected behavior should be like Windows Forms control, where it does not loose focus. > With `IsDefault = false`, pressing the ENTER key in the `TextField` would still trigger the default button action? No, if it's false then will not trigger the button action and the `TextField` maintain the focus. Ah, so I do not want to do that, as that looses the ability to trigger the default button action. IMHO, it should behave be like Windows Forms, where it does not loose focus. That is a much better user experience than having the focus unexpectedly bouncing to the button. When the button is default it will get the focus but it can focus again the previous focused view with some change to the button action, It's a suggestion to do that feature :-) In `Button.cs` it's only need do change like this: ```cs ///<inheritdoc/> public override bool ProcessColdKey (KeyEvent kb) { if (!Enabled) { return false; } var focused = SuperView?.MostFocused; var res = ExecuteColdKey (kb); focused?.SetFocus (); return res; } ``` I believe this is addressed. Closing. Reopen if you disagree. @tig why do you believe its addressed? was there a commit about this?
2024-01-20T01:40:39Z
0.1
['Terminal.Gui.ViewTests.ButtonTests.IsDefault_True_Does_Not_Get_The_Focus_On_Enter_Key']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1552
0e2ed511a5cfa303ba99c97ebb3f36c50cfa526f
diff --git a/src/Spectre.Console.Cli/Internal/Configuration/TemplateParser.cs b/src/Spectre.Console.Cli/Internal/Configuration/TemplateParser.cs index d7eef9b05..125947280 100644 --- a/src/Spectre.Console.Cli/Internal/Configuration/TemplateParser.cs +++ b/src/Spectre.Console.Cli/Internal/Configuration/TemplateParser.cs @@ -86,7 +86,7 @@ public static OptionResult ParseOptionTemplate(string template) foreach (var character in token.Value) { - if (!char.IsLetterOrDigit(character) && character != '-' && character != '_') + if (!char.IsLetterOrDigit(character) && character != '-' && character != '_' && character != '?') { throw CommandTemplateException.InvalidCharacterInOptionName(template, token, character); } diff --git a/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeParser.cs b/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeParser.cs index e4fad73a3..d985dcbd2 100644 --- a/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeParser.cs +++ b/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeParser.cs @@ -21,7 +21,7 @@ public CommandTreeParser(CommandModel configuration, CaseSensitivity caseSensiti { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _parsingMode = parsingMode ?? _configuration.ParsingMode; - _help = new CommandOptionAttribute("-h|--help"); + _help = new CommandOptionAttribute("-?|-h|--help"); _convertFlagsToRemainingArguments = convertFlagsToRemainingArguments ?? false; CaseSensitivity = caseSensitivity; diff --git a/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeTokenizer.cs b/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeTokenizer.cs index 27e6edbc6..840b072c7 100644 --- a/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeTokenizer.cs +++ b/src/Spectre.Console.Cli/Internal/Parsing/CommandTreeTokenizer.cs @@ -176,7 +176,7 @@ private static IEnumerable<CommandTreeToken> ScanShortOptions(CommandTreeTokeniz break; } - if (char.IsLetter(current)) + if (char.IsLetter(current) || current is '?') { context.AddRemaining(current); reader.Read(); // Consume
diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.QuestionMark.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.QuestionMark.verified.txt new file mode 100644 index 000000000..0432fe41a --- /dev/null +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.QuestionMark.verified.txt @@ -0,0 +1,10 @@ +USAGE: + myapp [OPTIONS] <COMMAND> + +OPTIONS: + -h, --help Prints help information + +COMMANDS: + dog <AGE> The dog command + horse The horse command + giraffe <LENGTH> The giraffe command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.QuestionMark.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.QuestionMark.verified.txt new file mode 100644 index 000000000..03c68750d --- /dev/null +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.QuestionMark.verified.txt @@ -0,0 +1,17 @@ +DESCRIPTION: +The horse command. + +USAGE: + myapp horse [LEGS] [OPTIONS] + +ARGUMENTS: + [LEGS] The number of legs + +OPTIONS: + DEFAULT + -h, --help Prints help information + -a, --alive Indicates whether or not the animal is alive + -n, --name <VALUE> + -d, --day <MON|TUE> + --file food.txt + --directory \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs index 9ce30cc24..8d3af800f 100644 --- a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs +++ b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs @@ -28,6 +28,27 @@ public Task Should_Output_Root_Correctly() return Verifier.Verify(result.Output); } + [Fact] + [Expectation("Root", "QuestionMark")] + public Task Should_Output_Root_Correctly_QuestionMark() + { + // Given + var fixture = new CommandAppTester(); + fixture.Configure(configurator => + { + configurator.SetApplicationName("myapp"); + configurator.AddCommand<DogCommand>("dog"); + configurator.AddCommand<HorseCommand>("horse"); + configurator.AddCommand<GiraffeCommand>("giraffe"); + }); + + // When + var result = fixture.Run("-?"); + + // Then + return Verifier.Verify(result.Output); + } + [Fact] [Expectation("Root_Command")] public Task Should_Output_Root_Command_Correctly() @@ -49,6 +70,27 @@ public Task Should_Output_Root_Command_Correctly() return Verifier.Verify(result.Output); } + [Fact] + [Expectation("Root_Command", "QuestionMark")] + public Task Should_Output_Root_Command_Correctly_QuestionMark() + { + // Given + var fixture = new CommandAppTester(); + fixture.Configure(configurator => + { + configurator.SetApplicationName("myapp"); + configurator.AddCommand<DogCommand>("dog"); + configurator.AddCommand<HorseCommand>("horse"); + configurator.AddCommand<GiraffeCommand>("giraffe"); + }); + + // When + var result = fixture.Run("horse", "-?"); + + // Then + return Verifier.Verify(result.Output); + } + [Fact] [Expectation("Hidden_Commands")] public Task Should_Skip_Hidden_Commands()
Add '-?' as an additional alias for '-h' and '--help', just like 'dotnet -?' It's second nature for me to just type `-?` to get help on stuff. Even in the GitHub CLI, typing `gh -?` (although not an official option to get help) gets you the default help :). I'd say it's a common enough shorthand for help that it deserves being supported built-in.
Sounds like a reasonable thing to add 👍
2024-05-17T21:10:33Z
0.1
['Spectre.Console.Tests.Unit.Cli.CommandAppTests+Help.Should_Output_Root_Correctly_QuestionMark', 'Spectre.Console.Tests.Unit.Cli.CommandAppTests+Help.Should_Output_Root_Command_Correctly_QuestionMark']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1531
c5e11626b521c47c45339d90ae7dcebc736a3224
diff --git a/dotnet-tools.json b/dotnet-tools.json index b0036d859..a7f9d036b 100644 --- a/dotnet-tools.json +++ b/dotnet-tools.json @@ -13,6 +13,12 @@ "commands": [ "dotnet-example" ] + }, + "verify.tool": { + "version": "0.6.0", + "commands": [ + "dotnet-verify" + ] } } } \ No newline at end of file diff --git a/src/Spectre.Console.Cli/ConfiguratorExtensions.cs b/src/Spectre.Console.Cli/ConfiguratorExtensions.cs index eb3f1be19..80895e302 100644 --- a/src/Spectre.Console.Cli/ConfiguratorExtensions.cs +++ b/src/Spectre.Console.Cli/ConfiguratorExtensions.cs @@ -82,7 +82,7 @@ public static IConfigurator SetApplicationName(this IConfigurator configurator, } /// <summary> - /// Overrides the auto-detected version of the application. + /// Sets the version of the application. /// </summary> /// <param name="configurator">The configurator.</param> /// <param name="version">The version of application.</param> @@ -98,6 +98,25 @@ public static IConfigurator SetApplicationVersion(this IConfigurator configurato return configurator; } + /// <summary> + /// Uses the version retrieved from the <see cref="AssemblyInformationalVersionAttribute"/> + /// as the application's version. + /// </summary> + /// <param name="configurator">The configurator.</param> + /// <returns>A configurator that can be used to configure the application further.</returns> + public static IConfigurator UseAssemblyInformationalVersion(this IConfigurator configurator) + { + if (configurator == null) + { + throw new ArgumentNullException(nameof(configurator)); + } + + configurator.Settings.ApplicationVersion = + VersionHelper.GetVersion(Assembly.GetEntryAssembly()); + + return configurator; + } + /// <summary> /// Hides the <c>DEFAULT</c> column that lists default values coming from the /// <see cref="DefaultValueAttribute"/> in the options help text. diff --git a/src/Spectre.Console.Cli/Help/HelpProvider.cs b/src/Spectre.Console.Cli/Help/HelpProvider.cs index 222b3d4ad..ca18f0fbb 100644 --- a/src/Spectre.Console.Cli/Help/HelpProvider.cs +++ b/src/Spectre.Console.Cli/Help/HelpProvider.cs @@ -41,7 +41,7 @@ private sealed class HelpArgument public bool Required { get; } public string? Description { get; } - public HelpArgument(string name, int position, bool required, string? description) + private HelpArgument(string name, int position, bool required, string? description) { Name = name; Position = position; @@ -68,7 +68,7 @@ private sealed class HelpOption public string? Description { get; } public object? DefaultValue { get; } - public HelpOption(string? @short, string? @long, string? @value, bool? valueIsOptional, string? description, object? defaultValue) + private HelpOption(string? @short, string? @long, string? @value, bool? valueIsOptional, string? description, object? defaultValue) { Short = @short; Long = @long; @@ -78,17 +78,27 @@ public HelpOption(string? @short, string? @long, string? @value, bool? valueIsOp DefaultValue = defaultValue; } - public static IReadOnlyList<HelpOption> Get(ICommandInfo? command, HelpProviderResources resources) + public static IReadOnlyList<HelpOption> Get( + ICommandModel model, + ICommandInfo? command, + HelpProviderResources resources) { - var parameters = new List<HelpOption>(); - parameters.Add(new HelpOption("h", "help", null, null, resources.PrintHelpDescription, null)); + var parameters = new List<HelpOption> + { + new HelpOption("h", "help", null, null, resources.PrintHelpDescription, null), + }; // Version information applies to the entire application // Include the "-v" option in the help when at the root of the command line application // Don't allow the "-v" option if users have specified one or more sub-commands - if ((command == null || command?.Parent == null) && !(command?.IsBranch ?? false)) + if ((command?.Parent == null) && !(command?.IsBranch ?? false)) { - parameters.Add(new HelpOption("v", "version", null, null, resources.PrintVersionDescription, null)); + // Only show the version command if there is an + // application version set. + if (model.ApplicationVersion != null) + { + parameters.Add(new HelpOption("v", "version", null, null, resources.PrintVersionDescription, null)); + } } parameters.AddRange(command?.Parameters.OfType<ICommandOption>().Where(o => !o.IsHidden).Select(o => @@ -101,11 +111,6 @@ public static IReadOnlyList<HelpOption> Get(ICommandInfo? command, HelpProviderR } } - internal Composer NewComposer() - { - return new Composer(RenderMarkupInline); - } - /// <summary> /// Initializes a new instance of the <see cref="HelpProvider"/> class. /// </summary> @@ -383,7 +388,7 @@ public virtual IEnumerable<IRenderable> GetArguments(ICommandModel model, IComma public virtual IEnumerable<IRenderable> GetOptions(ICommandModel model, ICommandInfo? command) { // Collect all options into a single structure. - var parameters = HelpOption.Get(command, resources); + var parameters = HelpOption.Get(model, command, resources); if (parameters.Count == 0) { return Array.Empty<IRenderable>(); @@ -420,7 +425,7 @@ public virtual IEnumerable<IRenderable> GetOptions(ICommandModel model, ICommand if (defaultValueColumn) { - columns.Add(GetOptionDefaultValue(option.DefaultValue)); + columns.Add(GetDefaultValueForOption(option.DefaultValue)); } columns.Add(NewComposer().Text(option.Description?.TrimEnd('.') ?? " ")); @@ -433,60 +438,6 @@ public virtual IEnumerable<IRenderable> GetOptions(ICommandModel model, ICommand return result; } - private IRenderable GetOptionParts(HelpOption option) - { - var composer = NewComposer(); - - if (option.Short != null) - { - composer.Text("-").Text(option.Short); - if (option.Long != null) - { - composer.Text(", "); - } - } - else - { - composer.Text(" "); - if (option.Long != null) - { - composer.Text(" "); - } - } - - if (option.Long != null) - { - composer.Text("--").Text(option.Long); - } - - if (option.Value != null) - { - composer.Text(" "); - if (option.ValueIsOptional ?? false) - { - composer.Style(helpStyles?.Options?.OptionalOption ?? Style.Plain, $"[{option.Value}]"); - } - else - { - composer.Style(helpStyles?.Options?.RequiredOption ?? Style.Plain, $"<{option.Value}>"); - } - } - - return composer; - } - - private IRenderable GetOptionDefaultValue(object? defaultValue) - { - return defaultValue switch - { - null => NewComposer().Text(" "), - "" => NewComposer().Text(" "), - Array { Length: 0 } => NewComposer().Text(" "), - Array array => NewComposer().Join(", ", array.Cast<object>().Select(o => NewComposer().Style(helpStyles?.Options?.DefaultValue ?? Style.Plain, o.ToString() ?? string.Empty))), - _ => NewComposer().Style(helpStyles?.Options?.DefaultValue ?? Style.Plain, defaultValue?.ToString() ?? string.Empty), - }; - } - /// <summary> /// Gets the commands section of the help information. /// </summary> @@ -556,4 +507,63 @@ public virtual IEnumerable<IRenderable> GetFooter(ICommandModel model, ICommandI { yield break; } + + private Composer NewComposer() + { + return new Composer(RenderMarkupInline); + } + + private IRenderable GetOptionParts(HelpOption option) + { + var composer = NewComposer(); + + if (option.Short != null) + { + composer.Text("-").Text(option.Short); + if (option.Long != null) + { + composer.Text(", "); + } + } + else + { + composer.Text(" "); + if (option.Long != null) + { + composer.Text(" "); + } + } + + if (option.Long != null) + { + composer.Text("--").Text(option.Long); + } + + if (option.Value != null) + { + composer.Text(" "); + if (option.ValueIsOptional ?? false) + { + composer.Style(helpStyles?.Options?.OptionalOption ?? Style.Plain, $"[{option.Value}]"); + } + else + { + composer.Style(helpStyles?.Options?.RequiredOption ?? Style.Plain, $"<{option.Value}>"); + } + } + + return composer; + } + + private Composer GetDefaultValueForOption(object? defaultValue) + { + return defaultValue switch + { + null => NewComposer().Text(" "), + "" => NewComposer().Text(" "), + Array { Length: 0 } => NewComposer().Text(" "), + Array array => NewComposer().Join(", ", array.Cast<object>().Select(o => NewComposer().Style(helpStyles?.Options?.DefaultValue ?? Style.Plain, o.ToString() ?? string.Empty))), + _ => NewComposer().Style(helpStyles?.Options?.DefaultValue ?? Style.Plain, defaultValue?.ToString() ?? string.Empty), + }; + } } \ No newline at end of file diff --git a/src/Spectre.Console.Cli/Help/ICommandModel.cs b/src/Spectre.Console.Cli/Help/ICommandModel.cs index e7fe5f728..2872bf889 100644 --- a/src/Spectre.Console.Cli/Help/ICommandModel.cs +++ b/src/Spectre.Console.Cli/Help/ICommandModel.cs @@ -9,4 +9,9 @@ public interface ICommandModel : ICommandContainer /// Gets the name of the application. /// </summary> string ApplicationName { get; } + + /// <summary> + /// Gets the version of the application. + /// </summary> + string? ApplicationVersion { get; } } diff --git a/src/Spectre.Console.Cli/Internal/CommandExecutor.cs b/src/Spectre.Console.Cli/Internal/CommandExecutor.cs index 2c2b1594f..22eeb2084 100644 --- a/src/Spectre.Console.Cli/Internal/CommandExecutor.cs +++ b/src/Spectre.Console.Cli/Internal/CommandExecutor.cs @@ -39,9 +39,12 @@ public async Task<int> Execute(IConfiguration configuration, IEnumerable<string> if (firstArgument.Equals("--version", StringComparison.OrdinalIgnoreCase) || firstArgument.Equals("-v", StringComparison.OrdinalIgnoreCase)) { - var console = configuration.Settings.Console.GetConsole(); - console.WriteLine(ResolveApplicationVersion(configuration)); - return 0; + if (configuration.Settings.ApplicationVersion != null) + { + var console = configuration.Settings.Console.GetConsole(); + console.MarkupLine(configuration.Settings.ApplicationVersion); + return 0; + } } } } @@ -126,13 +129,6 @@ private CommandTreeParserResult ParseCommandLineArguments(CommandModel model, Co return parsedResult; } - private static string ResolveApplicationVersion(IConfiguration configuration) - { - return - configuration.Settings.ApplicationVersion ?? // potential override - VersionHelper.GetVersion(Assembly.GetEntryAssembly()); - } - private static async Task<int> Execute( CommandTree leaf, CommandTree tree, diff --git a/src/Spectre.Console.Cli/Internal/Modelling/CommandModel.cs b/src/Spectre.Console.Cli/Internal/Modelling/CommandModel.cs index 3da02da4b..721960bd3 100644 --- a/src/Spectre.Console.Cli/Internal/Modelling/CommandModel.cs +++ b/src/Spectre.Console.Cli/Internal/Modelling/CommandModel.cs @@ -3,6 +3,7 @@ namespace Spectre.Console.Cli; internal sealed class CommandModel : ICommandContainer, ICommandModel { public string? ApplicationName { get; } + public string? ApplicationVersion { get; } public ParsingMode ParsingMode { get; } public IList<CommandInfo> Commands { get; } public IList<string[]> Examples { get; } @@ -20,9 +21,10 @@ public CommandModel( IEnumerable<string[]> examples) { ApplicationName = settings.ApplicationName; + ApplicationVersion = settings.ApplicationVersion; ParsingMode = settings.ParsingMode; - Commands = new List<CommandInfo>(commands ?? Array.Empty<CommandInfo>()); - Examples = new List<string[]>(examples ?? Array.Empty<string[]>()); + Commands = new List<CommandInfo>(commands); + Examples = new List<string[]>(examples); } /// <summary>
diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/ArgumentOrder.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/ArgumentOrder.Output.verified.txt index 6e29ed297..9a82776df 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/ArgumentOrder.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/ArgumentOrder.Output.verified.txt @@ -1,4 +1,4 @@ -USAGE: +USAGE: myapp <FOO> <BAR> <BAZ> <CORGI> [QUX] [OPTIONS] ARGUMENTS: @@ -9,5 +9,4 @@ ARGUMENTS: [QUX] OPTIONS: - -h, --help Prints help information - -v, --version Prints version information \ No newline at end of file + -h, --help Prints help information \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Configured_By_Instance.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Configured_By_Instance.Output.verified.txt index e4a56cd59..f2bd53972 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Configured_By_Instance.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Configured_By_Instance.Output.verified.txt @@ -1,15 +1,14 @@ --------------------------------------- ---- CUSTOM HELP PROVIDER --- --------------------------------------- - -USAGE: - myapp [OPTIONS] <COMMAND> - -OPTIONS: - -h, --help Prints help information - -v, --version Prints version information - -COMMANDS: - dog <AGE> The dog command - +-------------------------------------- +--- CUSTOM HELP PROVIDER --- +-------------------------------------- + +USAGE: + myapp [OPTIONS] <COMMAND> + +OPTIONS: + -h, --help Prints help information + +COMMANDS: + dog <AGE> The dog command + Version 1.0 \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Registered_By_Instance.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Registered_By_Instance.Output.verified.txt index ad99fbb63..f2bd53972 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Registered_By_Instance.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Custom_Help_Registered_By_Instance.Output.verified.txt @@ -1,4 +1,4 @@ --------------------------------------- +-------------------------------------- --- CUSTOM HELP PROVIDER --- -------------------------------------- @@ -6,8 +6,7 @@ USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default.Output.verified.txt index aa1978d8b..b53a06eb8 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default.Output.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The lion command. USAGE: @@ -10,8 +10,7 @@ ARGUMENTS: OPTIONS: DEFAULT - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Examples.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Examples.Output.verified.txt index cd5b1e4fe..58c2ec53b 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Examples.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Examples.Output.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The dog command. USAGE: @@ -18,7 +18,6 @@ ARGUMENTS: OPTIONS: -h, --help Prints help information - -v, --version Prints version information -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> -g, --good-boy \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args.Output.verified.txt index aa1978d8b..b53a06eb8 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args.Output.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The lion command. USAGE: @@ -10,8 +10,7 @@ ARGUMENTS: OPTIONS: DEFAULT - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_DE.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_DE.verified.txt index ba0602d87..8f21e0057 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_DE.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_DE.verified.txt @@ -1,4 +1,4 @@ -BESCHREIBUNG: +BESCHREIBUNG: The lion command. VERWENDUNG: @@ -14,7 +14,6 @@ ARGUMENTE: OPTIONEN: STANDARDWERT -h, --help Zeigt Hilfe an - -v, --version Zeigt Versionsinformationen an -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_EN.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_EN.verified.txt index d4a593379..905156f8a 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_EN.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_EN.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The lion command. USAGE: @@ -13,8 +13,7 @@ ARGUMENTS: OPTIONS: DEFAULT - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_FR.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_FR.verified.txt index 126de22d6..a555c1c1c 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_FR.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_FR.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The lion command. UTILISATION: @@ -13,8 +13,7 @@ ARGUMENTS: OPTIONS: DÉFAUT - -h, --help Affiche l'aide - -v, --version Affiche la version + -h, --help Affiche l'aide -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_SV.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_SV.verified.txt index 2292492b8..45fd6c0c4 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_SV.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional.Output_SV.verified.txt @@ -1,4 +1,4 @@ -BESKRIVNING: +BESKRIVNING: The lion command. ANVÄNDING: @@ -14,7 +14,6 @@ ARGUMENT: VAL: STANDARD -h, --help Skriver ut hjälpinformation - -v, --version Skriver ut versionsnummer -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> --agility <VALUE> 10 The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_BoldHeadings.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_BoldHeadings.Output.verified.txt index 4bea738da..5b0f4264a 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_BoldHeadings.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_BoldHeadings.Output.verified.txt @@ -1,4 +1,4 @@ -[bold]DESCRIPTION:[/] +[bold]DESCRIPTION:[/] The lion command. [bold]USAGE:[/] @@ -14,7 +14,6 @@ The lion command. []OPTIONS:[/] []DEFAULT[/] -h, --help Prints help information - -v, --version Prints version information -a, --alive Indicates whether or not the animal is alive -n, --name []<VALUE>[/] --agility []<VALUE>[/] []10[/] The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_Default.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_Default.Output.verified.txt index 30421ace0..82570d3aa 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_Default.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_Default.Output.verified.txt @@ -1,4 +1,4 @@ -[yellow]DESCRIPTION:[/] +[yellow]DESCRIPTION:[/] The lion command. [yellow]USAGE:[/] @@ -14,7 +14,6 @@ The lion command. [yellow]OPTIONS:[/] [lime]DEFAULT[/] -h, --help Prints help information - -v, --version Prints version information -a, --alive Indicates whether or not the animal is alive -n, --name [silver]<VALUE>[/] --agility [silver]<VALUE>[/] [bold]10[/] The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_None.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_None.Output.verified.txt index a0bb7b25a..2b92a199c 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_None.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Default_Without_Args_Additional_Style_None.Output.verified.txt @@ -1,4 +1,4 @@ -[]DESCRIPTION:[/] +[]DESCRIPTION:[/] The lion command. []USAGE:[/] @@ -14,7 +14,6 @@ The lion command. []OPTIONS:[/] []DEFAULT[/] -h, --help Prints help information - -v, --version Prints version information -a, --alive Indicates whether or not the animal is alive -n, --name []<VALUE>[/] --agility []<VALUE>[/] []10[/] The agility between 0 and 100 diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Description_No_Trailing_Period.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Description_No_Trailing_Period.Output.verified.txt index b53e7717e..9662e05f6 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Description_No_Trailing_Period.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Description_No_Trailing_Period.Output.verified.txt @@ -1,9 +1,8 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command. diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Command_Options.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Command_Options.Output.verified.txt index 7288aefa5..b96464bf4 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Command_Options.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Command_Options.Output.verified.txt @@ -1,10 +1,9 @@ -USAGE: +USAGE: myapp <FOO> [OPTIONS] ARGUMENTS: <FOO> Dummy argument FOO OPTIONS: - -h, --help Prints help information - -v, --version Prints version information - --baz Dummy option BAZ \ No newline at end of file + -h, --help Prints help information + --baz Dummy option BAZ \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Commands.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Commands.Output.verified.txt index 6a792dad6..212276974 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Commands.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Hidden_Commands.Output.verified.txt @@ -1,9 +1,8 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/NoDescription.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/NoDescription.Output.verified.txt index f214d32a4..7e3e079cd 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/NoDescription.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/NoDescription.Output.verified.txt @@ -1,9 +1,8 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: bar \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/NoVersion.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/NoVersion.Output.verified.txt new file mode 100644 index 000000000..9a82776df --- /dev/null +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/NoVersion.Output.verified.txt @@ -0,0 +1,12 @@ +USAGE: + myapp <FOO> <BAR> <BAZ> <CORGI> [QUX] [OPTIONS] + +ARGUMENTS: + <FOO> + <BAR> + <BAZ> + <CORGI> + [QUX] + +OPTIONS: + -h, --help Prints help information \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.Output.verified.txt index 366b6b38d..aa3dcc3bf 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root.Output.verified.txt @@ -1,9 +1,8 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.Output.verified.txt index c660618c1..2c6e498be 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Command.Output.verified.txt @@ -1,4 +1,4 @@ -DESCRIPTION: +DESCRIPTION: The horse command. USAGE: @@ -10,7 +10,6 @@ ARGUMENTS: OPTIONS: DEFAULT -h, --help Prints help information - -v, --version Prints version information -a, --alive Indicates whether or not the animal is alive -n, --name <VALUE> -d, --day <MON|TUE> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples.Output.verified.txt index 3488e38c2..82ba4675d 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples.Output.verified.txt @@ -1,4 +1,4 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> EXAMPLES: @@ -16,8 +16,7 @@ EXAMPLES: myapp horse --name Spirit OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children.Output.verified.txt index 47e373aa3..e2b67c8a3 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children.Output.verified.txt @@ -1,4 +1,4 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> EXAMPLES: @@ -9,8 +9,7 @@ EXAMPLES: myapp dog --name Daisy OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: dog <AGE> The dog command diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Eight.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Eight.Output.verified.txt index 3e5a6d939..7b486e1fe 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Eight.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Eight.Output.verified.txt @@ -1,20 +1,19 @@ -USAGE: - myapp [OPTIONS] <COMMAND> - -EXAMPLES: - myapp dog --name Rufus --age 12 --good-boy - myapp dog --name Luna - myapp dog --name Charlie - myapp dog --name Bella - myapp dog --name Daisy - myapp dog --name Milo - myapp horse --name Brutus - myapp horse --name Sugar --IsAlive false - -OPTIONS: - -h, --help Prints help information - -v, --version Prints version information - -COMMANDS: - dog <AGE> The dog command +USAGE: + myapp [OPTIONS] <COMMAND> + +EXAMPLES: + myapp dog --name Rufus --age 12 --good-boy + myapp dog --name Luna + myapp dog --name Charlie + myapp dog --name Bella + myapp dog --name Daisy + myapp dog --name Milo + myapp horse --name Brutus + myapp horse --name Sugar --IsAlive false + +OPTIONS: + -h, --help Prints help information + +COMMANDS: + dog <AGE> The dog command horse The horse command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_None.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_None.Output.verified.txt index 3377d2a96..212276974 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_None.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_None.Output.verified.txt @@ -1,10 +1,9 @@ -USAGE: - myapp [OPTIONS] <COMMAND> - -OPTIONS: - -h, --help Prints help information - -v, --version Prints version information - -COMMANDS: - dog <AGE> The dog command +USAGE: + myapp [OPTIONS] <COMMAND> + +OPTIONS: + -h, --help Prints help information + +COMMANDS: + dog <AGE> The dog command horse The horse command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Twelve.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Twelve.Output.verified.txt index 8924b5555..82ba4675d 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Twelve.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Children_Twelve.Output.verified.txt @@ -1,24 +1,23 @@ -USAGE: - myapp [OPTIONS] <COMMAND> - -EXAMPLES: - myapp dog --name Rufus --age 12 --good-boy - myapp dog --name Luna - myapp dog --name Charlie - myapp dog --name Bella - myapp dog --name Daisy - myapp dog --name Milo - myapp horse --name Brutus - myapp horse --name Sugar --IsAlive false - myapp horse --name Cash - myapp horse --name Dakota - myapp horse --name Cisco - myapp horse --name Spirit - -OPTIONS: - -h, --help Prints help information - -v, --version Prints version information - -COMMANDS: - dog <AGE> The dog command +USAGE: + myapp [OPTIONS] <COMMAND> + +EXAMPLES: + myapp dog --name Rufus --age 12 --good-boy + myapp dog --name Luna + myapp dog --name Charlie + myapp dog --name Bella + myapp dog --name Daisy + myapp dog --name Milo + myapp horse --name Brutus + myapp horse --name Sugar --IsAlive false + myapp horse --name Cash + myapp horse --name Dakota + myapp horse --name Cisco + myapp horse --name Spirit + +OPTIONS: + -h, --help Prints help information + +COMMANDS: + dog <AGE> The dog command horse The horse command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs.Output.verified.txt index 8b753619b..088dd1b82 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs.Output.verified.txt @@ -1,4 +1,4 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> EXAMPLES: @@ -9,8 +9,7 @@ EXAMPLES: myapp animal dog --name Daisy OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: animal The animal command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Eight.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Eight.Output.verified.txt index 63bded9a9..e236c9b54 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Eight.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Eight.Output.verified.txt @@ -12,8 +12,7 @@ EXAMPLES: myapp animal horse --name Sugar --IsAlive false OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: animal The animal command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_None.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_None.Output.verified.txt index 53228a04c..75de3a148 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_None.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_None.Output.verified.txt @@ -1,9 +1,8 @@ -USAGE: +USAGE: myapp [OPTIONS] <COMMAND> OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: animal The animal command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Twelve.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Twelve.Output.verified.txt index 07178cbc7..b6b89b68a 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Twelve.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Root_Examples_Leafs_Twelve.Output.verified.txt @@ -16,8 +16,7 @@ EXAMPLES: myapp animal horse --name Spirit OPTIONS: - -h, --help Prints help information - -v, --version Prints version information + -h, --help Prints help information COMMANDS: animal The animal command \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Help/Version.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Help/Version.Output.verified.txt new file mode 100644 index 000000000..a07a26663 --- /dev/null +++ b/test/Spectre.Console.Cli.Tests/Expectations/Help/Version.Output.verified.txt @@ -0,0 +1,13 @@ +USAGE: + myapp <FOO> <BAR> <BAZ> <CORGI> [QUX] [OPTIONS] + +ARGUMENTS: + <FOO> + <BAR> + <BAZ> + <CORGI> + [QUX] + +OPTIONS: + -h, --help Prints help information + -v, --version Prints version information \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs index 3c2b8ca8d..9ce30cc24 100644 --- a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs +++ b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Help.cs @@ -950,6 +950,45 @@ public Task Should_List_Arguments_In_Correct_Order() return Verifier.Verify(result.Output); } + [Fact] + [Expectation("NoVersion")] + public Task Should_Not_Include_Application_Version_If_Not_Set() + { + // Given + var fixture = new CommandAppTester(); + fixture.SetDefaultCommand<GenericCommand<ArgumentOrderSettings>>(); + fixture.Configure(config => + { + config.SetApplicationName("myapp"); + }); + + // When + var result = fixture.Run("--help"); + + // Then + return Verifier.Verify(result.Output); + } + + [Fact] + [Expectation("Version")] + public Task Should_Include_Application_Version_If_Set() + { + // Given + var fixture = new CommandAppTester(); + fixture.SetDefaultCommand<GenericCommand<ArgumentOrderSettings>>(); + fixture.Configure(config => + { + config.SetApplicationName("myapp"); + config.SetApplicationVersion("0.49.1"); + }); + + // When + var result = fixture.Run("--help"); + + // Then + return Verifier.Verify(result.Output); + } + [Fact] [Expectation("Hidden_Command_Options")] public Task Should_Not_Show_Hidden_Command_Options() diff --git a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Version.cs b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Version.cs index e9e38dc2f..e0a48ee26 100644 --- a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Version.cs +++ b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Version.cs @@ -34,6 +34,24 @@ public void Should_Output_Application_Version_To_The_Console_With_No_Command() result.Output.ShouldBe("1.0"); } + [Fact] + public void Should_Not_Display_Version_If_Not_Specified() + { + // Given + var fixture = new CommandAppTester(); + fixture.Configure(configurator => + { + configurator.AddCommand<EmptyCommand>("empty"); + }); + + // When + var result = fixture.Run("--version"); + + // Then + result.ExitCode.ShouldNotBe(0); + result.Output.ShouldStartWith("Error: Unexpected option 'version'"); + } + [Fact] public void Should_Execute_Command_Not_Output_Application_Version_To_The_Console() { @@ -42,7 +60,6 @@ public void Should_Execute_Command_Not_Output_Application_Version_To_The_Console fixture.Configure(configurator => { configurator.SetApplicationVersion("1.0"); - configurator.AddCommand<EmptyCommand>("empty"); }); @@ -81,7 +98,6 @@ public void Should_Output_Application_Version_To_The_Console_With_Branch_Default fixture.Configure(configurator => { configurator.SetApplicationVersion("1.0"); - configurator.AddBranch<EmptyCommandSettings>("branch", branch => { branch.SetDefaultCommand<EmptyCommand>();
Built-in parameter `--version` conflicts with existing one **Information** - OS: `Windows` - Version: `Spectre.Console.Cli` v0.49.0 - Terminal: `Windows Terminal / Oh My Posh` **Describe the bug** Recent `Spectre.Console.Cli` versions fixed the issue with the new built-in `--version` parameter when _running_ the application, but we can still spot this one when using `--help`. My application is using `--version|-v` for a dedicated usage for years, so I don't want to see nor use the new `Prints version information` in the help menu. Is there a way to remove this ? Thanks ! **To Reproduce** You can use: https://github.com/sailro/DependencyPath https://www.nuget.org/packages/DependencyPath#readme-body-tab with the following command `dependency-path --help` **Expected behavior** I don't want to see a conflicting `--version` parameter with my own. **Screenshots** ![image](https://github.com/spectreconsole/spectre.console/assets/638167/f01602c9-a482-47f3-8a04-0393c677950d) **Additional context** cc @FrankRay78 unfortunately, this simple little feature seems to be causing so many problems since its introduction. Thanks ! --- Please upvote :+1: this issue if you are interested in it.
That’s unfortunate. We should make the ʼ-—versionʼ option completely opt-in and ensure it’s easy to override the behaviour if wanted. I’m not super familiar with the changes that went into this specific addition, but I will take a look tonight and see if we can’t push a 0.49.1 version out that fixes this. Thank you @patriksvensson , yes I fully agree. Making this `opt-in` would be great. No risk to break existing applications.
2024-04-25T17:54:55Z
0.1
['Spectre.Console.Tests.Unit.Cli.CommandAppTests+Help.Should_Not_Include_Application_Version_If_Not_Set', 'Spectre.Console.Tests.Unit.Cli.CommandAppTests+Help.Should_Include_Application_Version_If_Set', 'Spectre.Console.Tests.Unit.Cli.CommandAppTests+Version.Should_Not_Display_Version_If_Not_Specified']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1513
eb38f76a6a988acbda3c955a8f6b72083a622bfb
diff --git a/src/Spectre.Console/Widgets/Table/TableRenderer.cs b/src/Spectre.Console/Widgets/Table/TableRenderer.cs index 23bff61cd..0d1716685 100644 --- a/src/Spectre.Console/Widgets/Table/TableRenderer.cs +++ b/src/Spectre.Console/Widgets/Table/TableRenderer.cs @@ -150,9 +150,9 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum result.Add(Segment.LineBreak); } - // Show row separator? + // Show row separator, if headers are hidden show separator after the first row if (context.Border.SupportsRowSeparator && context.ShowRowSeparators - && !isFirstRow && !isLastRow) + && (!isFirstRow || (isFirstRow && !context.ShowHeaders)) && !isLastRow) { var hasVisibleFootes = context is { ShowFooters: true, HasFooters: true }; var isNextLastLine = index == context.Rows.Count - 2;
diff --git a/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators_No_Header.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators_No_Header.Output.verified.txt new file mode 100644 index 000000000..e296413d0 --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators_No_Header.Output.verified.txt @@ -0,0 +1,7 @@ +┌────────┬────────┐ +│ Qux │ Corgi │ +├────────┼────────┤ +│ Waldo │ Grault │ +├────────┼────────┤ +│ Garply │ Fred │ +└────────┴────────┘ diff --git a/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs b/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs index 9df303846..18379bdcd 100644 --- a/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs +++ b/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs @@ -159,6 +159,29 @@ public Task Should_Render_Table_With_Row_Separators_Correctly() return Verifier.Verify(console.Output); } + [Fact] + [Expectation("Render_Row_Separators_No_Header")] + public Task Should_Render_Table_With_Row_Separators_No_Header_Correctly() + { + // Given + var console = new TestConsole(); + var table = new Table(); + + table.ShowRowSeparators(); + table.HideHeaders(); + + table.AddColumns("Foo", "Bar"); + table.AddRow("Qux", "Corgi"); + table.AddRow("Waldo", "Grault"); + table.AddRow("Garply", "Fred"); + + // When + console.Write(table); + + // Then + return Verifier.Verify(console.Output); + } + [Fact] [Expectation("Render_EA_Character")] public Task Should_Render_Table_With_EA_Character_Correctly()
Table line separators not showing for the first line when table headers are hidden **Information** - OS: Windows 11 23H2 (OS Build 22631.2506) - Version: Spectre.Console 0.48.0 - Terminal: Windows Terminal 1.19.3172.0 **Describe the bug** When table headers are hidden, the first row separator is not drawn. **To Reproduce** ```csharp var table = new Table(); table.AddColumn("First"); table.AddColumn("Second"); table.AddRow("1", "2"); table.AddRow("3", "4"); table.AddRow("5", "6"); table.ShowRowSeparators = true; table.HideHeaders(); AnsiConsole.Write(table); ``` **Expected behavior** The first row separator should be visible even if table headers are hidden **Screenshots** ![image](https://github.com/spectreconsole/spectre.console/assets/8770486/3f81a05b-4716-4351-92cc-b9735d863ef0)
null
2024-04-13T15:28:08Z
0.1
['Spectre.Console.Tests.Unit.TableTests.Should_Render_Table_With_Row_Separators_No_Header_Correctly']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1504
1a3249cdaea9efa06c25d5e55e4bb53e2a65bedc
diff --git a/src/Spectre.Console/Live/LiveRenderable.cs b/src/Spectre.Console/Live/LiveRenderable.cs index a681d2405..40107f9cd 100644 --- a/src/Spectre.Console/Live/LiveRenderable.cs +++ b/src/Spectre.Console/Live/LiveRenderable.cs @@ -49,7 +49,7 @@ public IRenderable PositionCursor() } var linesToMoveUp = _shape.Value.Height - 1; - return new ControlCode("\r" + (EL(2) + CUU(1)).Repeat(linesToMoveUp)); + return new ControlCode("\r" + CUU(linesToMoveUp)); } }
diff --git a/test/Spectre.Console.Tests/Expectations/Live/Status/Render.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Live/Status/Render.Output.verified.txt index cd5fed942..debe2399d 100644 --- a/test/Spectre.Console.Tests/Expectations/Live/Status/Render.Output.verified.txt +++ b/test/Spectre.Console.Tests/Expectations/Live/Status/Render.Output.verified.txt @@ -1,10 +1,10 @@ [?25l * foo - + - bar - + * baz [?25h \ No newline at end of file diff --git a/test/Spectre.Console.Tests/Expectations/Live/Status/WriteLineOverflow.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Live/Status/WriteLineOverflow.Output.verified.txt deleted file mode 100644 index d3647bb50..000000000 --- a/test/Spectre.Console.Tests/Expectations/Live/Status/WriteLineOverflow.Output.verified.txt +++ /dev/null @@ -1,12 +0,0 @@ -[?25l -⣷ long text that should not interfere writeline text - -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxx - -⣷ long text that should not interfere writeline text - - -⣷ long text that should not interfere writeline text - -[?25h \ No newline at end of file diff --git a/test/Spectre.Console.Tests/Unit/Live/StatusTests.cs b/test/Spectre.Console.Tests/Unit/Live/StatusTests.cs index b80c5d0d1..a9510ad89 100644 --- a/test/Spectre.Console.Tests/Unit/Live/StatusTests.cs +++ b/test/Spectre.Console.Tests/Unit/Live/StatusTests.cs @@ -48,30 +48,4 @@ public Task Should_Render_Status_Correctly() // Then return Verifier.Verify(console.Output); } - - [Fact] - [Expectation("WriteLineOverflow")] - public Task Should_Render_Correctly_When_WriteLine_Exceeds_Console_Width() - { - // Given - var console = new TestConsole() - .Colors(ColorSystem.TrueColor) - .Width(100) - .Interactive() - .EmitAnsiSequences(); - var status = new Status(console) - { - AutoRefresh = false, - }; - - // When - status.Start("long text that should not interfere writeline text", ctx => - { - ctx.Refresh(); - console.WriteLine("x".Repeat(console.Profile.Width + 10), new Style(foreground: Color.White)); - }); - - // Then - return Verifier.Verify(console.Output); - } }
Blatant flickering **Information** - OS: Windows 10/11 - Version: 0.48.0 - Terminal: Dos Prompt, Powershell and Windows Terminal **Describe the bug** Displaying a task list with spinners causes the whole task list to flicker. Apparently, see below, this is a regression introduced in 0.48.0 **To Reproduce** The following code exhibits the issue: (tested on .net 6.0 and .net 8.0) ```c# using Spectre.Console; namespace TestConsole { internal static class Program { private static async Task LoopAsync(ProgressTask task) { await Task.Yield(); for (int i = 0; i < 100; i++) { task.Increment(1); await Task.Delay(TimeSpan.FromSeconds(4)).ConfigureAwait(false); } } private static async Task Main() { Console.WriteLine("Flickering Test"); var progress = AnsiConsole.Progress() .AutoRefresh(true) .AutoClear(false) .HideCompleted(false) .Columns( [ new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn(), new RemainingTimeColumn(), new SpinnerColumn(Spinner.Known.Dots), ]); await progress.StartAsync(async x => { var tasks = new List<Task>(); for (int i = 0; i < 10; i++) { var t = x.AddTask($"Task {i}", true, 100); tasks.Add(LoopAsync(t)); } await Task.WhenAll(tasks).ConfigureAwait(false); }).ConfigureAwait(false); } } } ``` **Expected behavior** No flickering, like in 0.47.0 **Screenshots** **0.48.0**: ![Flickering](https://github.com/spectreconsole/spectre.console/assets/5850742/bd26b8a6-0ea0-4905-92d2-52e9186c4e92) **0.47.0**: ![NoFlickering](https://github.com/spectreconsole/spectre.console/assets/5850742/a9efe7e1-0b35-472c-9d2b-d03027633ecc) **Additional context** The "regression" has been introduced in the commit https://github.com/spectreconsole/spectre.console/commit/71a5d830671220e601e4e6ab4d4c352ae0e0a64a The offending line is in src/Spectre.Console/Live/LiveRenderable.cs: ```diff - return new ControlCode("\r" + CUU(linesToMoveUp)); + return new ControlCode("\r" + (EL(2) + CUU(1)).Repeat(linesToMoveUp)); ```
This is also happening for other widget types in `0.48` including up to at least `0.48.1-preview.0.32` in Windows terminal https://github.com/spectreconsole/spectre.console/assets/13159458/f2783bb7-08c5-49cd-a097-4bc06e78bea5 This happens in progress displays without spinners as well. Can confirm what @yenneferofvengerberg posted, rolling back that commit related to long lines smooths things out again. Probably need something a bit more clever than brute forcing a clear on each line each render. I'd almost be inclined to suggest using the `RenderHook` that now exists on `LiveRenderables` as the mechanism for including extra info while a progress is running rather than write line. Gives us a bit more control over the whole process too Is there a PR to roll this back? I considered doing it, but I couldn't figure out how to maintain the correct behavior when the text goes out of screen. If someone can provide me a hint, I would be happy to try Since it's a regression I would say that it's OK with restoring it how it was, and look at finding a solution for it later.
2024-04-01T15:38:29Z
0.1
[]
['Spectre.Console.Tests.Unit.StatusTests.Should_Render_Status_Correctly']
spectreconsole/spectre.console
spectreconsole__spectre-console-1503
43f9ae92adf36dd5cb96add90d74f867690c3ed3
diff --git a/src/Spectre.Console.Cli/Internal/Commands/XmlDocCommand.cs b/src/Spectre.Console.Cli/Internal/Commands/XmlDocCommand.cs index 807251833..7b7592ca8 100644 --- a/src/Spectre.Console.Cli/Internal/Commands/XmlDocCommand.cs +++ b/src/Spectre.Console.Cli/Internal/Commands/XmlDocCommand.cs @@ -84,6 +84,13 @@ private static XmlNode CreateCommandNode(XmlDocument doc, CommandInfo command, b node.SetNullableAttribute("Settings", command.SettingsType?.FullName); + if (!string.IsNullOrWhiteSpace(command.Description)) + { + var descriptionNode = doc.CreateElement("Description"); + descriptionNode.InnerText = command.Description; + node.AppendChild(descriptionNode); + } + // Parameters if (command.Parameters.Count > 0) { @@ -103,6 +110,27 @@ private static XmlNode CreateCommandNode(XmlDocument doc, CommandInfo command, b node.AppendChild(CreateCommandNode(doc, childCommand)); } + // Examples + if (command.Examples.Count > 0) + { + var exampleRootNode = doc.CreateElement("Examples"); + foreach (var example in command.Examples.SelectMany(static x => x)) + { + var exampleNode = CreateExampleNode(doc, example); + exampleRootNode.AppendChild(exampleNode); + } + + node.AppendChild(exampleRootNode); + } + + return node; + } + + private static XmlNode CreateExampleNode(XmlDocument document, string example) + { + var node = document.CreateElement("Example"); + node.SetAttribute("commandLine", example); + return node; }
diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_1.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_1.Output.verified.txt index 998a89b3a..e92f683de 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_1.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_1.Output.verified.txt @@ -21,6 +21,7 @@ </Parameters> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="AGE" Position="0" Required="true" Kind="scalar" ClrType="System.Int32" /> <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> @@ -28,6 +29,7 @@ </Command> <!--HORSE--> <Command Name="horse" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Option Short="d" Long="day" Value="MON|TUE" Required="false" Kind="scalar" ClrType="System.DayOfWeek" /> <Option Short="" Long="directory" Value="NULL" Required="false" Kind="scalar" ClrType="System.IO.DirectoryInfo" /> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_10.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_10.Output.verified.txt new file mode 100644 index 000000000..2c89d04a7 --- /dev/null +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_10.Output.verified.txt @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="utf-8"?> +<Model> + <!--DOG--> + <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> + <Parameters> + <Argument Name="LEGS" Position="0" Required="false" Kind="scalar" ClrType="System.Int32"> + <Description>The number of legs.</Description> + <Validators> + <Validator ClrType="Spectre.Console.Tests.Data.EvenNumberValidatorAttribute" Message="Animals must have an even number of legs." /> + <Validator ClrType="Spectre.Console.Tests.Data.PositiveNumberValidatorAttribute" Message="Number of legs must be greater than 0." /> + </Validators> + </Argument> + <Argument Name="AGE" Position="1" Required="true" Kind="scalar" ClrType="System.Int32" /> + <Option Short="a" Long="alive,not-dead" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean"> + <Description>Indicates whether or not the animal is alive.</Description> + </Option> + <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> + <Option Short="n,p" Long="name,pet-name" Value="VALUE" Required="false" Kind="scalar" ClrType="System.String" /> + </Parameters> + <Examples> + <Example commandLine="dog -g" /> + <Example commandLine="dog --good-boy" /> + </Examples> + </Command> +</Model> \ No newline at end of file diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_2.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_2.Output.verified.txt index 9f3463020..29098b822 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_2.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_2.Output.verified.txt @@ -2,6 +2,7 @@ <Model> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="LEGS" Position="0" Required="false" Kind="scalar" ClrType="System.Int32"> <Description>The number of legs.</Description> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_3.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_3.Output.verified.txt index 6b1f90fba..ffb491802 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_3.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_3.Output.verified.txt @@ -16,6 +16,7 @@ </Parameters> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="AGE" Position="0" Required="true" Kind="scalar" ClrType="System.Int32" /> <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> @@ -24,6 +25,7 @@ </Command> <!--HORSE--> <Command Name="horse" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Option Short="d" Long="day" Value="MON|TUE" Required="false" Kind="scalar" ClrType="System.DayOfWeek" /> <Option Short="" Long="directory" Value="NULL" Required="false" Kind="scalar" ClrType="System.IO.DirectoryInfo" /> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_4.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_4.Output.verified.txt index 594918922..07b9dcd35 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_4.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_4.Output.verified.txt @@ -16,6 +16,7 @@ </Parameters> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="AGE" Position="0" Required="true" Kind="scalar" ClrType="System.Int32" /> <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_6.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_6.Output.verified.txt index 0907636ae..92b2aba93 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_6.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_6.Output.verified.txt @@ -2,6 +2,7 @@ <Model> <!--DEFAULT COMMAND--> <Command Name="__default_command" IsBranch="false" IsDefault="true" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="LEGS" Position="0" Required="false" Kind="scalar" ClrType="System.Int32"> <Description>The number of legs.</Description> @@ -20,6 +21,7 @@ </Command> <!--HORSE--> <Command Name="horse" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Argument Name="LEGS" Position="0" Required="false" Kind="scalar" ClrType="System.Int32"> <Description>The number of legs.</Description> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_7.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_7.Output.verified.txt index 46ae6a82a..69699701d 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_7.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_7.Output.verified.txt @@ -21,6 +21,7 @@ </Parameters> <!--__DEFAULT_COMMAND--> <Command Name="__default_command" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Option Short="d" Long="day" Value="MON|TUE" Required="false" Kind="scalar" ClrType="System.DayOfWeek" /> <Option Short="" Long="directory" Value="NULL" Required="false" Kind="scalar" ClrType="System.IO.DirectoryInfo" /> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_8.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_8.Output.verified.txt index 3f836ae57..5ccfbd01a 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_8.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_8.Output.verified.txt @@ -16,6 +16,7 @@ </Parameters> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="AGE" Position="0" Required="true" Kind="scalar" ClrType="System.Int32" /> <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> @@ -24,6 +25,7 @@ </Command> <!--__DEFAULT_COMMAND--> <Command Name="__default_command" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Option Short="d" Long="day" Value="MON|TUE" Required="false" Kind="scalar" ClrType="System.DayOfWeek" /> <Option Short="" Long="directory" Value="NULL" Required="false" Kind="scalar" ClrType="System.IO.DirectoryInfo" /> diff --git a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_9.Output.verified.txt b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_9.Output.verified.txt index 5549f5dcf..7c2396bb0 100644 --- a/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_9.Output.verified.txt +++ b/test/Spectre.Console.Cli.Tests/Expectations/Xml/Test_9.Output.verified.txt @@ -18,6 +18,7 @@ </Parameters> <!--DOG--> <Command Name="dog" IsBranch="false" ClrType="Spectre.Console.Tests.Data.DogCommand" Settings="Spectre.Console.Tests.Data.DogSettings"> + <Description>The dog command.</Description> <Parameters> <Argument Name="AGE" Position="0" Required="true" Kind="scalar" ClrType="System.Int32" /> <Option Short="g" Long="good-boy" Value="NULL" Required="false" Kind="flag" ClrType="System.Boolean" /> @@ -26,6 +27,7 @@ </Command> <!--__DEFAULT_COMMAND--> <Command Name="__default_command" IsBranch="false" ClrType="Spectre.Console.Tests.Data.HorseCommand" Settings="Spectre.Console.Tests.Data.HorseSettings"> + <Description>The horse command.</Description> <Parameters> <Option Short="d" Long="day" Value="MON|TUE" Required="false" Kind="scalar" ClrType="System.DayOfWeek" /> <Option Short="" Long="directory" Value="NULL" Required="false" Kind="scalar" ClrType="System.IO.DirectoryInfo" /> diff --git a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Xml.cs b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Xml.cs index 1ed1b4152..8a6348b9e 100644 --- a/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Xml.cs +++ b/test/Spectre.Console.Cli.Tests/Unit/CommandAppTests.Xml.cs @@ -110,6 +110,26 @@ public Task Should_Dump_Correct_Model_For_Case_5() return Verifier.Verify(result.Output); } + [Fact] + [Expectation("Test_10")] + public Task Should_Dump_Correct_Model_For_Case_6() + { + // Given + var fixture = new CommandAppTester(); + fixture.Configure(config => + { + config.AddCommand<DogCommand>("dog") + .WithExample("dog -g") + .WithExample("dog --good-boy"); + }); + + // When + var result = fixture.Run(Constants.XmlDocCommand); + + // Then + return Verifier.Verify(result.Output); + } + [Fact] [Expectation("Test_6")] public Task Should_Dump_Correct_Model_For_Model_With_Default_Command()
Export for Documentation I'm currently manually creating the documentation to put on my site for the CLI usage. Which gave me a thought... Would it be possible to do some sort of export of the the documentation. If I have branch commands I have to go into each command and call `-h` to get the output for that command, then I use that to build the documentation on the site. I have no idea how you would solve it nicely, maybe a nuget tool which analysis it and generates a .md file. Feel free to close this is my idea is stupid...
A little hidden gem of Spectre.Console.Cli is that you can export XML structure with a hidden command. Try passing `cli xmldoc` to your application and it should give you the XML structure: <img width="776" alt="image" src="https://user-images.githubusercontent.com/357872/208904802-44228d2a-1dd1-4cf7-b7a2-47d298ddce7f.png"> You can use this XML to generate documentation for your app. Other than lacking Description and Examples, this is awesome! `explain` is really nice for being able to view the branches and check that descriptions and examples have been written. We could add description and examples to the xmldoc output. I don't mind trying to do a PR next week if you can point me in the right direction. @phillip-haydon The command you would want to extend is the `XmlDocCommand` which can be found here: https://github.com/spectreconsole/spectre.console/blob/main/src/Spectre.Console.Cli/Internal/Commands/XmlDocCommand.cs > I don't mind trying to do a PR next week if you can point me in the right direction. Still interested in preparing a PR for this @phillip-haydon? If so, I can make myself available to review with a view to merging. Hey, would still love this, no time at the moment :(.
2024-03-29T19:09:10Z
0.1
['Spectre.Console.Tests.Unit.Cli.CommandAppTests+Xml.Should_Dump_Correct_Model_For_Case_6']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1458
72704529c5ac45401eee0b61ddd6cbaba9baab22
diff --git a/src/Spectre.Console/Extensions/AnsiConsoleExtensions.Input.cs b/src/Spectre.Console/Extensions/AnsiConsoleExtensions.Input.cs index f5299adde..7769e33a5 100644 --- a/src/Spectre.Console/Extensions/AnsiConsoleExtensions.Input.cs +++ b/src/Spectre.Console/Extensions/AnsiConsoleExtensions.Input.cs @@ -53,7 +53,11 @@ internal static async Task<string> ReadLine(this IAnsiConsole console, Style? st if (text.Length > 0) { text = text.Substring(0, text.Length - 1); - console.Write("\b \b"); + + if (mask != null) + { + console.Write("\b \b"); + } } continue;
diff --git a/test/Spectre.Console.Tests/Expectations/Prompts/Text/SecretValueBackspaceNullMask.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Prompts/Text/SecretValueBackspaceNullMask.Output.verified.txt new file mode 100644 index 000000000..473c6d87b --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Prompts/Text/SecretValueBackspaceNullMask.Output.verified.txt @@ -0,0 +1,1 @@ +Favorite fruit? diff --git a/test/Spectre.Console.Tests/Unit/Prompts/TextPromptTests.cs b/test/Spectre.Console.Tests/Unit/Prompts/TextPromptTests.cs index 52d26e7d5..c358b9be3 100644 --- a/test/Spectre.Console.Tests/Unit/Prompts/TextPromptTests.cs +++ b/test/Spectre.Console.Tests/Unit/Prompts/TextPromptTests.cs @@ -248,6 +248,25 @@ public Task Should_Choose_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_ return Verifier.Verify(console.Output); } + [Fact] + [Expectation("SecretValueBackspaceNullMask")] + public Task Should_Not_Erase_Prompt_Text_On_Backspace_If_Prompt_Is_Secret_And_Mask_Is_Null() + { + // Given + var console = new TestConsole(); + console.Input.PushText("Bananas"); + console.Input.PushKey(ConsoleKey.Backspace); + console.Input.PushKey(ConsoleKey.Enter); + + // When + console.Prompt( + new TextPrompt<string>("Favorite fruit?") + .Secret(null)); + + // Then + return Verifier.Verify(console.Output); + } + [Fact] [Expectation("SecretDefaultValueCustomMask")] public Task Should_Choose_Custom_Masked_Default_Value_If_Nothing_Is_Entered_And_Prompt_Is_Secret_And_Mask_Is_Custom()
Prompt text is erased upon backspace when the prompt text is a secret and its mask is null. **Describe the bug** Prompt text is erased upon backspace when the prompt text is a secret and its mask is null. **To Reproduce** Create secret Prompt with a null mask. Show the Prompt. Enter a few characters, then backspace. The prompt text will be deleted. **Expected behavior** Prompt text deletion should stop after the ultimate character of the prompt text.
null
2024-02-12T20:05:19Z
0.1
['Spectre.Console.Tests.Unit.TextPromptTests.Should_Not_Erase_Prompt_Text_On_Backspace_If_Prompt_Is_Secret_And_Mask_Is_Null']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1338
e2a674815dcbe9589cc87723dd6410f64aaff682
diff --git a/src/Spectre.Console/Widgets/Rows.cs b/src/Spectre.Console/Widgets/Rows.cs index 8e3e59576..91c963f03 100644 --- a/src/Spectre.Console/Widgets/Rows.cs +++ b/src/Spectre.Console/Widgets/Rows.cs @@ -41,8 +41,8 @@ protected override Measurement Measure(RenderOptions options, int maxWidth) if (measurements.Length > 0) { return new Measurement( - measurements.Min(c => c.Min), - measurements.Min(c => c.Max)); + measurements.Max(c => c.Min), + measurements.Max(c => c.Max)); } return new Measurement(0, 0);
diff --git a/test/Spectre.Console.Tests/Expectations/Widgets/Rows/GH-1188-Rows.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Widgets/Rows/GH-1188-Rows.Output.verified.txt new file mode 100644 index 000000000..ed5efe628 --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Widgets/Rows/GH-1188-Rows.Output.verified.txt @@ -0,0 +1,5 @@ +┌─────┐ +│ 1 │ +│ 22 │ +│ 333 │ +└─────┘ diff --git a/test/Spectre.Console.Tests/Unit/Widgets/RowsTests.cs b/test/Spectre.Console.Tests/Unit/Widgets/RowsTests.cs index 9d95e64bf..6937d842f 100644 --- a/test/Spectre.Console.Tests/Unit/Widgets/RowsTests.cs +++ b/test/Spectre.Console.Tests/Unit/Widgets/RowsTests.cs @@ -4,6 +4,29 @@ namespace Spectre.Console.Tests.Unit; [ExpectationPath("Widgets/Rows")] public sealed class RowsTests { + [Fact] + [Expectation("GH-1188-Rows")] + [GitHubIssue("https://github.com/spectreconsole/spectre.console/issues/1188")] + public Task Should_Render_Rows_In_Panel_Without_Breaking_Lines() + { + // Given + var console = new TestConsole().Width(60); + var rows = new Rows( + new IRenderable[] + { + new Text("1"), + new Text("22"), + new Text("333"), + }); + var panel = new Panel(rows); + + // When + console.Write(panel); + + // Then + return Verifier.Verify(console.Output); + } + [Fact] [Expectation("Render")] public Task Should_Render_Rows()
Rows sizing is inconsistent **Information** - OS: Windows - Version: 0.46 - Terminal: Powershell, Windows Rider Integrated Terminal **Describe the bug** Sizing of `Panel` is confusing and buggy: - There's no way to make the panel fit its contents. Instead, it expands the full width of the terminal (which looks ugly) - Depending on the content I put in it, the size behavior changes. **To Reproduce** See MCVE: ```cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Spectre.Console; using Spectre.Console.Cli; using Spectre.Console.Rendering; namespace ConsoleApp1; public enum SupportedServices { Radarr, Sonarr } public record MyConfig(string InstanceName, SupportedServices Service); public class ConfigLocalLister : Command<ConfigLocalLister.CliSettings> { public class CliSettings : CommandSettings { } private readonly IAnsiConsole _console; public ConfigLocalLister(IAnsiConsole console) { _console = console; } private void List() { var appDataDir = @"C:\appDataDir"; var tree = new Tree(appDataDir); var configsDict = new Dictionary<string, MyConfig[]> { { "radarr.yml", new[] { new MyConfig("instance1", SupportedServices.Radarr), } }, { "sonarr.yml", new[] { new MyConfig("instance2", SupportedServices.Sonarr), new MyConfig("instance3", SupportedServices.Sonarr), } }, { "both.yml", new[] { new MyConfig("instance4", SupportedServices.Radarr), new MyConfig("instance5", SupportedServices.Radarr), new MyConfig("instance6", SupportedServices.Sonarr), new MyConfig("instance7", SupportedServices.Sonarr), } }, }; foreach (var configPath in configsDict.Keys) { var configs = configsDict[configPath]; var rows = new List<IRenderable>(); BuildInstanceTree(rows, configs, SupportedServices.Radarr); BuildInstanceTree(rows, configs, SupportedServices.Sonarr); if (!rows.Any()) { rows.Add(new Markup("([red]Empty[/])")); } var rowsWidget = new Rows(rows); var panel = new Panel(rowsWidget) .Header(configPath); tree.AddNode(panel); } _console.WriteLine(); _console.Write(tree); } private static void BuildInstanceTree( ICollection<IRenderable> rows, MyConfig[] registry, SupportedServices service) { var configs = registry.Where(x => x.Service == service).ToList(); if (!configs.Any()) { return; } var tree = new Tree(service.ToString()); tree.AddNodes(configs.Select(c => Markup.FromInterpolated($"[blue]{c.InstanceName}[/]"))); if (rows.Any()) { // This causes the size of the panel to adjust to the length of this line rows.Add(new Text("---------------------------")); } rows.Add(tree); } public override int Execute(CommandContext context, CliSettings settings) { List(); return 0; } } public static class Program { public static void Main(string[] args) { var app = new CommandApp(); app.Configure(c => { c.AddCommand<ConfigLocalLister>("list"); }); app.Run(args); } } ``` **Expected behavior** 1. There should be a way to tell the panel to fit its contents 2. The third panel in the tree is sized inconsistently; the inconsistency is the bug but I don't know what the actual expected sizing behavior is. **Screenshots** ![image](https://user-images.githubusercontent.com/1768054/222853351-81183c33-6818-44eb-a56a-09a81037c9f1.png)
null
2023-10-19T06:01:54Z
0.1
['Spectre.Console.Tests.Unit.RowsTests.Should_Render_Rows_In_Panel_Without_Breaking_Lines']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1308
2af3f7faeb0f5b89e48670af1b15619b3693388f
diff --git a/src/Spectre.Console/Widgets/TextPath.cs b/src/Spectre.Console/Widgets/TextPath.cs index db5eafc7e..fafafb7b1 100644 --- a/src/Spectre.Console/Widgets/TextPath.cs +++ b/src/Spectre.Console/Widgets/TextPath.cs @@ -74,7 +74,7 @@ public Measurement Measure(RenderOptions options, int maxWidth) return new Measurement( Math.Min(length, maxWidth), - Math.Max(length, maxWidth)); + Math.Min(length, maxWidth)); } /// <inheritdoc/> @@ -119,9 +119,6 @@ public IEnumerable<Segment> Render(RenderOptions options, int maxWidth) // Align the result Aligner.Align(parts, Justification, maxWidth); - // Insert a line break - parts.Add(Segment.LineBreak); - return parts; } @@ -134,7 +131,7 @@ private string[] Fit(RenderOptions options, int maxWidth) } // Will it fit as is? - if (_parts.Sum(p => Cell.GetCellLength(p)) + (_parts.Length - 1) < maxWidth) + if (_parts.Sum(Cell.GetCellLength) + (_parts.Length - 1) <= maxWidth) { return _parts; } @@ -159,7 +156,7 @@ private string[] Fit(RenderOptions options, int maxWidth) var queueWidth = rootLength // Root (if rooted) + ellipsisLength // Ellipsis - + queue.Sum(p => Cell.GetCellLength(p)) // Middle + + queue.Sum(Cell.GetCellLength) // Middle + Cell.GetCellLength(_parts.Last()) // Last + queue.Count + separatorCount; // Separators
diff --git a/test/Spectre.Console.Tests/Expectations/Widgets/TextPath/GH-1307.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Widgets/TextPath/GH-1307.Output.verified.txt new file mode 100644 index 000000000..06cfb5f27 --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Widgets/TextPath/GH-1307.Output.verified.txt @@ -0,0 +1,3 @@ +┌─────┐ ┌─────┐ +│ Baz │ │ Qux │ +└─────┘ └─────┘ diff --git a/test/Spectre.Console.Tests/Unit/Widgets/TextPathTests.cs b/test/Spectre.Console.Tests/Unit/Widgets/TextPathTests.cs index d7e5513c7..0dda74206 100644 --- a/test/Spectre.Console.Tests/Unit/Widgets/TextPathTests.cs +++ b/test/Spectre.Console.Tests/Unit/Widgets/TextPathTests.cs @@ -1,5 +1,7 @@ namespace Spectre.Console.Tests.Unit; +[UsesVerify] +[ExpectationPath("Widgets/TextPath")] public sealed class TextPathTests { [Theory] @@ -14,8 +16,7 @@ public void Should_Use_Last_Segments_If_Less_Than_Three(int width, string input, console.Write(new TextPath(input)); // Then - console.Output.TrimEnd() - .ShouldBe(expected); + console.Output.ShouldBe(expected); } [Theory] @@ -31,8 +32,7 @@ public void Should_Render_Full_Path_If_Possible(string input, string expected) console.Write(new TextPath(input)); // Then - console.Output.TrimEnd() - .ShouldBe(expected); + console.Output.ShouldBe(expected); } [Theory] @@ -48,53 +48,50 @@ public void Should_Pop_Segments_From_Left(int width, string input, string expect console.Write(new TextPath(input)); // Then - console.Output.TrimEnd() - .ShouldBe(expected); + console.Output.ShouldBe(expected); } - [Theory] - [InlineData("C:/My documents/Bar/Baz.txt")] - [InlineData("/My documents/Bar/Baz.txt")] - [InlineData("My documents/Bar/Baz.txt")] - [InlineData("Bar/Baz.txt")] - [InlineData("Baz.txt")] - public void Should_Insert_Line_Break_At_End_Of_Path(string input) + [Fact] + public void Should_Right_Align_Correctly() { // Given - var console = new TestConsole().Width(80); + var console = new TestConsole().Width(40); // When - console.Write(new TextPath(input)); + console.Write(new TextPath("C:/My documents/Bar/Baz.txt").RightJustified()); // Then - console.Output.ShouldEndWith("\n"); + console.Output.ShouldBe(" C:/My documents/Bar/Baz.txt"); } [Fact] - public void Should_Right_Align_Correctly() + public void Should_Center_Align_Correctly() { // Given var console = new TestConsole().Width(40); // When - console.Write(new TextPath("C:/My documents/Bar/Baz.txt").RightJustified()); + console.Write(new TextPath("C:/My documents/Bar/Baz.txt").Centered()); // Then - console.Output.TrimEnd('\n') - .ShouldBe(" C:/My documents/Bar/Baz.txt"); + console.Output.ShouldBe(" C:/My documents/Bar/Baz.txt "); } [Fact] - public void Should_Center_Align_Correctly() + [Expectation("GH-1307")] + [GitHubIssue("https://github.com/spectreconsole/spectre.console/issues/1307")] + public Task Should_Behave_As_Expected_When_Rendering_Inside_Panel_Columns() { // Given var console = new TestConsole().Width(40); // When - console.Write(new TextPath("C:/My documents/Bar/Baz.txt").Centered()); + console.Write( + new Columns( + new Panel(new Text("Baz")), + new Panel(new TextPath("Qux")))); // Then - console.Output.TrimEnd('\n') - .ShouldBe(" C:/My documents/Bar/Baz.txt "); + return Verifier.Verify(console.Output); } } diff --git a/test/Spectre.Console.Tests/Utilities/GitHubIssueAttribute.cs b/test/Spectre.Console.Tests/Utilities/GitHubIssueAttribute.cs new file mode 100644 index 000000000..d7d30a7c6 --- /dev/null +++ b/test/Spectre.Console.Tests/Utilities/GitHubIssueAttribute.cs @@ -0,0 +1,12 @@ +namespace Spectre.Console.Tests; + +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] +public sealed class GitHubIssueAttribute : Attribute +{ + public string Url { get; } + + public GitHubIssueAttribute(string url) + { + Url = url; + } +} \ No newline at end of file
TextPath behaves strange together with columns **Information** - OS: Windows - Version: 0.47.0 - Terminal: Windows Terminal **Describe the bug** TextPath seems to add a new line and/or being greedy about the max size. **To Reproduce** ```csharp // Works as expected AnsiConsole.Write( new Columns( new Panel(new Text("Foo")), new Panel(new Text("Bar")) )); // Does not work as expected AnsiConsole.Write( new Columns( new Panel(new Text("Baz")), new Panel(new TextPath("Qux")) ).Collapse()); ``` **Expected behavior** The bottom example in the reproduction should look like the top one. **Screenshots** <img width="667" alt="image" src="https://github.com/spectreconsole/spectre.console/assets/357872/3cfaa951-c0c1-4405-bfd2-7fa35344326d">
null
2023-09-17T22:08:56Z
0.1
['Spectre.Console.Tests.Unit.TextPathTests.Should_Behave_As_Expected_When_Rendering_Inside_Panel_Columns']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1304
037e109699f1e4465ffa112d1a5f19c9ad5d2233
diff --git a/examples/Console/Borders/Program.cs b/examples/Console/Borders/Program.cs index 0dca10135..2b755ae82 100644 --- a/examples/Console/Borders/Program.cs +++ b/examples/Console/Borders/Program.cs @@ -20,21 +20,22 @@ private static void PanelBorders() { static IRenderable CreatePanel(string name, BoxBorder border) { - return new Panel($"This is a panel with\nthe [yellow]{name}[/] border.") - .Header($" [blue]{name}[/] ", Justify.Center) - .Border(border) - .BorderStyle(Style.Parse("grey")); + return + new Panel($"This is a panel with\nthe [yellow]{name}[/] border.") + .Header($" [blue]{name}[/] ", Justify.Center) + .Border(border) + .BorderStyle(Style.Parse("grey")); } var items = new[] { - CreatePanel("Ascii", BoxBorder.Ascii), - CreatePanel("Square", BoxBorder.Square), - CreatePanel("Rounded", BoxBorder.Rounded), - CreatePanel("Heavy", BoxBorder.Heavy), - CreatePanel("Double", BoxBorder.Double), - CreatePanel("None", BoxBorder.None), - }; + CreatePanel("Ascii", BoxBorder.Ascii), + CreatePanel("Square", BoxBorder.Square), + CreatePanel("Rounded", BoxBorder.Rounded), + CreatePanel("Heavy", BoxBorder.Heavy), + CreatePanel("Double", BoxBorder.Double), + CreatePanel("None", BoxBorder.None), + }; AnsiConsole.Write( new Padder( @@ -47,6 +48,7 @@ private static void TableBorders() static IRenderable CreateTable(string name, TableBorder border) { var table = new Table().Border(border); + table.ShowRowSeparators(); table.AddColumn("[yellow]Header 1[/]", c => c.Footer("[grey]Footer 1[/]")); table.AddColumn("[yellow]Header 2[/]", col => col.Footer("[grey]Footer 2[/]").RightAligned()); table.AddRow("Cell", "Cell"); @@ -54,29 +56,23 @@ static IRenderable CreateTable(string name, TableBorder border) return new Panel(table) .Header($" [blue]{name}[/] ", Justify.Center) + .PadBottom(1) .NoBorder(); } var items = new[] { - CreateTable("Ascii", TableBorder.Ascii), - CreateTable("Ascii2", TableBorder.Ascii2), - CreateTable("AsciiDoubleHead", TableBorder.AsciiDoubleHead), - CreateTable("Horizontal", TableBorder.Horizontal), - CreateTable("Simple", TableBorder.Simple), - CreateTable("SimpleHeavy", TableBorder.SimpleHeavy), - CreateTable("Minimal", TableBorder.Minimal), - CreateTable("MinimalHeavyHead", TableBorder.MinimalHeavyHead), - CreateTable("MinimalDoubleHead", TableBorder.MinimalDoubleHead), - CreateTable("Square", TableBorder.Square), - CreateTable("Rounded", TableBorder.Rounded), - CreateTable("Heavy", TableBorder.Heavy), - CreateTable("HeavyEdge", TableBorder.HeavyEdge), - CreateTable("HeavyHead", TableBorder.HeavyHead), - CreateTable("Double", TableBorder.Double), - CreateTable("DoubleEdge", TableBorder.DoubleEdge), - CreateTable("Markdown", TableBorder.Markdown), - }; + CreateTable("Ascii", TableBorder.Ascii), CreateTable("Ascii2", TableBorder.Ascii2), + CreateTable("AsciiDoubleHead", TableBorder.AsciiDoubleHead), + CreateTable("Horizontal", TableBorder.Horizontal), CreateTable("Simple", TableBorder.Simple), + CreateTable("SimpleHeavy", TableBorder.SimpleHeavy), CreateTable("Minimal", TableBorder.Minimal), + CreateTable("MinimalHeavyHead", TableBorder.MinimalHeavyHead), + CreateTable("MinimalDoubleHead", TableBorder.MinimalDoubleHead), + CreateTable("Square", TableBorder.Square), CreateTable("Rounded", TableBorder.Rounded), + CreateTable("Heavy", TableBorder.Heavy), CreateTable("HeavyEdge", TableBorder.HeavyEdge), + CreateTable("HeavyHead", TableBorder.HeavyHead), CreateTable("Double", TableBorder.Double), + CreateTable("DoubleEdge", TableBorder.DoubleEdge), CreateTable("Markdown", TableBorder.Markdown), + }; AnsiConsole.Write(new Columns(items).Collapse()); } @@ -87,4 +83,4 @@ private static void HorizontalRule(string title) AnsiConsole.Write(new Rule($"[white bold]{title}[/]").RuleStyle("grey").LeftJustified()); AnsiConsole.WriteLine(); } -} +} \ No newline at end of file diff --git a/src/Spectre.Console/Extensions/TableExtensions.cs b/src/Spectre.Console/Extensions/TableExtensions.cs index e232e64bc..ddb23315a 100644 --- a/src/Spectre.Console/Extensions/TableExtensions.cs +++ b/src/Spectre.Console/Extensions/TableExtensions.cs @@ -334,6 +334,38 @@ public static Table HideHeaders(this Table table) return table; } + /// <summary> + /// Shows row separators. + /// </summary> + /// <param name="table">The table.</param> + /// <returns>The same instance so that multiple calls can be chained.</returns> + public static Table ShowRowSeparators(this Table table) + { + if (table is null) + { + throw new ArgumentNullException(nameof(table)); + } + + table.ShowRowSeparators = true; + return table; + } + + /// <summary> + /// Hides row separators. + /// </summary> + /// <param name="table">The table.</param> + /// <returns>The same instance so that multiple calls can be chained.</returns> + public static Table HideRowSeparators(this Table table) + { + if (table is null) + { + throw new ArgumentNullException(nameof(table)); + } + + table.ShowRowSeparators = false; + return table; + } + /// <summary> /// Shows table footers. /// </summary> diff --git a/src/Spectre.Console/Rendering/Borders/TableBorderPart.cs b/src/Spectre.Console/Rendering/Borders/TableBorderPart.cs index 2359266a8..dbf64af66 100644 --- a/src/Spectre.Console/Rendering/Borders/TableBorderPart.cs +++ b/src/Spectre.Console/Rendering/Borders/TableBorderPart.cs @@ -114,4 +114,24 @@ public enum TableBorderPart /// The bottom right part of a footer. /// </summary> FooterBottomRight, + + /// <summary> + /// The left part of a row. + /// </summary> + RowLeft, + + /// <summary> + /// The center part of a row. + /// </summary> + RowCenter, + + /// <summary> + /// The separator part of a row. + /// </summary> + RowSeparator, + + /// <summary> + /// The right part of a row. + /// </summary> + RowRight, } \ No newline at end of file diff --git a/src/Spectre.Console/Rendering/Borders/Tables/Ascii2TableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/Ascii2TableBorder.cs index 7bd17d60e..0cd6122ce 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/Ascii2TableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/Ascii2TableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "-", TableBorderPart.FooterBottomSeparator => "+", TableBorderPart.FooterBottomRight => "+", + TableBorderPart.RowLeft => "|", + TableBorderPart.RowCenter => "-", + TableBorderPart.RowSeparator => "+", + TableBorderPart.RowRight => "|", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/AsciiDoubleHeadTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/AsciiDoubleHeadTableBorder.cs index f5f2bad6d..33c78ce88 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/AsciiDoubleHeadTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/AsciiDoubleHeadTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "-", TableBorderPart.FooterBottomSeparator => "+", TableBorderPart.FooterBottomRight => "+", + TableBorderPart.RowLeft => "|", + TableBorderPart.RowCenter => "-", + TableBorderPart.RowSeparator => "+", + TableBorderPart.RowRight => "|", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/AsciiTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/AsciiTableBorder.cs index 7f4f743b5..903665c5e 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/AsciiTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/AsciiTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "-", TableBorderPart.FooterBottomSeparator => "-", TableBorderPart.FooterBottomRight => "+", + TableBorderPart.RowLeft => "|", + TableBorderPart.RowCenter => "-", + TableBorderPart.RowSeparator => "+", + TableBorderPart.RowRight => "|", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/DoubleEdgeTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/DoubleEdgeTableBorder.cs index ab1362127..6f756ff74 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/DoubleEdgeTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/DoubleEdgeTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "═", TableBorderPart.FooterBottomSeparator => "╧", TableBorderPart.FooterBottomRight => "╝", + TableBorderPart.RowLeft => "╟", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => "╢", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/DoubleTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/DoubleTableBorder.cs index b5eca04cd..40b2f6b72 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/DoubleTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/DoubleTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "═", TableBorderPart.FooterBottomSeparator => "╩", TableBorderPart.FooterBottomRight => "╝", + TableBorderPart.RowLeft => "╠", + TableBorderPart.RowCenter => "═", + TableBorderPart.RowSeparator => "╬", + TableBorderPart.RowRight => "╣", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/HeavyEdgeTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/HeavyEdgeTableBorder.cs index f5728be27..31cadcab4 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/HeavyEdgeTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/HeavyEdgeTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "━", TableBorderPart.FooterBottomSeparator => "┷", TableBorderPart.FooterBottomRight => "┛", + TableBorderPart.RowLeft => "┠", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => "┨", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/HeavyHeadTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/HeavyHeadTableBorder.cs index 87f357432..36c71c3e8 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/HeavyHeadTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/HeavyHeadTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "─", TableBorderPart.FooterBottomSeparator => "┴", TableBorderPart.FooterBottomRight => "┘", + TableBorderPart.RowLeft => "├", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => "┤", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/HeavyTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/HeavyTableBorder.cs index 783f742fe..68d3675e5 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/HeavyTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/HeavyTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "━", TableBorderPart.FooterBottomSeparator => "┻", TableBorderPart.FooterBottomRight => "┛", + TableBorderPart.RowLeft => "┣", + TableBorderPart.RowCenter => "━", + TableBorderPart.RowSeparator => "╋", + TableBorderPart.RowRight => "┫", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/HorizontalTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/HorizontalTableBorder.cs index db3021dbf..740f8e5dc 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/HorizontalTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/HorizontalTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "─", TableBorderPart.FooterBottomSeparator => "─", TableBorderPart.FooterBottomRight => "─", + TableBorderPart.RowLeft => "─", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "─", + TableBorderPart.RowRight => "─", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/MarkdownTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/MarkdownTableBorder.cs index f338c3960..fa21f1c88 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/MarkdownTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/MarkdownTableBorder.cs @@ -5,6 +5,9 @@ namespace Spectre.Console.Rendering; /// </summary> public sealed class MarkdownTableBorder : TableBorder { + /// <inheritdoc /> + public override bool SupportsRowSeparator => false; + /// <inheritdoc/> public override string GetPart(TableBorderPart part) { @@ -32,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => " ", + TableBorderPart.RowCenter => " ", + TableBorderPart.RowSeparator => " ", + TableBorderPart.RowRight => " ", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/MinimalDoubleHeadTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/MinimalDoubleHeadTableBorder.cs index 5fd281e90..8d58d8f69 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/MinimalDoubleHeadTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/MinimalDoubleHeadTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => " ", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => " ", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/MinimalHeavyHeadTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/MinimalHeavyHeadTableBorder.cs index 7c8cffec5..4d9fd6d0f 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/MinimalHeavyHeadTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/MinimalHeavyHeadTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => " ", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => " ", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/MinimalTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/MinimalTableBorder.cs index 06d47aa32..54d1d1740 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/MinimalTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/MinimalTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => " ", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => " ", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/NoTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/NoTableBorder.cs index c251d9bb9..26ed655e9 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/NoTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/NoTableBorder.cs @@ -8,6 +8,9 @@ public sealed class NoTableBorder : TableBorder /// <inheritdoc/> public override bool Visible => false; + /// <inheritdoc /> + public override bool SupportsRowSeparator => false; + /// <inheritdoc/> public override string GetPart(TableBorderPart part) { diff --git a/src/Spectre.Console/Rendering/Borders/Tables/RoundedTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/RoundedTableBorder.cs index 9d02c68fb..5db78ad6f 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/RoundedTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/RoundedTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "─", TableBorderPart.FooterBottomSeparator => "┴", TableBorderPart.FooterBottomRight => "╯", + TableBorderPart.RowLeft => "├", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => "┤", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/SimpleHeavyTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/SimpleHeavyTableBorder.cs index d8ae95786..1a703ab70 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/SimpleHeavyTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/SimpleHeavyTableBorder.cs @@ -35,6 +35,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => "─", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "─", + TableBorderPart.RowRight => "─", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/SimpleTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/SimpleTableBorder.cs index 30fa56348..0bc8531fc 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/SimpleTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/SimpleTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => " ", TableBorderPart.FooterBottomSeparator => " ", TableBorderPart.FooterBottomRight => " ", + TableBorderPart.RowLeft => "─", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "─", + TableBorderPart.RowRight => "─", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/Borders/Tables/SquareTableBorder.cs b/src/Spectre.Console/Rendering/Borders/Tables/SquareTableBorder.cs index 4e7e73188..e30ce3d52 100644 --- a/src/Spectre.Console/Rendering/Borders/Tables/SquareTableBorder.cs +++ b/src/Spectre.Console/Rendering/Borders/Tables/SquareTableBorder.cs @@ -32,6 +32,10 @@ public override string GetPart(TableBorderPart part) TableBorderPart.FooterBottom => "─", TableBorderPart.FooterBottomSeparator => "┴", TableBorderPart.FooterBottomRight => "┘", + TableBorderPart.RowLeft => "├", + TableBorderPart.RowCenter => "─", + TableBorderPart.RowSeparator => "┼", + TableBorderPart.RowRight => "┤", _ => throw new InvalidOperationException("Unknown border part."), }; } diff --git a/src/Spectre.Console/Rendering/TablePart.cs b/src/Spectre.Console/Rendering/TablePart.cs index 1992252a8..16349678d 100644 --- a/src/Spectre.Console/Rendering/TablePart.cs +++ b/src/Spectre.Console/Rendering/TablePart.cs @@ -15,6 +15,11 @@ public enum TablePart /// </summary> HeaderSeparator, + /// <summary> + /// The separator between the rows. + /// </summary> + RowSeparator, + /// <summary> /// The separator between the footer and the cells. /// </summary> diff --git a/src/Spectre.Console/Spectre.Console.csproj b/src/Spectre.Console/Spectre.Console.csproj index bf1630c76..fdecc8286 100644 --- a/src/Spectre.Console/Spectre.Console.csproj +++ b/src/Spectre.Console/Spectre.Console.csproj @@ -36,9 +36,6 @@ </PackageReference> </ItemGroup> - <ItemGroup> - <Folder Include="Widgets\Json\" /> - </ItemGroup> <PropertyGroup> <DefineConstants>$(DefineConstants)TRACE;WCWIDTH_VISIBILITY_INTERNAL</DefineConstants> diff --git a/src/Spectre.Console/TableBorder.cs b/src/Spectre.Console/TableBorder.cs index a20654430..a3397133a 100644 --- a/src/Spectre.Console/TableBorder.cs +++ b/src/Spectre.Console/TableBorder.cs @@ -13,7 +13,12 @@ public abstract partial class TableBorder /// <summary> /// Gets the safe border for this border or <c>null</c> if none exist. /// </summary> - public virtual TableBorder? SafeBorder { get; } + public virtual TableBorder? SafeBorder { get; } = null; + + /// <summary> + /// Gets a value indicating whether the border supports row separators or not. + /// </summary> + public virtual bool SupportsRowSeparator { get; } = true; /// <summary> /// Gets the string representation of a specified table border part. @@ -81,6 +86,11 @@ public virtual string GetColumnRow(TablePart part, IReadOnlyList<int> widths, IR (GetPart(TableBorderPart.HeaderBottomLeft), GetPart(TableBorderPart.HeaderBottom), GetPart(TableBorderPart.HeaderBottomSeparator), GetPart(TableBorderPart.HeaderBottomRight)), + // Separator between header and cells + TablePart.RowSeparator => + (GetPart(TableBorderPart.RowLeft), GetPart(TableBorderPart.RowCenter), + GetPart(TableBorderPart.RowSeparator), GetPart(TableBorderPart.RowRight)), + // Separator between footer and cells TablePart.FooterSeparator => (GetPart(TableBorderPart.FooterTopLeft), GetPart(TableBorderPart.FooterTop), diff --git a/src/Spectre.Console/Widgets/Panel.cs b/src/Spectre.Console/Widgets/Panel.cs index 05d41d459..7a34d9592 100644 --- a/src/Spectre.Console/Widgets/Panel.cs +++ b/src/Spectre.Console/Widgets/Panel.cs @@ -132,6 +132,15 @@ protected override IEnumerable<Segment> Render(RenderOptions options, int maxWid { AddTopBorder(result, options, border, borderStyle, panelWidth); } + else + { + // Not showing border, but we have a header text? + // Use a invisible border to draw the top border + if (Header?.Text != null) + { + AddTopBorder(result, options, BoxBorder.None, borderStyle, panelWidth); + } + } // Split the child segments into lines. var childSegments = ((IRenderable)child).Render(options with { Height = height }, innerWidth); diff --git a/src/Spectre.Console/Widgets/Table/Table.cs b/src/Spectre.Console/Widgets/Table/Table.cs index c0d83e186..345e83d7a 100644 --- a/src/Spectre.Console/Widgets/Table/Table.cs +++ b/src/Spectre.Console/Widgets/Table/Table.cs @@ -31,6 +31,11 @@ public sealed class Table : Renderable, IHasTableBorder, IExpandable, IAlignable /// </summary> public bool ShowHeaders { get; set; } = true; + /// <summary> + /// Gets or sets a value indicating whether or not row separators should be shown. + /// </summary> + public bool ShowRowSeparators { get; set; } + /// <summary> /// Gets or sets a value indicating whether or not table footers should be shown. /// </summary> diff --git a/src/Spectre.Console/Widgets/Table/TableRenderer.cs b/src/Spectre.Console/Widgets/Table/TableRenderer.cs index d27326e78..23bff61cd 100644 --- a/src/Spectre.Console/Widgets/Table/TableRenderer.cs +++ b/src/Spectre.Console/Widgets/Table/TableRenderer.cs @@ -36,7 +36,9 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum // Show top of header? if (isFirstRow && context.ShowBorder) { - var separator = Aligner.Align(context.Border.GetColumnRow(TablePart.Top, columnWidths, context.Columns), context.Alignment, context.MaxWidth); + var separator = Aligner.Align( + context.Border.GetColumnRow(TablePart.Top, columnWidths, context.Columns), + context.Alignment, context.MaxWidth); result.Add(new Segment(separator, context.BorderStyle)); result.Add(Segment.LineBreak); } @@ -66,7 +68,9 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum if (isFirstCell && context.ShowBorder) { // Show left column edge - var part = isFirstRow && context.ShowHeaders ? TableBorderPart.HeaderLeft : TableBorderPart.CellLeft; + var part = isFirstRow && context.ShowHeaders + ? TableBorderPart.HeaderLeft + : TableBorderPart.CellLeft; rowResult.Add(new Segment(context.Border.GetPart(part), context.BorderStyle)); } @@ -91,7 +95,8 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum } // Pad column on the right side - if (context.ShowBorder || (context.HideBorder && !isLastCell) || (context.HideBorder && isLastCell && context.IsGrid && context.PadRightCell)) + if (context.ShowBorder || (context.HideBorder && !isLastCell) || + (context.HideBorder && isLastCell && context.IsGrid && context.PadRightCell)) { var rightPadding = context.Columns[cellIndex].Padding.GetRightSafe(); if (rightPadding > 0) @@ -103,13 +108,17 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum if (isLastCell && context.ShowBorder) { // Add right column edge - var part = isFirstRow && context.ShowHeaders ? TableBorderPart.HeaderRight : TableBorderPart.CellRight; + var part = isFirstRow && context.ShowHeaders + ? TableBorderPart.HeaderRight + : TableBorderPart.CellRight; rowResult.Add(new Segment(context.Border.GetPart(part), context.BorderStyle)); } else if (context.ShowBorder) { // Add column separator - var part = isFirstRow && context.ShowHeaders ? TableBorderPart.HeaderSeparator : TableBorderPart.CellSeparator; + var part = isFirstRow && context.ShowHeaders + ? TableBorderPart.HeaderSeparator + : TableBorderPart.CellSeparator; rowResult.Add(new Segment(context.Border.GetPart(part), context.BorderStyle)); } } @@ -133,15 +142,40 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum // Show header separator? if (isFirstRow && context.ShowBorder && context.ShowHeaders && context.HasRows) { - var separator = Aligner.Align(context.Border.GetColumnRow(TablePart.HeaderSeparator, columnWidths, context.Columns), context.Alignment, context.MaxWidth); + var separator = + Aligner.Align( + context.Border.GetColumnRow(TablePart.HeaderSeparator, columnWidths, context.Columns), + context.Alignment, context.MaxWidth); result.Add(new Segment(separator, context.BorderStyle)); result.Add(Segment.LineBreak); } + // Show row separator? + if (context.Border.SupportsRowSeparator && context.ShowRowSeparators + && !isFirstRow && !isLastRow) + { + var hasVisibleFootes = context is { ShowFooters: true, HasFooters: true }; + var isNextLastLine = index == context.Rows.Count - 2; + + var isRenderingFooter = hasVisibleFootes && isNextLastLine; + if (!isRenderingFooter) + { + var separator = + Aligner.Align( + context.Border.GetColumnRow(TablePart.RowSeparator, columnWidths, context.Columns), + context.Alignment, context.MaxWidth); + result.Add(new Segment(separator, context.BorderStyle)); + result.Add(Segment.LineBreak); + } + } + // Show bottom of footer? if (isLastRow && context.ShowBorder) { - var separator = Aligner.Align(context.Border.GetColumnRow(TablePart.Bottom, columnWidths, context.Columns), context.Alignment, context.MaxWidth); + var separator = + Aligner.Align( + context.Border.GetColumnRow(TablePart.Bottom, columnWidths, context.Columns), + context.Alignment, context.MaxWidth); result.Add(new Segment(separator, context.BorderStyle)); result.Add(Segment.LineBreak); } @@ -151,7 +185,8 @@ public static List<Segment> Render(TableRendererContext context, List<int> colum return result; } - private static IEnumerable<Segment> RenderAnnotation(TableRendererContext context, TableTitle? header, Style defaultStyle) + private static IEnumerable<Segment> RenderAnnotation(TableRendererContext context, TableTitle? header, + Style defaultStyle) { if (header == null) { diff --git a/src/Spectre.Console/Widgets/Table/TableRendererContext.cs b/src/Spectre.Console/Widgets/Table/TableRendererContext.cs index b54980248..ad9b709a2 100644 --- a/src/Spectre.Console/Widgets/Table/TableRendererContext.cs +++ b/src/Spectre.Console/Widgets/Table/TableRendererContext.cs @@ -10,6 +10,7 @@ internal sealed class TableRendererContext : TableAccessor public TableBorder Border { get; } public Style BorderStyle { get; } public bool ShowBorder { get; } + public bool ShowRowSeparators { get; } public bool HasRows { get; } public bool HasFooters { get; } @@ -47,6 +48,7 @@ public TableRendererContext(Table table, RenderOptions options, IEnumerable<Tabl HasFooters = Rows.Any(column => column.IsFooter); Border = table.Border.GetSafeBorder(!options.Unicode && table.UseSafeBorder); BorderStyle = table.BorderStyle ?? Style.Plain; + ShowRowSeparators = table.ShowRowSeparators; TableWidth = tableWidth; MaxWidth = maxWidth;
diff --git a/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder.Output.verified.txt index 0d3e931ff..a254250d8 100644 --- a/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder.Output.verified.txt +++ b/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder.Output.verified.txt @@ -1,1 +1,1 @@ - Hello World + Hello World diff --git a/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder_With_Header.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder_With_Header.Output.verified.txt new file mode 100644 index 000000000..2ad34aef5 --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Rendering/Borders/Box/NoBorder_With_Header.Output.verified.txt @@ -0,0 +1,2 @@ + Greeting + Hello World diff --git a/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators.Output.verified.txt new file mode 100644 index 000000000..02d8f0d7d --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Widgets/Table/Render_Row_Separators.Output.verified.txt @@ -0,0 +1,7 @@ +┌────────┬────────┬───────┐ +│ Foo │ Bar │ Baz │ +├────────┼────────┼───────┤ +│ Qux │ Corgi │ Waldo │ +├────────┼────────┼───────┤ +│ Grault │ Garply │ Fred │ +└────────┴────────┴───────┘ diff --git a/test/Spectre.Console.Tests/Unit/Rendering/Borders/BoxBorderTests.cs b/test/Spectre.Console.Tests/Unit/Rendering/Borders/BoxBorderTests.cs index f16fe9775..d9643cbf8 100644 --- a/test/Spectre.Console.Tests/Unit/Rendering/Borders/BoxBorderTests.cs +++ b/test/Spectre.Console.Tests/Unit/Rendering/Borders/BoxBorderTests.cs @@ -23,6 +23,22 @@ public void Should_Return_Safe_Border() [Fact] [Expectation("NoBorder")] public Task Should_Render_As_Expected() + { + // Given + var console = new TestConsole(); + var panel = Fixture.GetPanel().NoBorder(); + panel.Header = null; + + // When + console.Write(panel); + + // Then + return Verifier.Verify(console.Output); + } + + [Fact] + [Expectation("NoBorder_With_Header")] + public Task Should_Render_NoBorder_With_Header_As_Expected() { // Given var console = new TestConsole(); diff --git a/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs b/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs index a8fb9082f..8a1ce1d36 100644 --- a/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs +++ b/test/Spectre.Console.Tests/Unit/Widgets/Table/TableTests.cs @@ -142,6 +142,25 @@ public Task Should_Render_Table_Correctly() return Verifier.Verify(console.Output); } + [Fact] + [Expectation("Render_Row_Separators")] + public Task Should_Render_Table_With_Row_Separators_Correctly() + { + // Given + var console = new TestConsole(); + var table = new Table(); + table.ShowRowSeparators(); + table.AddColumns("Foo", "Bar", "Baz"); + table.AddRow("Qux", "Corgi", "Waldo"); + table.AddRow("Grault", "Garply", "Fred"); + + // When + console.Write(table); + + // Then + return Verifier.Verify(console.Output); + } + [Fact] [Expectation("Render_EA_Character")] public Task Should_Render_Table_With_EA_Character_Correctly()
Add option to show separators between rows **Is your feature request related to a problem? Please describe.** It would be nice if there was a way to show separators between table rows. **Additional context** This should be opt-in
null
2023-09-16T15:13:47Z
0.1
['Spectre.Console.Tests.Unit.TableTests.Should_Render_Table_With_Row_Separators_Correctly']
[]
spectreconsole/spectre.console
spectreconsole__spectre-console-1303
037e109699f1e4465ffa112d1a5f19c9ad5d2233
diff --git a/examples/Console/Charts/Program.cs b/examples/Console/Charts/Program.cs index b107f6b24..5aadfa8a0 100644 --- a/examples/Console/Charts/Program.cs +++ b/examples/Console/Charts/Program.cs @@ -23,6 +23,7 @@ public static void Main() .FullSize() .Width(60) .ShowPercentage() + .WithValueColor(Color.Orange1) .AddItem("SCSS", 37, Color.Red) .AddItem("HTML", 28.3, Color.Blue) .AddItem("C#", 22.6, Color.Green) diff --git a/src/Spectre.Console/Extensions/BreakdownChartExtensions.cs b/src/Spectre.Console/Extensions/BreakdownChartExtensions.cs index 5ace7a969..ed3610f49 100644 --- a/src/Spectre.Console/Extensions/BreakdownChartExtensions.cs +++ b/src/Spectre.Console/Extensions/BreakdownChartExtensions.cs @@ -297,4 +297,21 @@ public static BreakdownChart Compact(this BreakdownChart chart, bool compact) chart.Compact = compact; return chart; } + + /// <summary> + /// Sets the <see cref="BreakdownChart.ValueColor"/>. + /// </summary> + /// <param name="chart">The breakdown chart.</param> + /// <param name="color">The <see cref="Color"/> to set.</param> + /// <returns>The same instance so that multiple calls can be chained.</returns> + public static BreakdownChart WithValueColor(this BreakdownChart chart, Color color) + { + if (chart is null) + { + throw new ArgumentNullException(nameof(chart)); + } + + chart.ValueColor = color; + return chart; + } } \ No newline at end of file diff --git a/src/Spectre.Console/Widgets/Charts/BreakdownChart.cs b/src/Spectre.Console/Widgets/Charts/BreakdownChart.cs index 85067c904..7ed9ce824 100644 --- a/src/Spectre.Console/Widgets/Charts/BreakdownChart.cs +++ b/src/Spectre.Console/Widgets/Charts/BreakdownChart.cs @@ -30,6 +30,11 @@ public sealed class BreakdownChart : Renderable, IHasCulture, IExpandable /// </summary> public Func<double, CultureInfo, string>? ValueFormatter { get; set; } + /// <summary> + /// Gets or sets the Color in which the values will be shown. + /// </summary> + public Color ValueColor { get; set; } = Color.Grey; + /// <summary> /// Gets or sets a value indicating whether or not the /// chart and tags should be rendered in compact mode. @@ -94,6 +99,7 @@ protected override IEnumerable<Segment> Render(RenderOptions options, int maxWid Culture = Culture, ShowTagValues = ShowTagValues, ValueFormatter = ValueFormatter, + ValueColor = ValueColor, }); } diff --git a/src/Spectre.Console/Widgets/Charts/BreakdownTags.cs b/src/Spectre.Console/Widgets/Charts/BreakdownTags.cs index a74734555..67a49092d 100644 --- a/src/Spectre.Console/Widgets/Charts/BreakdownTags.cs +++ b/src/Spectre.Console/Widgets/Charts/BreakdownTags.cs @@ -8,6 +8,7 @@ internal sealed class BreakdownTags : Renderable public CultureInfo? Culture { get; set; } public bool ShowTagValues { get; set; } = true; public Func<double, CultureInfo, string>? ValueFormatter { get; set; } + public Color ValueColor { get; set; } = Color.Grey; public BreakdownTags(List<IBreakdownChartItem> data) { @@ -55,8 +56,9 @@ private string FormatValue(IBreakdownChartItem item, CultureInfo culture) if (ShowTagValues) { - return string.Format(culture, "{0} [grey]{1}[/]", + return string.Format(culture, "{0} [{1}]{2}[/]", item.Label.EscapeMarkup(), + ValueColor.ToMarkup(), formatter(item.Value, culture)); }
diff --git a/test/Spectre.Console.Tests/Expectations/Widgets/BreakdownChart/ValueColor.Output.verified.txt b/test/Spectre.Console.Tests/Expectations/Widgets/BreakdownChart/ValueColor.Output.verified.txt new file mode 100644 index 000000000..5b95b8b27 --- /dev/null +++ b/test/Spectre.Console.Tests/Expectations/Widgets/BreakdownChart/ValueColor.Output.verified.txt @@ -0,0 +1,3 @@ +████████████████████████████████████████████████████████████ +■ SCSS 37 ■ HTML 28.3 ■ C# 22.6 ■ JavaScript 6 +■ Ruby 6 ■ Shell 0.1 diff --git a/test/Spectre.Console.Tests/Unit/Widgets/BreakdownChartTests.cs b/test/Spectre.Console.Tests/Unit/Widgets/BreakdownChartTests.cs index ab92efb4c..4fdc7d1ff 100644 --- a/test/Spectre.Console.Tests/Unit/Widgets/BreakdownChartTests.cs +++ b/test/Spectre.Console.Tests/Unit/Widgets/BreakdownChartTests.cs @@ -127,6 +127,21 @@ public async Task Should_Render_Correct_Ansi() await Verifier.Verify(console.Output); } + [Fact] + [Expectation("ValueColor")] + public async Task Should_Render_Correct_ValueColor() + { + // Given + var console = new TestConsole().EmitAnsiSequences(); + var chart = Fixture.GetChart().Width(60).WithValueColor(Color.Red); + + // When + console.Write(chart); + + // Then + await Verifier.Verify(console.Output); + } + public static class Fixture { public static BreakdownChart GetChart()
Grey hard-coded in BreakdownTags **Information** - OS: Windows - Version: 0.43.0 - Terminal: cmd.exe **Describe the bug** I noticed that there is a hard-coded `grey` color inside the breakdown chart tag format: https://github.com/spectreconsole/spectre.console/blob/main/src/Spectre.Console/Widgets/Charts/BreakdownTags.cs#L58 It can be difficult to see on light backgrounds: ![image](https://user-images.githubusercontent.com/578591/148657072-9c257118-ef59-42d4-afff-e99333bdbd83.png) **To Reproduce** Display a breakdown chart on a light or grey background. **Expected behavior** I'd expect this value to either be not colored by default or be configurable. However, I'm guessing now there would be a back-compat concern around changing it, so perhaps the fix is to keep grey the default but expose a way to configure it with a new field on `IBreakdownChartItem`. **Screenshots** See above **Additional context** I'm working on incorporating Spectre.Console into Maoni's realmon tool at https://github.com/Maoni0/realmon/pull/39 and ran into this issue while coming up with a light color theme. Happy to contribute a fix here if there is an acceptable resolution! Thanks for this wonderful library.
null
2023-09-15T18:12:46Z
0.1
['Spectre.Console.Tests.Unit.BreakdownChartTests.Should_Render_Correct_ValueColor']
[]
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2491
41b23b7dc8037cec7c05c0ca0bac0db1e767954b
diff --git a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs index a6d7b37b81..6cb4a983c3 100644 --- a/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs +++ b/src/BenchmarkDotNet/Characteristics/CharacteristicObject.cs @@ -402,6 +402,12 @@ protected CharacteristicObject UnfreezeCopyCore() var newRoot = (CharacteristicObject)Activator.CreateInstance(GetType()); newRoot.ApplyCore(this); + // Preserve the IdCharacteristic of the original object + if (this.HasValue(IdCharacteristic)) + { + newRoot.SetValue(IdCharacteristic, this.GetValue(IdCharacteristic)); + } + return newRoot; } #endregion
diff --git a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs index 896f93925b..64e3889fcf 100644 --- a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs +++ b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs @@ -233,7 +233,7 @@ public void UserCanSpecifyMultipleCoreRunPaths() Assert.Equal(2, jobs.Length); Assert.Single(jobs.Where(job => job.GetToolchain() is CoreRunToolchain toolchain && toolchain.SourceCoreRun.FullName == fakeCoreRunPath_1)); Assert.Single(jobs.Where(job => job.GetToolchain() is CoreRunToolchain toolchain && toolchain.SourceCoreRun.FullName == fakeCoreRunPath_2)); - Assert.Equal(2, jobs.Select(job => job.Id).Distinct().Count()); // each job must have a unique ID + } [Fact] diff --git a/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs b/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs index 96f671e60d..050b84de7c 100644 --- a/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs +++ b/tests/BenchmarkDotNet.Tests/Configs/JobTests.cs @@ -60,11 +60,11 @@ public static void Test01Create() Assert.False(j.Environment.Gc.AllowVeryLargeObjects); Assert.Equal(Platform.AnyCpu, j.Environment.Platform); Assert.Equal(RunStrategy.Throughput, j.Run.RunStrategy); // set by default - Assert.Equal("Default", j.Id); // id reset - Assert.True(j.DisplayInfo == "DefaultJob", "DisplayInfo = " + j.DisplayInfo); - Assert.True(j.ResolvedId == "DefaultJob", "ResolvedId = " + j.ResolvedId); + Assert.Equal("CustomId", j.Id); // id remains after unfreeze + Assert.Equal("CustomId", j.DisplayInfo); + Assert.Equal("CustomId", j.ResolvedId); Assert.Equal(j.ResolvedId, j.FolderInfo); - Assert.Equal("Default", j.Environment.Id); + Assert.Equal("CustomId", j.Environment.Id); // id remains after unfreeze // new job j = new Job(j.Freeze()); @@ -160,7 +160,7 @@ public static void Test02Modify() // 4. Freeze-unfreeze: j = j.Freeze().UnfreezeCopy(); - Assert.Equal("Platform=X86, LaunchCount=1", j.Id); + Assert.Equal("SomeId", j.Id); // id not lost Assert.Equal(Platform.X86, j.Environment.Platform); Assert.Equal(1, j.Run.LaunchCount); @@ -204,15 +204,15 @@ public static void Test03IdDoesNotFlow() Assert.False(j.HasValue(CharacteristicObject.IdCharacteristic)); Assert.False(j.Environment.HasValue(CharacteristicObject.IdCharacteristic)); - Job.EnvironmentCharacteristic[j] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); // id will not flow - Assert.False(j.HasValue(CharacteristicObject.IdCharacteristic)); - Assert.False(j.Environment.HasValue(CharacteristicObject.IdCharacteristic)); + Job.EnvironmentCharacteristic[j] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); // id will flow + Assert.True(j.HasValue(CharacteristicObject.IdCharacteristic)); + Assert.True(j.Environment.HasValue(CharacteristicObject.IdCharacteristic)); var c = new CharacteristicSet(EnvironmentMode.LegacyJitX64, RunMode.Long); // id will not flow, new CharacteristicSet Assert.False(c.HasValue(CharacteristicObject.IdCharacteristic)); - Job.EnvironmentCharacteristic[c] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); // id will not flow - Assert.False(c.HasValue(CharacteristicObject.IdCharacteristic)); + Job.EnvironmentCharacteristic[c] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); // id will flow + Assert.True(c.HasValue(CharacteristicObject.IdCharacteristic)); CharacteristicObject.IdCharacteristic[c] = "MyId"; // id set explicitly Assert.Equal("MyId", c.Id); @@ -221,12 +221,12 @@ public static void Test03IdDoesNotFlow() Assert.Equal("MyId", j.Id); Assert.Equal("MyId", j.Environment.Id); - Job.EnvironmentCharacteristic[j] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); // id will not flow - Assert.Equal("MyId", j.Id); - Assert.Equal("MyId", j.Environment.Id); + Job.EnvironmentCharacteristic[j] = EnvironmentMode.LegacyJitX86.UnfreezeCopy(); + Assert.Equal("LegacyJitX86", j.Id); + Assert.Equal("LegacyJitX86", j.Environment.Id); - j = j.WithJit(Jit.RyuJit); // custom id will flow - Assert.Equal("MyId", j.Id); + j = j.WithJit(Jit.RyuJit); + Assert.Equal("LegacyJitX86", j.Id); } [Fact] @@ -474,6 +474,20 @@ public static void WithNuGet() Assert.Equal(expected, j.Infrastructure.NuGetReferences); // ensure that the list's equality operator returns true when the contents are the same } + [Fact] + public static void UnfreezeCopy_PreservesIdCharacteristic() + { + // Arrange + var original = new Job(); + original.SetValue(Job.IdCharacteristic, "TestID"); + + // Act + var copy = original.UnfreezeCopy(); + + // Assert + Assert.Equal("TestID", copy.GetValue(Job.IdCharacteristic)); + } + private static bool IsSubclassOfobModeOfItself(Type type) { Type jobModeOfT;
Custom `SimpleJob` Id ignored when the `MinIterationTime` attribute is used. Hello, just identified the issue that causes all Jobs declared as attributes to have their Id's replaced with random Job names in the summary table if the `MinIterationTime `attribute is used. Steps to reproduce: Create benchmark class and add two `SimpleJob `attributes as well as `AllStatisticsColumn` to show the Job Id. Here I just use the default example from README. ``` [AllStatisticsColumn] [SimpleJob(RunStrategy.ColdStart, launchCount: 5, warmupCount: 1, iterationCount: 1, id: "Job A")] [SimpleJob(RunStrategy.Throughput, launchCount:1, warmupCount:1, iterationCount: 5, id: "Job B")] public class Md5VsSha256 { private SHA256 sha256 = SHA256.Create(); private MD5 md5 = MD5.Create(); private byte[] data; [Params(1000, 10000)] public int N; [GlobalSetup] public void Setup() { data = new byte[N]; new Random(42).NextBytes(data); } [Benchmark] public byte[] Sha256() => sha256.ComputeHash(data); [Benchmark] public byte[] Md5() => md5.ComputeHash(data); } ``` In this case the table shows correct Job Id in the table( included only 2 lines for brevity) | Method | Job | IterationCount | LaunchCount | RunStrategy | UnrollFactor | N | Mean | Error | StdDev | StdErr | Min | Q1 | Median | Q3 | Max | Op/s | |------- |------ |--------------- |------------ |------------ |------------- |------ |-------------:|-------------:|-------------:|-------------:|-------------:|-------------:|-------------:|-------------:|-------------:|------------:| | Sha256 | Job A | 1 | 5 | ColdStart | 1 | 1000 | 488,140.0 ns | 134,559.1 ns | 34,944.57 ns | 15,627.69 ns | 454,800.0 ns | 474,900.0 ns | 475,200.0 ns | 489,100.0 ns | 546,700.0 ns | 2,048.6 | | Md5 | Job A | 1 | 5 | ColdStart | 1 | 1000 | 512,220.0 ns | 101,163.3 ns | 26,271.79 ns | 11,749.10 ns | 483,100.0 ns | 487,600.0 ns | 518,800.0 ns | 527,100.0 ns | 544,500.0 ns | 1,952.3 | In case when also the `MinIterationTIme `attribute is added, the table shows the randomly generated Job Id ``` [AllStatisticsColumn] [MinIterationTime(25)] [SimpleJob(RunStrategy.ColdStart, launchCount: 5, warmupCount: 1, iterationCount: 1, id: "Job A")] [SimpleJob(RunStrategy.Throughput, launchCount:1, warmupCount:1, iterationCount: 5, id: "Job B")] public class Md5VsSha256 { ... } ``` | Method | Job | IterationCount | LaunchCount | RunStrategy | UnrollFactor | N | Mean | Error | StdDev | StdErr | Min | Q1 | Median | Q3 | Max | Op/s | |------- |----------- |--------------- |------------ |------------ |------------- |------ |-----------:|------------:|-----------:|-----------:|-----------:|-----------:|-----------:|-----------:|-----------:|----------:| | Sha256 | Job-UJDDOK | 1 | 5 | ColdStart | 1 | 1000 | 498.600 us | 93.2607 us | 24.2195 us | 10.8313 us | 483.000 us | 483.500 us | 487.300 us | 498.800 us | 540.400 us | 2,005.6 | | Md5 | Job-UJDDOK | 1 | 5 | ColdStart | 1 | 1000 | 552.900 us | 314.1166 us | 81.5751 us | 36.4815 us | 485.900 us | 514.700 us | 526.400 us | 543.600 us | 693.900 us | 1,808.6 |
Leaving some findings here to (hopefully) help the next person. I noticed that I can recreate the issue with other attributes like [IterationTime(100)] or [MinInvokeCount(2)] as long as it has .IsMutator set to true. The ResolvedId is set in the Job class `public string ResolvedId => HasValue(IdCharacteristic) ? Id : JobIdGenerator.GenerateRandomId(this);` So I assume somewhere along the way IdCharacteristic loses it's value. One method of interest with my comments added. Found in the ImmutableConfigBuilder class: ``` private static IReadOnlyList<Job> GetRunnableJobs(IEnumerable<Job> jobs) { var unique = jobs.Distinct(JobComparer.Instance).ToArray(); var result = new List<Job>(); foreach (var standardJob in unique.Where(job => !job.Meta.IsMutator && !job.Meta.IsDefault)) result.Add(standardJob); var customDefaultJob = unique.SingleOrDefault(job => job.Meta.IsDefault); var defaultJob = customDefaultJob ?? Job.Default; if (!result.Any()) result.Add(defaultJob); // If no mutatorJob then the ResolvedId names are kept in place as the code will skip this foreach. // Here is where the ResolvedId changes to the randomly generated value foreach (var mutatorJob in unique.Where(job => job.Meta.IsMutator)) { for (int i = 0; i < result.Count; i++) { // As soon as UnfreezeCopy() finishes the resolvedId changes var copy = result[i].UnfreezeCopy(); copy.Apply(mutatorJob); result[i] = copy.Freeze(); } } return result; } ``` I also kept testing old commits and the issue was there as well. I went as far as 7/26/23 d93490d1f and this was still an issue.
2024-01-02T03:41:37Z
0.1
['BenchmarkDotNet.Tests.Configs.JobTests.UnfreezeCopy_PreservesIdCharacteristic']
['BenchmarkDotNet.Tests.ConfigParserTests.UsersCanSpecifyWithoutOverheadEvalution', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyNoForceGCs', 'BenchmarkDotNet.Tests.ConfigParserTests.InvalidHardwareCounterNameMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanEasilyRequestToRunTheBenchmarkOncePerIteration', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyBuildTimeout', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseInfo', 'BenchmarkDotNet.Tests.ConfigParserTests.NetMonikersAreRecognizedAsNetCoreMonikers', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyCustomMaxParameterColumnWidth', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyEnvironmentVariables', 'BenchmarkDotNet.Tests.ConfigParserTests.DotNetCliParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyHowManyTimesTheBenchmarkShouldBeExecuted', 'BenchmarkDotNet.Tests.ConfigParserTests.SimpleConfigParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.SimpleConfigAlternativeVersionParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenConfigOptionsFlagsAreNotSpecifiedTheyAreNotSet', 'BenchmarkDotNet.Tests.ConfigParserTests.TooManyHardwareCounterNameMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyCustomDefaultJobAndOverwriteItsSettingsViaConsoleArgs', 'BenchmarkDotNet.Tests.ConfigParserTests.NonExistingPathMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanChooseStrategy', 'BenchmarkDotNet.Tests.ConfigParserTests.PackagesPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseDisassemblerWithCustomRecursiveDepth', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenCustomDisassemblerSettingsAreProvidedItsEnabledByDefault', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseHardwareCounters', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenUserDoesNotSpecifyTimeoutTheDefaultValueIsUsed', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyProcessPlatform', 'BenchmarkDotNet.Tests.ConfigParserTests.IlCompilerPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.ConfigOptionsParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyWasmArgsViaResponseFile', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyWasmArgsUsingEquals', 'BenchmarkDotNet.Tests.ConfigParserTests.PlatformSpecificMonikersAreSupported', 'BenchmarkDotNet.Tests.ConfigParserTests.MonoPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.CanCompareFewDifferentRuntimes', 'BenchmarkDotNet.Tests.ConfigParserTests.InvalidEnvVarAreRecognized', 'BenchmarkDotNet.Tests.ConfigParserTests.CheckUpdateInvalidArgs', 'BenchmarkDotNet.Tests.ConfigParserTests.EmptyArgsMeansConfigWithoutJobs', 'BenchmarkDotNet.Tests.ConfigParserTests.CanUseStatisticalTestsToCompareFewDifferentRuntimes', 'BenchmarkDotNet.Tests.ConfigParserTests.SpecifyingInvalidStatisticalTestsThresholdMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.NetFrameworkMonikerParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.CheckUpdateValidArgs']
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2453
e170684208103ca5ba4212ad8dc7c2aad5cf02d4
diff --git a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs index af12d018b5..eaf1da4683 100644 --- a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs +++ b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs @@ -34,7 +34,8 @@ public class CsProjGenerator : DotNetCliGenerator, IEquatable<CsProjGenerator> "CopyLocalLockFileAssemblies", "PreserveCompilationContext", "UserSecretsId", - "EnablePreviewFeatures" + "EnablePreviewFeatures", + "RuntimeHostConfigurationOption", }.ToImmutableArray(); public string RuntimeFrameworkVersion { get; }
diff --git a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs index 715d7dad64..323da8ddba 100644 --- a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs +++ b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs @@ -18,6 +18,11 @@ namespace BenchmarkDotNet.Tests public class CsProjGeneratorTests { private FileInfo TestAssemblyFileInfo = new FileInfo(typeof(CsProjGeneratorTests).Assembly.Location); + private const string runtimeHostConfigurationOptionChunk = """ +<ItemGroup> + <RuntimeHostConfigurationOption Include="System.Runtime.Loader.UseRidGraph" Value="true" /> +</ItemGroup> +"""; [Theory] [InlineData("net471", false)] @@ -68,7 +73,7 @@ private void AssertParsedSdkName(string csProjContent, string targetFrameworkMon private static void AssertCustomProperties(string expected, string actual) { - Assert.Equal(expected.Replace(Environment.NewLine, "\n").Replace("\n", Environment.NewLine), actual); + Assert.Equal(expected.Replace("\r", "").Replace("\n", Environment.NewLine), actual); } [Fact] @@ -158,6 +163,24 @@ public void SettingsFromPropsFileImportedUsingRelativePathGetCopies() File.Delete(propsFilePath); } + [Fact] + public void RuntimeHostConfigurationOptionIsCopied() + { + string source = $@" +<Project Sdk=""Microsoft.NET.Sdk""> +{runtimeHostConfigurationOptionChunk} +</Project>"; + + var sut = new CsProjGenerator("netcoreapp3.0", null, null, null, true); + + var xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(source); + var (customProperties, sdkName) = sut.GetSettingsThatNeedToBeCopied(xmlDoc, TestAssemblyFileInfo); + + AssertCustomProperties(runtimeHostConfigurationOptionChunk, customProperties); + Assert.Equal("Microsoft.NET.Sdk", sdkName); + } + [Fact] public void TheDefaultFilePathShouldBeUsedWhenAnAssemblyLocationIsEmpty() {
Add support for `runtimeconfig.template.json` If I add RuntimeHostConfigurationOption to the benchmark project like this: ```xml <ItemGroup> <RuntimeHostConfigurationOption Include="System.Runtime.Loader.UseRidGraph" Value="true" /> </ItemGroup> ``` The built project will have this added to [appname].runtimeconfig.json: ```json { "runtimeOptions": { "configProperties": { "System.Runtime.Loader.UseRidGraph": true } } } ``` This is important to be able to deal with this breaking change in .NET 8: https://learn.microsoft.com/en-us/dotnet/core/compatibility/deployment/8.0/rid-asset-list#recommended-action However, the generated project does not copy this setting over, so the resulting project will not get the correct value injected into its runtimeconfig.json. An alternative way is to add a `runtimeconfig.template.json` file with the above json, but again, the generated project will not pick this up. Perhaps https://github.com/dotnet/BenchmarkDotNet/blob/ece5ccfc91d92b610338b05da73d2a91508e2837/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs#L26 needs `RuntimeHostConfigurationOption` added, and also a way to make sure `runtimeconfig.template.json` files are copied as well.
null
2023-10-26T15:49:07Z
0.1
['BenchmarkDotNet.Tests.CsProjGeneratorTests.RuntimeHostConfigurationOptionIsCopied']
['BenchmarkDotNet.Tests.CsProjGeneratorTests.TestAssemblyFilePathIsUsedWhenTheAssemblyLocationIsNotEmpty', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.ItsPossibleToCustomizeProjectSdkForNetCoreAppsBasedOnTheImportOfSdk', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.UseWpfSettingGetsCopied', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.SettingsFromPropsFileImportedUsingAbsolutePathGetCopies', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.TheDefaultFilePathShouldBeUsedWhenAnAssemblyLocationIsEmpty', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.ItsPossibleToCustomizeProjectSdkBasedOnProjectSdkFromTheProjectFile', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.SettingsFromPropsFileImportedUsingRelativePathGetCopies', 'BenchmarkDotNet.Tests.CsProjGeneratorTests.ItsImpossibleToCustomizeProjectSdkForFullFrameworkAppsBasedOnTheImportOfSdk']
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2395
2c999b9a2396a2c8138fa6e5ec093c6f35326b6a
diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs index f5d857df1d..0540dd1426 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs @@ -109,28 +109,28 @@ void AddWarning(string message) configAnalyse.Add(conclusion); } - var mergeDictionary = new Dictionary<System.Type, IExporter>(); + var mergeDictionary = new Dictionary<string, IExporter>(); foreach (var exporter in exporters) { - var exporterType = exporter.GetType(); - if (mergeDictionary.ContainsKey(exporterType)) + var exporterName = exporter.Name; + if (mergeDictionary.ContainsKey(exporterName)) { - AddWarning($"The exporter {exporterType} is already present in configuration. There may be unexpected results."); + AddWarning($"The exporter {exporterName} is already present in configuration. There may be unexpected results."); } - mergeDictionary[exporterType] = exporter; + mergeDictionary[exporterName] = exporter; } foreach (var diagnoser in uniqueDiagnosers) foreach (var exporter in diagnoser.Exporters) { - var exporterType = exporter.GetType(); - if (mergeDictionary.ContainsKey(exporterType)) + var exporterName = exporter.Name; + if (mergeDictionary.ContainsKey(exporterName)) { - AddWarning($"The exporter {exporterType} of {diagnoser.GetType().Name} is already present in configuration. There may be unexpected results."); + AddWarning($"The exporter {exporterName} of {diagnoser.GetType().Name} is already present in configuration. There may be unexpected results."); } - mergeDictionary[exporterType] = exporter; + mergeDictionary[exporterName] = exporter; } var result = mergeDictionary.Values.ToList(); @@ -143,7 +143,7 @@ void AddWarning(string message) if (hardwareCounterDiagnoser != default(IHardwareCountersDiagnoser) && disassemblyDiagnoser != default(DisassemblyDiagnoser)) result.Add(new InstructionPointerExporter(hardwareCounterDiagnoser, disassemblyDiagnoser)); - for (int i = result.Count - 1; i >=0; i--) + for (int i = result.Count - 1; i >= 0; i--) if (result[i] is IExporterDependencies exporterDependencies) foreach (var dependency in exporterDependencies.Dependencies) /* @@ -165,7 +165,7 @@ void AddWarning(string message) * "The CsvMeasurementsExporter is already present in the configuration. There may be unexpected results of RPlotExporter. * */ - if (!result.Any(exporter=> exporter.GetType() == dependency.GetType())) + if (!result.Any(exporter => exporter.GetType() == dependency.GetType())) result.Insert(i, dependency); // All the exporter dependencies should be added before the exporter else { @@ -186,9 +186,9 @@ private static ImmutableHashSet<IAnalyser> GetAnalysers(IEnumerable<IAnalyser> a builder.Add(analyser); foreach (var diagnoser in uniqueDiagnosers) - foreach (var analyser in diagnoser.Analysers) - if (!builder.Contains(analyser)) - builder.Add(analyser); + foreach (var analyser in diagnoser.Analysers) + if (!builder.Contains(analyser)) + builder.Add(analyser); return builder.ToImmutable(); }
diff --git a/tests/BenchmarkDotNet.Tests/Configs/ImmutableConfigTests.cs b/tests/BenchmarkDotNet.Tests/Configs/ImmutableConfigTests.cs index 82c01d3b81..2eae58c7c1 100644 --- a/tests/BenchmarkDotNet.Tests/Configs/ImmutableConfigTests.cs +++ b/tests/BenchmarkDotNet.Tests/Configs/ImmutableConfigTests.cs @@ -143,6 +143,19 @@ public void DuplicateExportersAreExcluded() Assert.Same(MarkdownExporter.GitHub, final.GetExporters().Single()); } + [Fact] + public void MultipleExportersOfSameTypeWithDifferentNamesAreAccepted() + { + var mutable = ManualConfig.CreateEmpty(); + + mutable.AddExporter(MarkdownExporter.GitHub); + mutable.AddExporter(MarkdownExporter.Atlassian); + + var final = ImmutableConfigBuilder.Create(mutable); + + Assert.Equal(2, final.GetExporters().Count()); + } + [Fact] public void DuplicateAnalyzersAreExcluded() { @@ -380,7 +393,7 @@ private static ImmutableConfig[] AddLeftToTheRightAndRightToTheLef(ManualConfig var leftAddedToTheRight = ManualConfig.Create(right); leftAddedToTheRight.Add(left); - return new[]{ rightAddedToLeft.CreateImmutableConfig(), leftAddedToTheRight.CreateImmutableConfig() }; + return new[] { rightAddedToLeft.CreateImmutableConfig(), leftAddedToTheRight.CreateImmutableConfig() }; } public class TestExporter : IExporter, IExporterDependencies
Multiple MarkdownExporters not possible I'm testing BenchmarkDotNet and would like to have the benchmark results exported to both GitHub markdown and Atlassian markdown. But I get the error ``` The exporter BenchmarkDotNet.Exporters.MarkdownExporter is already present in configuration. There may be unexpected results. ``` Is that by intention - and why is it not possible to export to both markdown formats in the same run?
> Is that by intention I really doubt that, it's most likely a bug on our side. The issue is as far as I can see in the `ImmutableConfigBuilder.GetExporters` method. It makes a mergeDictionary by the System.Type - and that will be the same for both the GitHub MarkdownExporter and the Atlassian MarkdownExporter. If the purpose is to avoid having for example GitHub MarkdownExporter twice in the merged list, I see the logic in going through the lists of exporters and remove duplicates. But it has to be on something else or more that just the System.Type.
2023-08-09T13:43:49Z
0.1
['BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.MultipleExportersOfSameTypeWithDifferentNamesAreAccepted']
['BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.GenerateWarningWhenExporterDependencyAlreadyExistInConfig', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateExportersAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateDiagnosersAreExcludedBasedOnType', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenSummaryStyleIsNullDefaultValueShouldBeUsed', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateHardwareCountersAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateColumnProvidersAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateAnalyzersAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateValidatorsAreExcludedBasedOnTreatsWarningsAsErrorsProperty', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTwoConfigsAreAddedTheMutatorJobsAreAppliedToAllOtherJobs', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTwoConfigsAreAddedTheRegularJobsAreJustAdded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTwoCustomTimeoutsAreProvidedTheLongerOneIsUsed', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.BaseLineValidatorIsMandatory', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.JitOptimizationsValidatorIsMandatoryByDefault', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTimeoutIsNotSpecifiedTheDefaultValueIsUsed', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateLoggersAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.MissingDependencyIsNotAddedWhenItIsAlreadyPresent', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.DuplicateJobsAreExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenArtifactsPathIsNullDefaultValueShouldBeUsed', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.JitOptimizationsValidatorIsMandatoryCanBeDisabledOnDemand', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.NoSetHardwareCounterIsExcluded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTwoConfigsAreAddedTheMutatorJobsAreAppliedToDefaultJobIfCustomDefaultJobIsNotPresent', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenTwoConfigsAreAddedTheMutatorJobsAreAppliedToCustomDefaultJobIfPresent', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.MissingExporterDependencyIsAddedWhenNeeded', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.CustomTimeoutHasPrecedenceOverDefaultTimeout', 'BenchmarkDotNet.Tests.Configs.ImmutableConfigTests.WhenOrdererIsNullDefaultValueShouldBeUsed']
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2368
8a7caa7acd6a2b2f5e49b57f225ccbabd268029b
diff --git a/src/BenchmarkDotNet/Parameters/ParameterComparer.cs b/src/BenchmarkDotNet/Parameters/ParameterComparer.cs index a1363de073..6cadf6a946 100644 --- a/src/BenchmarkDotNet/Parameters/ParameterComparer.cs +++ b/src/BenchmarkDotNet/Parameters/ParameterComparer.cs @@ -28,7 +28,16 @@ private int CompareValues(object x, object y) if (x != null && y != null && x.GetType() == y.GetType() && x is IComparable xComparable) { - return xComparable.CompareTo(y); + try + { + return xComparable.CompareTo(y); + } + // Some types, such as Tuple and ValueTuple, have a fallible CompareTo implementation which can throw if the inner items don't implement IComparable. + // See: https://github.com/dotnet/BenchmarkDotNet/issues/2346 + // For now, catch and ignore the exception, and fallback to string comparison below. + catch (ArgumentException ex) when (ex.Message.Contains("At least one object must implement IComparable.")) + { + } } // Anything else.
diff --git a/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs b/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs index 0f01045b5c..2ef1bc8891 100644 --- a/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs +++ b/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs @@ -157,6 +157,70 @@ public void IComparableComparisionTest() Assert.Equal(4, ((ComplexParameter)sortedData[3].Items[0].Value).Value); } + [Fact] + public void ValueTupleWithNonIComparableInnerTypesComparisionTest() + { + var comparer = ParameterComparer.Instance; + var originalData = new[] + { + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, (new ComplexNonIComparableParameter(), 1), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, (new ComplexNonIComparableParameter(), 3), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, (new ComplexNonIComparableParameter(), 2), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, (new ComplexNonIComparableParameter(), 4), null) + }) + }; + + var sortedData = originalData.OrderBy(d => d, comparer).ToArray(); + + Assert.Equal(1, (((ComplexNonIComparableParameter, int))sortedData[0].Items[0].Value).Item2); + Assert.Equal(2, (((ComplexNonIComparableParameter, int))sortedData[1].Items[0].Value).Item2); + Assert.Equal(3, (((ComplexNonIComparableParameter, int))sortedData[2].Items[0].Value).Item2); + Assert.Equal(4, (((ComplexNonIComparableParameter, int))sortedData[3].Items[0].Value).Item2); + } + + [Fact] + public void TupleWithNonIComparableInnerTypesComparisionTest() + { + var comparer = ParameterComparer.Instance; + var originalData = new[] + { + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, Tuple.Create(new ComplexNonIComparableParameter(), 1), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, Tuple.Create(new ComplexNonIComparableParameter(), 3), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, Tuple.Create(new ComplexNonIComparableParameter(), 2), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, Tuple.Create(new ComplexNonIComparableParameter(), 4), null) + }) + }; + + var sortedData = originalData.OrderBy(d => d, comparer).ToArray(); + + Assert.Equal(1, ((Tuple<ComplexNonIComparableParameter, int>)sortedData[0].Items[0].Value).Item2); + Assert.Equal(2, ((Tuple<ComplexNonIComparableParameter, int>)sortedData[1].Items[0].Value).Item2); + Assert.Equal(3, ((Tuple<ComplexNonIComparableParameter, int>)sortedData[2].Items[0].Value).Item2); + Assert.Equal(4, ((Tuple<ComplexNonIComparableParameter, int>)sortedData[3].Items[0].Value).Item2); + } + private class ComplexParameter : IComparable<ComplexParameter>, IComparable { public ComplexParameter(int value, string name) @@ -199,5 +263,9 @@ public int CompareTo(object obj) return CompareTo(other); } } + + private class ComplexNonIComparableParameter + { + } } } \ No newline at end of file
Can't use latest version of BenchmarkDotNet I tried to use the latest bdn master (dotnet/BenchmarkDotNet@73f8fd1dc49f34b79afa4ef16e0204b1369fdd1a) here, but trying to run benchmarks fails with: ``` Unhandled exception. System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b) at System.ValueTuple`3.CompareTo(ValueTuple`3 other) at System.ValueTuple`3.System.IComparable.CompareTo(Object other) at BenchmarkDotNet.Parameters.ParameterComparer.CompareValues(Object x, Object y) at BenchmarkDotNet.Parameters.ParameterComparer.Compare(ParameterInstances x, ParameterInstances y) at BenchmarkDotNet.Order.DefaultOrderer.BenchmarkComparer.Compare(BenchmarkCase x, BenchmarkCase y) at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(Span`1 keys, Comparison`1 comparer, Int32 i, Int32 j) at System.Collections.Generic.ArraySortHelper`1.PickPivotAndPartition(Span`1 keys, Comparison`1 comparer) at System.Collections.Generic.ArraySortHelper`1.IntroSort(Span`1 keys, Int32 depthLimit, Comparison`1 comparer) at System.Collections.Generic.ArraySortHelper`1.IntrospectiveSort(Span`1 keys, Comparison`1 comparer) at System.Collections.Generic.GenericArraySortHelper`1.Sort(Span`1 keys, IComparer`1 comparer) --- End of inner exception stack trace --- at System.Collections.Generic.GenericArraySortHelper`1.Sort(Span`1 keys, IComparer`1 comparer) at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer) at BenchmarkDotNet.Order.DefaultOrderer.GetExecutionOrder(ImmutableArray`1 benchmarkCases, IEnumerable`1 order) at BenchmarkDotNet.Running.BenchmarkConverter.MethodsToBenchmarksWithFullConfig(Type type, MethodInfo[] benchmarkMethods, IConfig config) at BenchmarkDotNet.Running.BenchmarkConverter.TypeToBenchmarks(Type type, IConfig config) at BenchmarkDotNet.Running.TypeFilter.<>c__DisplayClass1_0.<Filter>b__0(Type type) at System.Linq.Enumerable.SelectListIterator`2.MoveNext() at System.Linq.Enumerable.WhereEnumerableIterator`1.ToArray() at BenchmarkDotNet.Running.TypeFilter.Filter(IConfig effectiveConfig, IEnumerable`1 types) at BenchmarkDotNet.Running.BenchmarkSwitcher.RunWithDirtyAssemblyResolveHelper(String[] args, IConfig config, Boolean askUserForInput) at BenchmarkDotNet.Running.BenchmarkSwitcher.Run(String[] args, IConfig config) at MicroBenchmarks.Program.Main(String[] args) in /Users/ankj/dev/performance/src/benchmarks/micro/Program.cs:line 43 ``` This seems to be failing for ``` System.ValueTuple`3[System.Globalization.CultureInfo,System.Globalization.CompareOptions,System.Boolean], (en-US, Ordinal, False) System.ValueTuple`3[System.Globalization.CultureInfo,System.Globalization.CompareOptions,System.Boolean], (pl-PL, None, False)` ``` .. , because `CultureInfo` does not implement `IComparable`. IIUC, this is a new code path introduced as part of https://github.com/dotnet/BenchmarkDotNet/pull/2304 . And it fails for https://github.com/dotnet/performance/blob/dd14c7d44444a0211035af8464b743a55b4dd55e/src/benchmarks/micro/libraries/System.Globalization/StringSearch.cs#L46 . cc @mrahhal @adamsitnik @LoopedBard3
Should this be in dotnet/BenchmarkDotNet instead? The following reproduces the problem: ```cs var t1 = (new CultureInfo("en-US"), CompareOptions.Ordinal, false); var t2 = (new CultureInfo("pl-PL"), CompareOptions.None, false); Assert.IsTrue(typeof(IComparable).IsAssignableFrom(t1.GetType())); // Succeeds var result = t1.CompareTo(t2); // Throws System.ArgumentException: At least one object must implement IComparable. ``` This is because `ValueTuple` implements `IComparable` regardless of whether or not the inner types inside imeplement it, so its `CompareTo` implementation is fallible and might throw in that case. In this particular case, `CultureInfo` doesn't, and so it throws. One potential solution is to have specific support for detecting `ValueTuple`s, and do an alternative check of whether all the types inside are `IComparable` to consider the whole tuple `IComparable`. Or the easy way out, if it's a `ValueTuple` then just skip the `IComparable` support and go straight to the `ToString()` comparison. For reference, the `ValueTuple`'s `CompareTo` [implementation](https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/ValueTuple.cs,722), and [this is](https://github.com/mrahhal/BenchmarkDotNet/blob/ca4d012c3b9c1a8bac230b8311ea2f7db1d13d55/src/BenchmarkDotNet/Parameters/ParameterComparer.cs#L28-L32) where we might solve this in BenchmarkDotNet. Working on this fix. Let me know which of the following two solutions I listed above do you prefer: 1. For `ValueTuple`s, check all inner types if they implement `IComparable` before considering it such 2. For `ValueTuple`s, just skip `IComparable` support and go straight to string comparison (emulates old behavior for `ValueTuple`s) Any other suggested solution? @mrahhal Maybe just catch the exception and fall back to string comparison? Could do that, but that might hide other unrelated exceptions we didn't intend to hide. Might be better to properly handle this particular case in my opinion. `ValueTuple` seems to be a special case, `IComparable` doesn't usually throw. @mrahhal How is the fix looking? Any ETA? Thanks. Was waiting for a reply as I didn't want to work on something and then change it right after a review. And honestly forgot about it while waiting. Ready to roll out a fix when a maintainer confirms one of my two suggestions above.. Or I think I'll just go with whatever I think is better to start with. Will submit a PR soon. I think if you want to handle `ValueTuple` specially, it's fine. > check all inner types if they implement `IComparable` before considering it such Just be aware that they can have variable number of types and nested `ValueTuple`s. > Just be aware that they can have variable number of types and nested ValueTuples. Going through `ITuple` might make that easier. > Going through `ITuple` might make that easier. That's an internal interface (and it only has a Size prop, I don't think it helps much anyway). > Just be aware that they can have variable number of types and nested `ValueTuple`s. Yes. A simple recursive check will do for nesting. The problem is actually how to detect `ValueTuple`s, since it's a series of (unlimited number of?) structs depending on the number of items. And I don't feel either supporting up to some fixed number or doing something fancy with `Type.FullName` is a good idea. Starting to think handling exceptions when calling the `IComparable` impl and falling back to `.ToString()` as @timcassell suggested is just the easiest as a start to get the old behavior back. Mayhe this can be handled better in the future, but let's just roll out a fix for now. > That's an internal interface (and it only has a Size prop, I don't think it helps much anyway). It's public interface. And has also indexer. > It's public interface. And has also indexer. I think it's internal in netstandard. But more importantly, isn't `ITuple` for `Tuple` (the older class tuples)? I don't think it's related to `ValueTuple`. Yeah, you need at least `netstandard2.1`. :( Both `Tuple` and `ValueTuple`. BDN has a transitive reference to the `System.ValueTuple` nuget package, so you can use the `ITuple` interface. In fact, you should use that interface to check for `Tuple` also, as it also has the same `IComparable` functionality. ```cs public interface ITuple { int Length { get; } object this[int index] { get; } } ``` ![image](https://github.com/dotnet/BenchmarkDotNet/assets/4404199/bbb42ca8-32bf-47bd-8b11-8795fedd4d59) Doesn't seem usable in netstandard2.0. And yes, `Tuple` has the same problem. Looking at the `ITuple` interface above, indeed it would have been the best way to solve this, but I guess we're stuck because of netstandard2.0. Oh weird, it's not public from the nuget package. You may still be able to use it with reflection, though.
2023-07-13T09:08:20Z
0.1
['BenchmarkDotNet.Tests.ParameterComparerTests.TupleWithNonIComparableInnerTypesComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.ValueTupleWithNonIComparableInnerTypesComparisionTest']
['BenchmarkDotNet.Tests.ParameterComparerTests.IComparableComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.BasicComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.AlphaNumericComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.MultiParameterComparisionTest']
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2057
44f79c1f3e23ff16ecadc22e8c135c449a1890ae
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 0ed26db03..067853098 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -190,7 +190,7 @@ public class TypeCollector private readonly ITypeSymbol? targetType; // visitor workspace: - private readonly Dictionary<ITypeSymbol, bool> alreadyCollected = new(SymbolEqualityComparer.Default); + private readonly HashSet<ITypeSymbol> alreadyCollected = new(SymbolEqualityComparer.Default); private readonly ImmutableSortedSet<ObjectSerializationInfo>.Builder collectedObjectInfo = ImmutableSortedSet.CreateBuilder<ObjectSerializationInfo>(ResolverRegisterInfoComparer.Default); private readonly ImmutableSortedSet<EnumSerializationInfo>.Builder collectedEnumInfo = ImmutableSortedSet.CreateBuilder<EnumSerializationInfo>(ResolverRegisterInfoComparer.Default); private readonly ImmutableSortedSet<GenericSerializationInfo>.Builder collectedGenericInfo = ImmutableSortedSet.CreateBuilder<GenericSerializationInfo>(ResolverRegisterInfoComparer.Default); @@ -271,111 +271,92 @@ public FullModel Collect() } // Gate of recursive collect - private bool CollectCore(ITypeSymbol typeSymbol) + private void CollectCore(ITypeSymbol typeSymbol, ISymbol? callerSymbol = null) { this.cancellationToken.ThrowIfCancellationRequested(); - if (this.alreadyCollected.TryGetValue(typeSymbol, out bool result)) + if (!this.alreadyCollected.Add(typeSymbol)) { - return result; + return; } var typeSymbolString = typeSymbol.WithNullableAnnotation(NullableAnnotation.NotAnnotated).ToString(); if (!string.IsNullOrEmpty(typeSymbolString) && EmbeddedTypes.Contains(typeSymbolString)) { - result = true; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } FormattableType formattableType = new(typeSymbol, null); if (this.options.AssumedFormattableTypes.Contains(formattableType) || this.options.AssumedFormattableTypes.Contains(formattableType with { IsFormatterInSameAssembly = true })) { - result = true; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } if (typeSymbol is IArrayTypeSymbol arrayTypeSymbol) { - return RecursiveProtection(() => this.CollectArray((IArrayTypeSymbol)this.ToTupleUnderlyingType(arrayTypeSymbol))); + this.CollectArray((IArrayTypeSymbol)this.ToTupleUnderlyingType(arrayTypeSymbol), callerSymbol); + return; } if (typeSymbol is ITypeParameterSymbol) { - result = true; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } if (!IsAllowAccessibility(typeSymbol)) { - result = false; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } if (!(typeSymbol is INamedTypeSymbol type)) { - result = false; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } var customFormatterAttr = typeSymbol.GetAttributes().FirstOrDefault(x => x.AttributeClass.ApproximatelyEqual(this.typeReferences.FormatterAttribute)); if (customFormatterAttr != null) { this.CheckValidMessagePackFormatterAttribute(customFormatterAttr); - result = true; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } if (type.EnumUnderlyingType != null) { - return RecursiveProtection(() => this.CollectEnum(type, type.EnumUnderlyingType)); + this.CollectEnum(type, type.EnumUnderlyingType); + return; } if (type.IsGenericType) { - return RecursiveProtection(() => this.CollectGeneric((INamedTypeSymbol)this.ToTupleUnderlyingType(type))); + this.CollectGeneric((INamedTypeSymbol)this.ToTupleUnderlyingType(type), callerSymbol); + return; } if (type.Locations[0].IsInMetadata) { - result = true; - this.alreadyCollected.Add(typeSymbol, result); - return result; + return; } if (type.TypeKind == TypeKind.Interface || (type.TypeKind == TypeKind.Class && type.IsAbstract)) { - return RecursiveProtection(() => this.CollectUnion(type)); + this.CollectUnion(type); + return; } - return RecursiveProtection(() => this.CollectObject(type)); - - bool RecursiveProtection(Func<bool> func) - { - this.alreadyCollected.Add(typeSymbol, true); - bool result = func(); - this.alreadyCollected[typeSymbol] = result; - return result; - } + this.CollectObject(type, callerSymbol); } - private bool CollectEnum(INamedTypeSymbol type, ISymbol enumUnderlyingType) + private void CollectEnum(INamedTypeSymbol type, ISymbol enumUnderlyingType) { this.collectedEnumInfo.Add(EnumSerializationInfo.Create(type, enumUnderlyingType, this.options.Generator.Resolver)); - return true; } - private bool CollectUnion(INamedTypeSymbol type) + private void CollectUnion(INamedTypeSymbol type) { if (!options.IsGeneratingSource) { // In analyzer-only mode, this method doesn't work. - return true; + return; } ImmutableArray<TypedConstant>[] unionAttrs = type.GetAttributes().Where(x => x.AttributeClass.ApproximatelyEqual(this.typeReferences.UnionAttribute)).Select(x => x.ConstructorArguments).ToArray(); @@ -405,7 +386,6 @@ private bool CollectUnion(INamedTypeSymbol type) this.options.Generator.Resolver); this.collectedUnionInfo.Add(info); - return true; } private void CollectGenericUnion(INamedTypeSymbol type) @@ -420,7 +400,7 @@ private void CollectGenericUnion(INamedTypeSymbol type) do { var x = enumerator.Current; - if (x[1] is { Value: INamedTypeSymbol unionType } && !this.alreadyCollected.ContainsKey(unionType)) + if (x[1] is { Value: INamedTypeSymbol unionType } && !this.alreadyCollected.Contains(unionType)) { this.CollectCore(unionType); } @@ -428,18 +408,15 @@ private void CollectGenericUnion(INamedTypeSymbol type) while (enumerator.MoveNext()); } - private bool CollectArray(IArrayTypeSymbol array) + private void CollectArray(IArrayTypeSymbol array, ISymbol? callerSymbol) { ITypeSymbol elemType = array.ElementType; - if (!this.CollectCore(elemType)) - { - return false; - } + this.CollectCore(elemType, callerSymbol); if (elemType is ITypeParameterSymbol || (elemType is INamedTypeSymbol symbol && IsOpenGenericTypeRecursively(symbol))) { - return true; + return; } QualifiedTypeName elementTypeName = QualifiedTypeName.Create(elemType); @@ -454,7 +431,7 @@ private bool CollectArray(IArrayTypeSymbol array) if (formatterName is null) { ////this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.AotArrayRankTooHigh)); - return false; + return; } var info = ResolverRegisterInfo.CreateArray(array, this.options.Generator.Resolver) with @@ -468,7 +445,6 @@ private bool CollectArray(IArrayTypeSymbol array) }, }; this.collectedArrayInfo.Add(info); - return true; } private ITypeSymbol ToTupleUnderlyingType(ITypeSymbol typeSymbol) @@ -493,7 +469,7 @@ private ITypeSymbol ToTupleUnderlyingType(ITypeSymbol typeSymbol) return namedType; } - private bool CollectGeneric(INamedTypeSymbol type) + private void CollectGeneric(INamedTypeSymbol type, ISymbol? callerSymbol) { INamedTypeSymbol typeDefinition = type.ConstructUnboundGenericType(); var genericTypeDefinitionString = typeDefinition.ToDisplayString(); @@ -506,21 +482,18 @@ private bool CollectGeneric(INamedTypeSymbol type) // special case if (fullName == "global::System.ArraySegment<byte>" || fullName == "global::System.ArraySegment<byte>?") { - return true; + return; } // nullable if (genericTypeDefinitionString == "T?") { var firstTypeArgument = type.TypeArguments[0]; - if (!this.CollectCore(firstTypeArgument)) - { - return false; - } + this.CollectCore(firstTypeArgument, callerSymbol); if (EmbeddedTypes.Contains(firstTypeArgument.ToString()!)) { - return true; + return; } if (!isOpenGenericType) @@ -537,7 +510,7 @@ private bool CollectGeneric(INamedTypeSymbol type) this.collectedGenericInfo.Add(info); } - return true; + return; } // collection @@ -546,14 +519,14 @@ private bool CollectGeneric(INamedTypeSymbol type) { foreach (ITypeSymbol item in type.TypeArguments) { - this.CollectCore(item); + this.CollectCore(item, callerSymbol); } GenericSerializationInfo info; if (isOpenGenericType) { - return true; + return; } else { @@ -575,7 +548,7 @@ private bool CollectGeneric(INamedTypeSymbol type) if (genericTypeDefinitionString != "System.Linq.ILookup<,>") { - return true; + return; } formatterName = KnownGenericTypes["System.Linq.IGrouping<,>"]; @@ -607,17 +580,17 @@ private bool CollectGeneric(INamedTypeSymbol type) Formatter = enumerableInfo.Formatter with { Name = formatterName }, }; this.collectedGenericInfo.Add(enumerableInfo); - return true; + return; } if (type.AllInterfaces.FirstOrDefault(x => !x.IsUnboundGenericType && x.ConstructUnboundGenericType() is { Name: nameof(ICollection<int>) }) is INamedTypeSymbol collectionIface && type.InstanceConstructors.Any(ctor => ctor.Parameters.Length == 0)) { - this.CollectCore(collectionIface.TypeArguments[0]); + this.CollectCore(collectionIface.TypeArguments[0], callerSymbol); if (isOpenGenericType) { - return true; + return; } else { @@ -633,6 +606,7 @@ private bool CollectGeneric(INamedTypeSymbol type) }; this.collectedGenericInfo.Add(info); + return; } } @@ -640,29 +614,23 @@ private bool CollectGeneric(INamedTypeSymbol type) if (type.IsDefinition) { this.CollectGenericUnion(type); - return this.CollectObject(type); + this.CollectObject(type, callerSymbol); } else { // Collect substituted types for the properties and fields. // NOTE: It is used to register formatters from nested generic type. // However, closed generic types such as `Foo<string>` are not registered as a formatter. - this.GetObjectInfo(type); + this.GetObjectInfo(type, callerSymbol); // Collect generic type definition, that is not collected when it is defined outside target project. - if (!this.CollectCore(type.OriginalDefinition)) - { - return false; - } + this.CollectCore(type.OriginalDefinition, callerSymbol); } // Collect substituted types for the type parameters (e.g. Bar in Foo<Bar>) foreach (var item in type.TypeArguments) { - if (!this.CollectCore(item)) - { - return false; - } + this.CollectCore(item, callerSymbol); } if (!isOpenGenericType) @@ -676,22 +644,18 @@ static ImmutableArray<GenericTypeParameterInfo> GetTypeParameters(QualifiedTypeN static ImmutableArray<QualifiedTypeName> GetTypeArguments(QualifiedTypeName qtn) => qtn is QualifiedNamedTypeName named ? named.TypeArguments : ImmutableArray<QualifiedTypeName>.Empty; - - return true; } - private bool CollectObject(INamedTypeSymbol type) + private void CollectObject(INamedTypeSymbol type, ISymbol? callerSymbol) { - ObjectSerializationInfo? info = this.GetObjectInfo(type); + ObjectSerializationInfo? info = this.GetObjectInfo(type, callerSymbol); if (info is not null) { this.collectedObjectInfo.Add(info); } - - return info is not null; } - private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttribute) + private void CheckValidMessagePackFormatterAttribute(AttributeData formatterAttribute) { if (formatterAttribute.ConstructorArguments[0].Value is ITypeSymbol formatterType) { @@ -703,14 +667,10 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr ImmutableDictionary<string, string?> typeInfo = ImmutableDictionary.Create<string, string?>().Add("type", formatterType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.MessageFormatterMustBeMessagePackFormatter, location, typeInfo)); } - - return isMessagePackFormatter; } - - return false; } - private ObjectSerializationInfo? GetObjectInfo(INamedTypeSymbol formattedType) + private ObjectSerializationInfo? GetObjectInfo(INamedTypeSymbol formattedType, ISymbol? callerSymbol) { var isClass = !formattedType.IsValueType; bool nestedFormatterRequired = false; @@ -851,7 +811,7 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) if (specialFormatter is null) { - this.CollectCore(item.Type); // recursive collect + this.CollectCore(item.Type, item); // recursive collect } } @@ -882,7 +842,7 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) if (specialFormatter is null) { - this.CollectCore(item.Type); // recursive collect + this.CollectCore(item.Type, item); // recursive collect } } @@ -1053,19 +1013,7 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) if (messagePackFormatter == null) { // recursive collect - if (!this.CollectCore(item.Type)) - { - var syntax = item.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); - - var typeSyntax = (syntax as PropertyDeclarationSyntax)?.Type - ?? (syntax as ParameterSyntax)?.Type; // for primary constructor - - // TODO: add the declaration of the referenced type as an additional location. - this.reportDiagnostic?.Invoke(Diagnostic.Create( - MsgPack00xMessagePackAnalyzer.TypeMustBeMessagePackObject, - typeSyntax?.GetLocation(), - item.Type.ToDisplayString(ShortTypeNameFormat))); - } + this.CollectCore(item.Type, item); } } } @@ -1198,18 +1146,7 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) if (messagePackFormatter == null) { // recursive collect - if (!this.CollectCore(item.Type)) - { - var syntax = item.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); - - var typeSyntax = ((syntax as VariableDeclaratorSyntax)?.Parent as VariableDeclarationSyntax)?.Type; - - // TODO: add the declaration of the referenced type as an additional location. - this.reportDiagnostic?.Invoke(Diagnostic.Create( - MsgPack00xMessagePackAnalyzer.TypeMustBeMessagePackObject, - typeSyntax?.GetLocation(), - item.Type.ToDisplayString(ShortTypeNameFormat))); - } + this.CollectCore(item.Type, item); } } } @@ -1372,6 +1309,15 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) if (contractAttr is null) { + if (formattedType.IsDefinition) + { + Location location = callerSymbol is not null ? callerSymbol.Locations[0] : formattedType.Locations[0]; + var targetName = callerSymbol is not null ? callerSymbol.ContainingType.Name + "." + callerSymbol.Name : formattedType.Name; + + ImmutableDictionary<string, string?> typeInfo = ImmutableDictionary.Create<string, string?>().Add("type", formattedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); + this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.TypeMustBeMessagePackObject, location, typeInfo, targetName)); + } + // Indicate to our caller that we don't have a valid object. return null; }
diff --git a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs index a0191b047..d39d74ef9 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs @@ -318,7 +318,7 @@ public class Foo public class Bar { [MessagePack.Key(0)] - public {|MsgPack003:Foo|} Member { get; set; } + public Foo {|MsgPack003:Member|} { get; set; } } """; @@ -361,7 +361,7 @@ public class Foo public class Bar { [MessagePack.Key(0)] - public {|MsgPack003:Foo|} Member; + public Foo {|MsgPack003:Member|}; } """; @@ -390,6 +390,92 @@ public class Bar }.RunAsync(); } + [Fact] + public async Task AddAttributeToType_Nullable() + { + // Don't use Preamble because we want to test that it works without a using statement at the top. + string input = /* lang=c#-test */ """ + public struct Foo + { + public string Member; + } + + [MessagePack.MessagePackObject] + public class Bar + { + [MessagePack.Key(0)] + public Foo? {|MsgPack003:Member|}; + } + """; + + string output = /* lang=c#-test */ """ + [MessagePack.MessagePackObject] + public struct Foo + { + [MessagePack.Key(0)] + public string Member; + } + + [MessagePack.MessagePackObject] + public class Bar + { + [MessagePack.Key(0)] + public Foo? Member; + } + """; + + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); + } + + [Fact] + public async Task AddAttributeToType_Generic() + { + // Don't use Preamble because we want to test that it works without a using statement at the top. + string input = /* lang=c#-test */ """ + public struct Foo + { + public string Member; + } + + [MessagePack.MessagePackObject] + public class Bar + { + [MessagePack.Key(0)] + public System.Collections.Generic.List<Foo> {|MsgPack003:Member|}; + } + """; + + string output = /* lang=c#-test */ """ + [MessagePack.MessagePackObject] + public struct Foo + { + [MessagePack.Key(0)] + public string Member; + } + + [MessagePack.MessagePackObject] + public class Bar + { + [MessagePack.Key(0)] + public System.Collections.Generic.List<Foo> Member; + } + """; + + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); + } + [Fact] public async Task AddAttributeToTypeForRecord1() { @@ -404,7 +490,7 @@ public class Foo public record Bar { [MessagePack.Key(0)] - public {|MsgPack003:Foo|} Member { get; set; } + public Foo {|MsgPack003:Member|} { get; set; } } "; @@ -447,7 +533,7 @@ public record Foo public record Bar { [MessagePack.Key(0)] - public {|MsgPack003:Foo|} Member { get; set; } + public Foo {|MsgPack003:Member|} { get; set; } } "; @@ -487,7 +573,7 @@ public class Foo } [MessagePack.MessagePackObject] -public record Bar([property: MessagePack.Key(0)] {|MsgPack003:Foo|} Member); +public record Bar([property: MessagePack.Key(0)] Foo {|MsgPack003:Member|}); namespace System.Runtime.CompilerServices { @@ -590,7 +676,7 @@ public class Foo<T> public class Bar { [Key(0)] - public {|MsgPack003:Foo<int>|} MemberUserGeneric { get; set; } + public Foo<int> {|MsgPack003:MemberUserGeneric|} { get; set; } [Key(1)] public System.Collections.Generic.List<int> MemberKnownGeneric { get; set; }
Code analysis and fix don't work for Nullable and generics in 3.0 prerelease #### Bug description 1. Code fix doesn't add `MessagePackObjectAttribute` and `KeyAttribute` to `A` ```cs public struct A { public int Id; } [MessagePackObject] public class B { [Key(0)] public A? Member; } ``` 2. Code analysis doesn't report that `A` is missing `MessagePackObjectAttribute` ```cs public struct A { public int Id; } [MessagePackObject] public class B { [Key(0)] public List<A> Member; } ``` - Version used: 3.0.238-rc.1 - Runtime: net6.0 #### Additional context v2.5.168 works fine for both cases.
null
2024-11-09T13:25:39Z
0.1
['MsgPack00xAnalyzerTests.AddAttributeToType_Nullable', 'MsgPack00xAnalyzerTests.AddAttributeToType_Generic']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2056
44f79c1f3e23ff16ecadc22e8c135c449a1890ae
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs index 361959503..c35fe171a 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs @@ -20,7 +20,7 @@ private GenericTypeParameterInfo(ITypeParameterSymbol typeParameter, ImmutableSt this.HasReferenceTypeConstraint = typeParameter.HasReferenceTypeConstraint; this.HasValueTypeConstraint = typeParameter.HasValueTypeConstraint; this.HasNotNullConstraint = typeParameter.HasNotNullConstraint; - this.ConstraintTypes = typeParameter.ConstraintTypes.Select(t => QualifiedTypeName.Create(t, recursionGuard)).ToImmutableArray(); + this.ConstraintTypes = typeParameter.ConstraintTypes.Select(t => QualifiedTypeName.Create(t, recursionGuard)).ToImmutableEquatableArray(); this.HasConstructorConstraint = typeParameter.HasConstructorConstraint; this.ReferenceTypeConstraintNullableAnnotation = typeParameter.ReferenceTypeConstraintNullableAnnotation; } @@ -49,7 +49,7 @@ public static GenericTypeParameterInfo Create(ITypeParameterSymbol typeParameter public bool HasNotNullConstraint { get; init; } - public ImmutableArray<QualifiedTypeName> ConstraintTypes { get; init; } + public ImmutableEquatableArray<QualifiedTypeName> ConstraintTypes { get; init; } = ImmutableEquatableArray<QualifiedTypeName>.Empty; public bool HasConstructorConstraint { get; init; } diff --git a/src/MessagePack.SourceGenerator/Utils/ImmutableEquatableArray.cs b/src/MessagePack.SourceGenerator/Utils/ImmutableEquatableArray.cs new file mode 100644 index 000000000..590524131 --- /dev/null +++ b/src/MessagePack.SourceGenerator/Utils/ImmutableEquatableArray.cs @@ -0,0 +1,96 @@ +// Copyright (c) All contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#pragma warning disable SA1127 // Generic type constraints must be on own line +#pragma warning disable SA1402 // File may only contain a single type +#pragma warning disable SA1649 // File name should match first type name + +using System.Collections; + +namespace MessagePack.SourceGenerator; + +/// <summary> +/// Provides an immutable list implementation which implements sequence equality. +/// </summary> +public sealed class ImmutableEquatableArray<T> : IEquatable<ImmutableEquatableArray<T>>, IReadOnlyList<T> + where T : IEquatable<T> +{ + public static ImmutableEquatableArray<T> Empty { get; } = new ImmutableEquatableArray<T>(Array.Empty<T>()); + + private readonly T[] values; + + public T this[int index] => values[index]; + + public int Count => values.Length; + + public ImmutableEquatableArray(IEnumerable<T> values) + => this.values = values.ToArray(); + + public bool Equals(ImmutableEquatableArray<T>? other) + => other is not null && ((ReadOnlySpan<T>)values).SequenceEqual(other.values); + + public override bool Equals(object? obj) + => obj is ImmutableEquatableArray<T> other && Equals(other); + + public override int GetHashCode() + { + int hash = 0; + foreach (T value in values) + { + hash = Combine(hash, value is null ? 0 : value.GetHashCode()); + } + + return hash; + + static int Combine(int h1, int h2) + { + uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27); + return ((int)rol5 + h1) ^ h2; + } + } + + public Enumerator GetEnumerator() => new Enumerator(values); + + IEnumerator<T> IEnumerable<T>.GetEnumerator() => ((IEnumerable<T>)values).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => values.GetEnumerator(); + + public struct Enumerator + { + private readonly T[] values; + private int index; + + internal Enumerator(T[] values) + { + this.values = values; + index = -1; + } + + public bool MoveNext() + { + int newIndex = index + 1; + + if ((uint)newIndex < (uint)values.Length) + { + index = newIndex; + return true; + } + + return false; + } + + public readonly T Current => values[index]; + } +} + +public static class ImmutableEquatableArray +{ + public static ImmutableEquatableArray<T> Empty<T>() where T : IEquatable<T> + => ImmutableEquatableArray<T>.Empty; + + public static ImmutableEquatableArray<T> ToImmutableEquatableArray<T>(this IEnumerable<T> values) where T : IEquatable<T> + => new(values); + + public static ImmutableEquatableArray<T> Create<T>(params T[] values) where T : IEquatable<T> + => values is { Length: > 0 } ? new(values) : ImmutableEquatableArray<T>.Empty; +}
diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index 61a152b25..cb5d73b51 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -947,4 +947,38 @@ public class A await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); } + + [Fact] + public async Task CustomFormatterForGenericWithConstraints() + { + string testSource = /* lang=c#-test */ """ + using System; + using MessagePack; + using MessagePack.Formatters; + + [MessagePackObject] + public partial class SampleObject + { + [Key(0)] + public MyGenericObject<string> Value; + } + + public class MyGenericObject<T> where T : ICloneable { } + + public sealed class MyGenericObjectFormatter<T> : IMessagePackFormatter<MyGenericObject<T>> where T : ICloneable + { + public void Serialize(ref MessagePackWriter writer, MyGenericObject<T> value, MessagePackSerializerOptions options) + { + throw new NotImplementedException(); + } + + public MyGenericObject<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + throw new NotImplementedException(); + } + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/Formatters.MessagePack.GeneratedMessagePackResolver.SampleObjectFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/Formatters.MessagePack.GeneratedMessagePackResolver.SampleObjectFormatter.g.cs new file mode 100644 index 000000000..8aef4f642 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/Formatters.MessagePack.GeneratedMessagePackResolver.SampleObjectFormatter.g.cs @@ -0,0 +1,58 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +namespace MessagePack { +partial class GeneratedMessagePackResolver { + + internal sealed class SampleObjectFormatter : MsgPack::Formatters.IMessagePackFormatter<global::SampleObject> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::SampleObject value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + writer.WriteArrayHeader(1); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::MyGenericObject<string>>(formatterResolver).Serialize(ref writer, value.Value, options); + } + + public global::SampleObject Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + var length = reader.ReadArrayHeader(); + var ____result = new global::SampleObject(); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + ____result.Value = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::MyGenericObject<string>>(formatterResolver).Deserialize(ref reader, options); + break; + default: + reader.Skip(); + break; + } + } + + reader.Depth--; + return ____result; + } + } +} +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..3a33d483a --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/CustomFormatterForGenericWithConstraints/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,75 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) + { + { typeof(global::SampleObject), 0 }, + }; + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> openTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) + { + { typeof(global::MyGenericObject<>), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + switch (closedKey) + { + case 0: return new global::MessagePack.GeneratedMessagePackResolver.SampleObjectFormatter(); + default: return null; // unreachable + }; + } + if (t.IsGenericType && openTypeLookup.TryGetValue(t.GetGenericTypeDefinition(), out int openKey)) + { + switch (openKey) + { + case 0: return global::System.Activator.CreateInstance(typeof(global::MyGenericObjectFormatter<>).MakeGenericType(t.GenericTypeArguments)); + default: return null; // unreachable + }; + } + + return null; + } + } +} + +}
MessagePackAssumesFormattable, MessagePackKnownFormatter not resolving MsgPack003 for type with source-generated formatter #### Bug description In assembly Utilities, there is a custom generic struct: MyStruct<T>. I cannot change this assembly. In the assembly I'm working in, Internal, I have a serializable record type MyRecord. ```csharp [MessagePackObject(AllowPrivate = true) internal record MyRecord( [property: Key(0)] MyStruct<string> Foo); ``` In Internal, I also have a custom formatter for MyStruct<T>. All custom formatters in Internal extend an abstract base class. ```csharp internal abstract class CustomFormatter<T> : IMessagePackFormatter<T> { ... } internal class MyStructFormatter<T> : CustomFormatter<MyStruct<T>> { public static readonly IMessagePackFormatter<MyStruct<T>> Instance = new MyStructFormatter<T>(); ... } ``` When building Internal, I get an analyzer error: MyRecord.cs: error MsgPack003: Type must be marked with MessagePackObjectAttribute: MyStruct (https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/master/doc/analyzers/MsgPack003.md) [Internal.csproj] I tried adding these assembly level attributes (one at a time) to force the analyzer to recognize the type MyStruct<T> as formattable. [assembly: MessagePackKnownFormatter(typeof(MyStructFormatter<>))] [assembly: MessagePackKnownFormatter(typeof(MyStructFormatter<string>))] [assembly: MessagePackAssumedFormattable(typeof(MyStruct<>))] [assembly: MessagePackAssumedFormattable(typeof(MyStruct<string>))] With each one, the result was the same. I would get the same analyzer error. I can workaround it by putting a MessagePackFormatter attribute on the property in MyRecord. I would expect that [assembly: MessagePackKnownFormatter(typeof(MyStructFormatter<>))] would fix the analyzer error. - Version used: 3.0.238-rc.1 - Runtime: .NET Framework
I encontered this issue today. After some investigation, I found it's caused by `GenericTypeParameterInfo.ConstraintTypes`, which doesn't have value equality. When `ConstraintTypes.Length` is zero (like the code above), this issue can only be reproduced in Visual Studio 2022, but not in unit test project (MessagePack.SourceGenerator.Tests). It seems to be caused by the different platforms running roslyn: Visual Studio 2022 uses .net framework and unit test project uses .net8. A simple test: ```cs using System; using System.Collections.Immutable; using System.Linq; namespace ConsoleApp6 { internal class Program { static void Main(string[] args) { var arr = ImmutableArray<int>.Empty; var arr1 = arr.Select(x => x + 1).ToImmutableArray(); var arr2 = arr.Select(x => x + 1).ToImmutableArray(); Console.WriteLine(arr1.Equals(arr2)); } } } ``` It prints `true` in .net8 and prints `false` in net481.
2024-11-09T11:53:53Z
0.1
['GenerationTests.CustomFormatterForGenericWithConstraints']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2045
c54ab0abeeeb71415a924fa784d9b56db4efec3b
diff --git a/README.md b/README.md index 2751b4ba1..fdc288e84 100644 --- a/README.md +++ b/README.md @@ -665,16 +665,11 @@ Untrusted data might come from over the network from an untrusted source (e.g. a Please be very mindful of these attack scenarios; many projects and companies, and serialization library users in general, have been bitten by untrusted user data deserialization in the past. -You should also avoid the Typeless serializer/formatters/resolvers for untrusted data as that opens the door for the untrusted data to potentially deserialize unanticipated types that can compromise security. - -MessagePack v3 assumes the data you deserialize is untrusted and takes mitigating steps including use of collision resistant hash functions when deserializing dictionaries. -The `UntrustedData` default mode merely hardens against some common attacks, but is no fully secure solution in itself. - -When you are deserializing data that you already trust and wish to use faster (insecure) hash functions, you can switch to trusted data mode by configuring your `MessagePackSerializerOptions.Security` property: +When deserializing untrusted data, put MessagePack into a more secure mode by configuring your `MessagePackSerializerOptions.Security` property: ```cs var options = MessagePackSerializerOptions.Standard - .WithSecurity(MessagePackSecurity.TrustedData); + .WithSecurity(MessagePackSecurity.UntrustedData); // Pass the options explicitly for the greatest control. T object = MessagePackSerializer.Deserialize<T>(data, options); @@ -683,8 +678,9 @@ T object = MessagePackSerializer.Deserialize<T>(data, options); MessagePackSerializer.DefaultOptions = options; ``` -You can also derive your own type from the `MessagePackSecurity` class to customize security decisions and hash functions. -Provide an instance of your derived type to the `MessagePackSerializationOptions` type to use it in your deserialization. +You should also avoid the Typeless serializer/formatters/resolvers for untrusted data as that opens the door for the untrusted data to potentially deserialize unanticipated types that can compromise security. + +The `UntrustedData` mode merely hardens against some common attacks, but is no fully secure solution in itself. ## Performance diff --git a/doc/migrating_v2-v3.md b/doc/migrating_v2-v3.md index 7dbdc9181..9d3569470 100644 --- a/doc/migrating_v2-v3.md +++ b/doc/migrating_v2-v3.md @@ -9,10 +9,6 @@ v3 adds many new diagnostic providers to the set of analyzers as well, with gene ## Breaking Changes -- Secure by default: `MessagePackSerializerOptions.Security` defaults to `MessagePackSecurity.UntrustedData` instead of the v2 default of `MessagePackSecurity.TrustedData`. - This may have a small negative perf impact for deserialization. - It may also cause deserialization to fail if the object model requires hashing deserialized data for which no collision resistant hash function is known by the library. - [Learn more about security switches and customization](../README.md#security). - `MessagePackAnalyzer.json` is no longer used to configure the analyzer. Use `GeneratedMessagePackResolverAttribute`, `MessagePackKnownFormatterAttribute` and `MessagePackAssumedFormattableAttribute` instead. - The `mpc` CLI tool is no longer used to generate ahead-of-time (AOT) formatters and resolver. diff --git a/src/MessagePack/MessagePackSecurity.cs b/src/MessagePack/MessagePackSecurity.cs index 3a6715299..ecbd99c99 100644 --- a/src/MessagePack/MessagePackSecurity.cs +++ b/src/MessagePack/MessagePackSecurity.cs @@ -20,7 +20,8 @@ namespace MessagePack public class MessagePackSecurity { /// <summary> - /// Gets an instance preconfigured with settings that omit all protections. Useful for deserializing fully-trusted and valid msgpack sequences. + /// Gets an instance preconfigured with settings that omit hash collision resistance protections. + /// Useful for deserializing fully-trusted and valid msgpack sequences. /// </summary> public static readonly MessagePackSecurity TrustedData = new MessagePackSecurity(); @@ -79,7 +80,7 @@ protected MessagePackSecurity(MessagePackSecurity copyFrom) /// Since stack space occupied may vary by the kind of object deserialized, a conservative value for this property to defend against stack overflow attacks might be 500. /// </para> /// </remarks> - public int MaximumObjectGraphDepth { get; private set; } = int.MaxValue; + public int MaximumObjectGraphDepth { get; private set; } = 500; /// <summary> /// Gets a copy of these options with the <see cref="MaximumObjectGraphDepth"/> property set to a new value. diff --git a/src/MessagePack/MessagePackSerializerOptions.cs b/src/MessagePack/MessagePackSerializerOptions.cs index db48a386d..f750f93df 100644 --- a/src/MessagePack/MessagePackSerializerOptions.cs +++ b/src/MessagePack/MessagePackSerializerOptions.cs @@ -135,7 +135,7 @@ protected MessagePackSerializerOptions(MessagePackSerializerOptions copyFrom) /// <value> /// The default value is to use <see cref="MessagePackSecurity.TrustedData"/>. /// </value> - public MessagePackSecurity Security { get; private set; } = MessagePackSecurity.UntrustedData; + public MessagePackSecurity Security { get; private set; } = MessagePackSecurity.TrustedData; /// <summary> /// Gets a thread-safe pool of reusable <see cref="Sequence{T}"/> objects.
diff --git a/tests/MessagePack.Tests/MessagePackSerializerOptionsTests.cs b/tests/MessagePack.Tests/MessagePackSerializerOptionsTests.cs index 5b995f7b5..0db5157c0 100644 --- a/tests/MessagePack.Tests/MessagePackSerializerOptionsTests.cs +++ b/tests/MessagePack.Tests/MessagePackSerializerOptionsTests.cs @@ -75,8 +75,8 @@ public void Resolver() [Fact] public void Security() { - Assert.Same(MessagePackSecurity.UntrustedData, MessagePackSerializerOptions.Standard.Security); - Assert.Same(MessagePackSecurity.TrustedData, MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.TrustedData).Security); + Assert.Same(MessagePackSecurity.TrustedData, MessagePackSerializerOptions.Standard.Security); + Assert.Same(MessagePackSecurity.UntrustedData, MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData).Security); } [Fact]
TypeAccessException error from non-hash-safe key used in UntrustedData mode Thank you for your hard work. After checking the fix in #2034, deserialization failed. ``` TypeAccessException: No hash-resistant equality comparer available for type: Localization.Runtime.LocalizeKey MessagePack.MessagePackSecurity.GetHashCollisionResistantEqualityComparer[T] () (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.MessagePackSecurity.GetEqualityComparer[T] () (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.Formatters.DictionaryFormatter`2[TKey,TValue].Create (System.Int32 count, MessagePack.MessagePackSerializerOptions options) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.Formatters.DictionaryFormatterBase`5[TKey,TValue,TIntermediate,TEnumerator,TDictionary].Deserialize (MessagePack.MessagePackReader& reader, MessagePack.MessagePackSerializerOptions options) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.GeneratedMessagePackResolver+Localization+Runtime+LocalizeStringsFormatter.Deserialize (MessagePack.MessagePackReader& reader, MessagePack.MessagePackSerializerOptions options) (at MessagePack.SourceGenerator/MessagePack.SourceGenerator.MessagePackGenerator/Formatters.MessagePack.GeneratedMessagePackResolver.Localization.Runtime.LocalizeStringsFormatter.g.cs:48) MessagePack.MessagePackSerializer.Deserialize[T] (MessagePack.MessagePackReader& reader, MessagePack.MessagePackSerializerOptions options) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) Rethrow as MessagePackSerializationException: Failed to deserialize Localization.Runtime.LocalizeStrings value. MessagePack.MessagePackSerializer.Deserialize[T] (MessagePack.MessagePackReader& reader, MessagePack.MessagePackSerializerOptions options) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.MessagePackSerializer.DeserializeFromSequenceAndRewindStreamIfPossible[T] (System.IO.Stream streamToRewind, MessagePack.MessagePackSerializerOptions options, System.Buffers.ReadOnlySequence`1[T] sequence, System.Threading.CancellationToken cancellationToken) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) MessagePack.MessagePackSerializer.Deserialize[T] (System.IO.Stream stream, MessagePack.MessagePackSerializerOptions options, System.Threading.CancellationToken cancellationToken) (at <5f2070410d8a408cacd68ee6662e8e3f>:0) Localization.Runtime.Localizables.LoadText (System.String baseFileName) (at Assets/Plugins/Localization/Runtime/Localizables.cs:418) UnityEngine.Debug:LogException(Exception) Localization.Runtime.Localizables:LoadText(String) (at Assets/Plugins/Localization/Runtime/Localizables.cs:424) Localization.Runtime.Localizables:SetLocaleCore(String) (at Assets/Plugins/Localization/Runtime/Localizables.cs:255) Localization.Runtime.Localizables:SetLocale(String) (at Assets/Plugins/Localization/Runtime/Localizables.cs:228) Localization.Runtime.Localizables:Initialize() (at Assets/Plugins/Localization/Runtime/Localizables.cs:181) Localization.Runtime.Localizables:EnsureInitialized() (at Assets/Plugins/Localization/Runtime/Localizables.cs:156) Localization.Runtime.Localizables:.cctor() (at Assets/Plugins/Localization/Runtime/Localizables.cs:110) CoreSystem.Runtime.Shared.UISystem.Components.CustomTMPText:ApplyLocalizeFontSize() (at Assets/Plugins/CoreSystem/Runtime/Shared/UISystem/Components/CustomTMPText.cs:222) UISystem.Runtime.Components.CustomTMPText:Awake() (at Assets/Plugins/UISystem/Runtime/Components/CustomTMPText.cs:239) ``` ``` using System; using System.Diagnostics; using TextControlSystem.Runtime; using MessagePack; using MessagePack.Formatters; namespace Localization.Runtime { [MessagePackObject] [MessagePackFormatter(typeof(Formatter))] [DebuggerDisplay("\"{ToString()}\"")] public readonly struct LocalizeKey : IEquatable<LocalizeKey> { private const char SEPARATOR = '.'; public string RawText { get; } private int Offset { get; } public int Length { get; } public bool HasCategory => RawText.IndexOf(SEPARATOR, Offset) != -1; public static implicit operator LocalizeKey(string id) => new (id); public static implicit operator StringSlice(LocalizeKey key) => new StringSlice(key.RawText, key.Offset, key.Length); public LocalizeKey(string id) { RawText = id; Offset = 0; Length = RawText.Length; } private LocalizeKey(LocalizeKey id, int startIndex) { RawText = id.RawText; Offset = Math.Min(startIndex, RawText.Length); var endIndex = RawText.IndexOf(SEPARATOR, startIndex); if (endIndex == -1) { endIndex = RawText.Length; } Length = endIndex - Offset; } public LocalizeKey GetTopCategoryId() { return new LocalizeKey(this, Offset); } public LocalizeKey GetSubTextId() { var nextStartIndex = RawText.IndexOf(SEPARATOR, Offset); return new LocalizeKey(this, Math.Min(nextStartIndex + 1, RawText.Length)); } public override string ToString() { return RawText.Substring(Offset, Length); } public override int GetHashCode() { if (RawText == null) return 0; var hashCode = typeof(LocalizeKey).GetHashCode(); for (var i = 0; i < Length; i++) { hashCode ^= RawText[i + Offset]; } return hashCode; } public bool Equals(LocalizeKey other) { if (RawText == other.RawText && Offset == other.Offset && Length == other.Length) { return true; } if (Length != other.Length) { return false; } for (var i = 0; i < Length; i++) { if (RawText[i + Offset] != other.RawText[i + other.Offset]) { return false; } } return true; } public override bool Equals(object obj) { switch (obj) { case LocalizeKey other when Equals(other): case string str when Equals(new LocalizeKey(str)): return true; default: return false; } } internal class Formatter : IMessagePackFormatter<LocalizeKey> { public void Serialize(ref MessagePackWriter writer, LocalizeKey value, MessagePackSerializerOptions options) { // ToolOnly throw new NotImplementedException(); } public LocalizeKey Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.TryReadNil()) { return default; } var formatterResolver = options.Resolver; var str = formatterResolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options); return new LocalizeKey(str); } } public static string GetLabel(string key) { var index = key.LastIndexOf('.'); return index >= 0 ? key[(index + 1)..] : key; } } } ``` When I serialized something with v3.0.238-rc.1 and deserialized it with v3.0.214-rc.1, it was successful, so I think this is due to the fixes in v3.0.214-rc.1 to v3.0.238-rc.1. Unity 6000.0.10f1 Message Pack v3.0.238-rc.1
This is by design because v3 now runs in UntrustedData mode by default. Learn more [in our readme file](https://github.com/MessagePack-CSharp/MessagePack-CSharp/tree/develop?tab=readme-ov-file#security). You can resolve this either by switching back to TrustedData or providing your own secure hash function as documented. Sorry It definitely worked after I changed it to TrustedData Thank you for the explanation @AArnott Ah, I hadn't thought it through deeply enough. I thought UntrustedData would be fine as default because I didn't think these issues would occur. This is too big of a breaking change. Dictionaries with custom keys are quite common. Having it throw exceptions by default is too strict behavior-wise. Is there a way we can make it secure by default while preventing exceptions? ```csharp // minimum example of throw exception var options = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData); var dict = new Dictionary<CustomKey, int> { { new CustomKey(0), 0 } }; var bin = MessagePackSerializer.Serialize(dict, options); var dict2 = MessagePackSerializer.Deserialize<Dictionary<CustomKey, int>>(bin, options); // throws [MessagePackObject] public struct CustomKey(int x) : IEquatable<CustomKey> { [Key(0)] public int X { get; } = x; public bool Equals(CustomKey other) { return this.X == other.X; } public override int GetHashCode() { return X; } } ``` Since a custom GetHashCode is part of the logic, honestly, I feel like it might be fine to just pass it through as-is... > This is too big of a breaking change. Bummer. I guess I'll revert the change. > Is there a way we can make it secure by default while preventing exceptions? This is challenging. Only one idea occurs to me on how we could apply a secure hash to everything automatically. I happen to be exploring it [here](https://github.com/eiriktsarpalis/typeshape-csharp/issues/33#issuecomment-2441413241), which you're welcome to chime in on. This is slightly off topic, but if TrustedData has to be the default in the end, it is a good to set MaximumObjectGraphDepth to 500 on TrustedData.
2024-10-29T14:32:31Z
0.1
['MessagePackSerializerOptionsTests.Security']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2037
ab4a3bb5302a5467bba99d6de4b22fb8cee196a6
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 50565ad91..0ed26db03 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -541,7 +541,8 @@ private bool CollectGeneric(INamedTypeSymbol type) } // collection - if (KnownGenericTypes.TryGetValue(genericTypeDefinitionString, out string formatterFullName)) + string? formatterFullName; + if (KnownGenericTypes.TryGetValue(genericTypeDefinitionString, out formatterFullName)) { foreach (ITypeSymbol item in type.TypeArguments) { @@ -609,6 +610,32 @@ private bool CollectGeneric(INamedTypeSymbol type) return true; } + if (type.AllInterfaces.FirstOrDefault(x => !x.IsUnboundGenericType && x.ConstructUnboundGenericType() is { Name: nameof(ICollection<int>) }) is INamedTypeSymbol collectionIface + && type.InstanceConstructors.Any(ctor => ctor.Parameters.Length == 0)) + { + this.CollectCore(collectionIface.TypeArguments[0]); + + if (isOpenGenericType) + { + return true; + } + else + { + GenericSerializationInfo info = GenericSerializationInfo.Create(type, this.options.Generator.Resolver) with + { + Formatter = new(TypeKind.Class) + { + Container = new NamespaceTypeContainer("MsgPack::Formatters"), + Name = "GenericCollectionFormatter", + TypeParameters = ImmutableArray.Create<GenericTypeParameterInfo>(new("TElement"), new("TCollection")), + TypeArguments = ImmutableArray.Create<QualifiedTypeName>(QualifiedTypeName.Create(collectionIface.TypeArguments[0]), QualifiedTypeName.Create(type)), + }, + }; + + this.collectedGenericInfo.Add(info); + } + } + // Generic types if (type.IsDefinition) {
diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index 857bbf193..61a152b25 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -929,4 +929,22 @@ public partial class SampleObject await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); } + + [Fact] + public async Task SystemCollectionsObjectModelCollection() + { + string testSource = /* lang=c#-test */ """ + using MessagePack; + using System.Collections.ObjectModel; + + [MessagePackObject] + public class A + { + [Key(0)] + public Collection<int> SampleCollection { get; set; } + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs new file mode 100644 index 000000000..a7f360882 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs @@ -0,0 +1,58 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +namespace MessagePack { +partial class GeneratedMessagePackResolver { + + internal sealed class AFormatter : MsgPack::Formatters.IMessagePackFormatter<global::A> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::A value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + writer.WriteArrayHeader(1); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Serialize(ref writer, value.SampleCollection, options); + } + + public global::A Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + var length = reader.ReadArrayHeader(); + var ____result = new global::A(); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + ____result.SampleCollection = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Deserialize(ref reader, options); + break; + default: + reader.Skip(); + break; + } + } + + reader.Depth--; + return ____result; + } + } +} +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..daadab91c --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/SystemCollectionsObjectModelCollection/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,65 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(2) + { + { typeof(global::System.Collections.ObjectModel.Collection<int>), 0 }, + { typeof(global::A), 1 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + switch (closedKey) + { + case 0: return new MsgPack::Formatters.GenericCollectionFormatter<int, global::System.Collections.ObjectModel.Collection<int>>(); + case 1: return new global::MessagePack.GeneratedMessagePackResolver.AFormatter(); + default: return null; // unreachable + }; + } + + return null; + } + } +} + +}
v3: MsgPack003 Analyzer triggering on System.Collections.ObjectModel.Collection #### Bug description The MsgPack003 Analyzer triggers on `System.Collections.ObjectModel.Collection<>` even though it can be handled through `IList<>` etc. #### Repro steps Create the following program ```csharp using MessagePack; using System.Collections.ObjectModel; [MessagePackObject] public partial class A { [Key(0)] public Collection<int> SampleCollection { get; set; } = []; // Error is placed here } ``` #### Expected behavior The analyzer should not report an error. #### Actual behavior The compiler throws an error: | Severity | Code | Description | |----------------|-------------|-------------------------------------------------------------------| | Error | MsgPack003 | Type must be marked with MessagePackObjectAttribute: Collection (https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/master/doc/analyzers/MsgPack003.md) | - Version used: 3.0.233-rc.1 - Runtime: .NET 8 #### Additional context If we extend the program with ```csharp A test = new A(); test.SampleCollection.Add(1); var output = MessagePackSerializer.Serialize(test); var deserialized = MessagePackSerializer.Deserialize<A>(output); if (deserialized.SampleCollection is not [1]) Console.WriteLine("Error"); else Console.WriteLine("Success"); ``` and use the play button in Visual Studio to skip the analyzers the program runs without issues. Source generator output: ```csharp // <auto-generated /> #pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 #pragma warning disable CS8669 // We may leak nullable annotations into generated code. using MsgPack = global::MessagePack; namespace MessagePack { partial class GeneratedMessagePackResolver { internal sealed class AFormatter : MsgPack::Formatters.IMessagePackFormatter<global::A> { public void Serialize(ref MsgPack::MessagePackWriter writer, global::A value, MsgPack::MessagePackSerializerOptions options) { if (value == null) { writer.WriteNil(); return; } MsgPack::IFormatterResolver formatterResolver = options.Resolver; writer.WriteArrayHeader(1); MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Serialize(ref writer, value.SampleCollection, options); } public global::A Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) { if (reader.TryReadNil()) { return null; } options.Security.DepthStep(ref reader); MsgPack::IFormatterResolver formatterResolver = options.Resolver; var length = reader.ReadArrayHeader(); var ____result = new global::A(); for (int i = 0; i < length; i++) { switch (i) { case 0: ____result.SampleCollection = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.ObjectModel.Collection<int>>(formatterResolver).Deserialize(ref reader, options); break; default: reader.Skip(); break; } } reader.Depth--; return ____result; } } } } ```
null
2024-10-23T14:28:43Z
v3.0.238-rc.1
['GenerationTests.SystemCollectionsObjectModelCollection']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2036
168179ef9aba18a16a12df932a9cb818cc545377
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/CodeAnalysisUtilities.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/CodeAnalysisUtilities.cs index b08594f66..94033e030 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/CodeAnalysisUtilities.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/CodeAnalysisUtilities.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; -using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -81,20 +80,20 @@ internal static int GetArity(ITypeSymbol dataType) _ => throw new NotSupportedException(), }; - internal static ImmutableArray<GenericTypeParameterInfo> GetTypeParameters(ITypeSymbol dataType) + internal static ImmutableArray<GenericTypeParameterInfo> GetTypeParameters(ITypeSymbol dataType, ImmutableStack<GenericTypeParameterInfo>? recursionGuard = null) => dataType switch { - INamedTypeSymbol namedType => namedType.TypeParameters.Select(t => new GenericTypeParameterInfo(t)).ToImmutableArray(), + INamedTypeSymbol namedType => namedType.TypeParameters.Select(t => GenericTypeParameterInfo.Create(t, recursionGuard)).ToImmutableArray(), IArrayTypeSymbol arrayType => GetTypeParameters(arrayType.ElementType), ITypeParameterSymbol => ImmutableArray<GenericTypeParameterInfo>.Empty, _ => throw new NotSupportedException(), }; - internal static ImmutableArray<QualifiedTypeName> GetTypeArguments(ITypeSymbol dataType) + internal static ImmutableArray<QualifiedTypeName> GetTypeArguments(ITypeSymbol dataType, ImmutableStack<GenericTypeParameterInfo>? recursionGuard = null) => dataType switch { - INamedTypeSymbol namedType => namedType.TypeArguments.Select(QualifiedTypeName.Create).ToImmutableArray(), - IArrayTypeSymbol arrayType => GetTypeArguments(arrayType.ElementType), + INamedTypeSymbol namedType => namedType.TypeArguments.Select(t => QualifiedTypeName.Create(t, recursionGuard)).ToImmutableArray(), + IArrayTypeSymbol arrayType => GetTypeArguments(arrayType.ElementType, recursionGuard), ITypeParameterSymbol => ImmutableArray<QualifiedTypeName>.Empty, _ => throw new NotSupportedException(), }; diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs index bd85069ae..361959503 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/GenericTypeParameterInfo.cs @@ -11,18 +11,30 @@ public record GenericTypeParameterInfo(string Name) : IComparable<GenericTypePar { private string? constraints; - public GenericTypeParameterInfo(ITypeParameterSymbol typeParameter) + private GenericTypeParameterInfo(ITypeParameterSymbol typeParameter, ImmutableStack<GenericTypeParameterInfo> recursionGuard) : this(typeParameter.Name) { + recursionGuard = recursionGuard.Push(this); + this.HasUnmanagedTypeConstraint = typeParameter.HasUnmanagedTypeConstraint; this.HasReferenceTypeConstraint = typeParameter.HasReferenceTypeConstraint; this.HasValueTypeConstraint = typeParameter.HasValueTypeConstraint; this.HasNotNullConstraint = typeParameter.HasNotNullConstraint; - this.ConstraintTypes = typeParameter.ConstraintTypes.Select(t => QualifiedTypeName.Create(t)).ToImmutableArray(); + this.ConstraintTypes = typeParameter.ConstraintTypes.Select(t => QualifiedTypeName.Create(t, recursionGuard)).ToImmutableArray(); this.HasConstructorConstraint = typeParameter.HasConstructorConstraint; this.ReferenceTypeConstraintNullableAnnotation = typeParameter.ReferenceTypeConstraintNullableAnnotation; } + public static GenericTypeParameterInfo Create(ITypeParameterSymbol typeParameter, ImmutableStack<GenericTypeParameterInfo>? recursionGuard = null) + { + if (recursionGuard?.FirstOrDefault(tpi => tpi.Name == typeParameter.Name) is { } existing) + { + return existing; + } + + return new(typeParameter, recursionGuard ?? ImmutableStack<GenericTypeParameterInfo>.Empty); + } + public string Constraints => this.constraints ??= this.ConstructConstraintString(); public bool HasConstraints => this.Constraints.Length > 0; diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedNamedTypeName.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedNamedTypeName.cs index 5023ed837..97d51d976 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedNamedTypeName.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedNamedTypeName.cs @@ -3,8 +3,6 @@ #pragma warning disable SA1402 // File may only contain a single type -using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -39,7 +37,7 @@ public QualifiedNamedTypeName(TypeKind kind, bool isRecord = false) } [SetsRequiredMembers] - public QualifiedNamedTypeName(INamedTypeSymbol symbol) + public QualifiedNamedTypeName(INamedTypeSymbol symbol, ImmutableStack<GenericTypeParameterInfo>? recursionGuard = null) { this.Name = symbol.Name; this.Kind = symbol.TypeKind; @@ -47,8 +45,8 @@ public QualifiedNamedTypeName(INamedTypeSymbol symbol) this.Container = symbol.ContainingType is { } nesting ? new NestingTypeContainer(new(nesting)) : symbol.ContainingNamespace?.GetFullNamespaceName() is string ns ? new NamespaceTypeContainer(ns) : null; - this.TypeParameters = CodeAnalysisUtilities.GetTypeParameters(symbol); - this.TypeArguments = CodeAnalysisUtilities.GetTypeArguments(symbol); + this.TypeParameters = CodeAnalysisUtilities.GetTypeParameters(symbol, recursionGuard); + this.TypeArguments = CodeAnalysisUtilities.GetTypeArguments(symbol, recursionGuard); this.ReferenceTypeNullableAnnotation = symbol.NullableAnnotation; } diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedTypeName.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedTypeName.cs index d2d5679fe..5eda4f6cf 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedTypeName.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/QualifiedTypeName.cs @@ -2,10 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; -using System.Diagnostics; -using System.Text; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; namespace MessagePack.SourceGenerator.CodeAnalysis; @@ -18,17 +15,21 @@ public abstract record QualifiedTypeName : IComparable<QualifiedTypeName> /// Initializes a new instance of the <see cref="QualifiedTypeName"/> class. /// </summary> /// <param name="symbol">The symbol this instance will identify.</param> - public static QualifiedTypeName Create(ITypeSymbol symbol) + /// <param name="recursionGuard">A stack of objects that serves to avoid infinite recursion when generic constraints are written in terms of themselves.</param> + public static QualifiedTypeName Create(ITypeSymbol symbol, ImmutableStack<GenericTypeParameterInfo>? recursionGuard = null) { return symbol switch { IArrayTypeSymbol arrayType => new QualifiedArrayTypeName(arrayType), - INamedTypeSymbol namedType => new QualifiedNamedTypeName(namedType), + INamedTypeSymbol namedType => new QualifiedNamedTypeName(namedType, recursionGuard), ITypeParameterSymbol typeParam => new TypeParameter(typeParam), _ => throw new NotSupportedException(), }; } + /// <inheritdoc cref="Create(ITypeSymbol, ImmutableStack{GenericTypeParameterInfo}?)"/> + public static QualifiedTypeName Create(ITypeSymbol symbol) => Create(symbol, null); + /// <summary> /// Gets the kind of type. /// </summary> diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 2d7da5a63..50565ad91 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -5,13 +5,11 @@ #pragma warning disable SA1649 // File name should match first type name using System.Collections.Immutable; -using System.ComponentModel; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Operations; namespace MessagePack.SourceGenerator.CodeAnalysis; @@ -1407,7 +1405,7 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) formattedType, isClass: isClass, nestedFormatterRequired: nestedFormatterRequired, - genericTypeParameters: formattedType.IsGenericType ? formattedType.TypeParameters.Select(t => new GenericTypeParameterInfo(t)).ToArray() : Array.Empty<GenericTypeParameterInfo>(), + genericTypeParameters: formattedType.IsGenericType ? formattedType.TypeParameters.Select(t => GenericTypeParameterInfo.Create(t)).ToArray() : Array.Empty<GenericTypeParameterInfo>(), constructorParameters: constructorParameters.ToArray(), isIntKey: isIntKey, members: isIntKey ? intMembers.Values.Select(v => v.Info).ToArray() : stringMembers.Values.Select(v => v.Info).ToArray(),
diff --git a/tests/MessagePack.SourceGenerator.Tests/GenericsFormatterTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenericsFormatterTests.cs index 57ae40582..283622c59 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenericsFormatterTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenericsFormatterTests.cs @@ -493,4 +493,24 @@ public class MyObjectNested }, }.RunAsync(); } + + /// <summary> + /// Asserts that the generator can handle directly recursive generic constraints. + /// </summary> + [Fact] + public async Task RecursiveGenerics_Direct() + { + string testSource = /* lang=c#-test */ """ + using System; + using MessagePack; + + [MessagePackObject] + public class A<T> + where T : IEquatable<A<T>> + { + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter`1.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter`1.g.cs new file mode 100644 index 000000000..1e400bc4e --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter`1.g.cs @@ -0,0 +1,39 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +namespace MessagePack { +partial class GeneratedMessagePackResolver { + + internal sealed class AFormatter<T> : MsgPack::Formatters.IMessagePackFormatter<global::A<T>> + where T : global::System.IEquatable<global::A<T>> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::A<T> value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + writer.WriteArrayHeader(0); + } + + public global::A<T> Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + reader.Skip(); + return new global::A<T>(); + } + } +} +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..186f7d6b2 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecursiveGenerics_Direct/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> openTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) + { + { typeof(global::A<>), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (t.IsGenericType && openTypeLookup.TryGetValue(t.GetGenericTypeDefinition(), out int openKey)) + { + switch (openKey) + { + case 0: return global::System.Activator.CreateInstance(typeof(global::MessagePack.GeneratedMessagePackResolver.AFormatter<>).MakeGenericType(t.GenericTypeArguments)); + default: return null; // unreachable + }; + } + + return null; + } + } +} + +}
SourceGenerator recursion crash from recursive generic type constraints Thank you for your hard work. The fix for #2005 was fixed in v3.0.233-rc.1, so I updated it with NgetForUnity, but I got the following compile error: ``` Stack overflow. at System.Runtime.CompilerServices.CastHelpers.ChkCastAny(Void*, System.Object) at Microsoft.CodeAnalysis.CSharp.Symbols.SymbolExtensions.GetPublicSymbol[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](Microsoft.CodeAnalysis.CSharp.Symbol) at Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.Symbol.Microsoft.CodeAnalysis.ISymbol.get_ContainingNamespace() at MessagePack.SourceGenerator.AnalyzerUtilities.GetFullNamespaceName(Microsoft.CodeAnalysis.INamespaceSymbol) at MessagePack.SourceGenerator.AnalyzerUtilities.GetFullNamespaceName(Microsoft.CodeAnalysis.INamespaceSymbol) at MessagePack.SourceGenerator.AnalyzerUtilities.GetFullNamespaceName(Microsoft.CodeAnalysis.INamespaceSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon><message truncated> ``` Additional information I tried to find the cause by following the setup procedure from the initial Unity project, but it seems that this compilation error occurs when you install addressables from Unity's package manager. ``` "com.unity.addressables": "2.1.0" ``` ``` Stack overflow. at System.Linq.Enumerable.Select[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>, System.Func`2<System.__Canon,System.__Canon>) at System.Linq.ImmutableArrayExtensions.Select[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Immutable.ImmutableArray`1<System.__Canon>, System.Func`2<System.__Canon,System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo..ctor(Microsoft.CodeAnalysis.ITypeParameterSymbol) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities+<>c.<GetTypeParameters>b__9_0(Microsoft.CodeAnalysis.ITypeParameterSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.ToImmutableArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at MessagePack.SourceGenerator.CodeAnalysis.CodeAnalysisUtilities.GetTypeParameters(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedNamedTypeName..ctor(Microsoft.CodeAnalysis.INamedTypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.QualifiedTypeName.Create(Microsoft.CodeAnalysis.ITypeSymbol) at MessagePack.SourceGenerator.CodeAnalysis.GenericTypeParameterInfo+<>c.<.ctor>b__8_0(Microsoft.CodeAnalysis.ITypeSymbol) at System.Linq.Enumerable+SelectArrayIterator`2[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ToArray() at System.Linq.Enumerable.ToArray[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](System.Collections.Generic.IEnumerable`1<System.__Canon>) at System.Collections.Immutable.ImmutableArray.CreateRange[[System.__Canon, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, Public<message truncated> ``` Unity 6000.0.10f1 Message Pack v3.0.233-rc.1
Thanks for reporting. Here is the repro I contrived from the callstack: ```cs using System; using MessagePack; [MessagePackObject] public class A<T> where T : IEquatable<A<T>> { } ```
2024-10-23T13:38:48Z
0.1
['GenericsFormatterTests.RecursiveGenerics_Direct']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2031
4a804d22b6f608fcb04a0dc9a1b51fbd0a52c874
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs index 4832023ec..f117ee557 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs @@ -258,8 +258,8 @@ public static bool TryCreate(INamedTypeSymbol type, [NotNullWhen(true)] out Form public bool ExcludeFromSourceGeneratedResolver { get; init; } public string InstanceExpression => this.InstanceProvidingMember == ".ctor" - ? $"new {this.Name.GetQualifiedName()}()" - : $"{this.Name.GetQualifiedName()}.{this.InstanceProvidingMember}"; + ? $"new {this.Name.GetQualifiedName(genericStyle: GenericParameterStyle.Arguments)}()" + : $"{this.Name.GetQualifiedName(genericStyle: GenericParameterStyle.Arguments)}.{this.InstanceProvidingMember}"; public virtual bool Equals(FormatterDescriptor? other) {
diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index fd305d5a7..ab53b8de5 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -865,4 +865,37 @@ public List<A> Deserialize(ref MessagePackReader reader, MessagePackSerializerOp """; await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); } + + [Fact] + public async Task GenericCustomFormatter() + { + string testSource = /* lang=c#-test */ """ + using System; + using MessagePack; + using MessagePack.Formatters; + + [MessagePackObject(AllowPrivate = true)] + public partial class SampleObject + { + [Key(0)] + [MessagePackFormatter(typeof(ValueTupleFormatter<string>))] + private ValueTuple<string> TupleTest; + } + + public sealed class ValueTupleFormatter<T1> : IMessagePackFormatter<ValueTuple<T1>> + { + public void Serialize(ref MessagePackWriter writer, ValueTuple<T1> value, MessagePackSerializerOptions options) + { + throw new NotImplementedException(); + } + + public ValueTuple<T1> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + throw new NotImplementedException(); + } + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/Formatters.SampleObject.SampleObjectFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/Formatters.SampleObject.SampleObjectFormatter.g.cs new file mode 100644 index 000000000..7f389d0d7 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/Formatters.SampleObject.SampleObjectFormatter.g.cs @@ -0,0 +1,55 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +partial class SampleObject { + + internal sealed class SampleObjectFormatter : MsgPack::Formatters.IMessagePackFormatter<global::SampleObject> + { + private readonly global::ValueTupleFormatter<string> __TupleTestCustomFormatter__ = new global::ValueTupleFormatter<string>(); + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::SampleObject value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + writer.WriteArrayHeader(1); + this.__TupleTestCustomFormatter__.Serialize(ref writer, value.TupleTest, options); + } + + public global::SampleObject Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + var length = reader.ReadArrayHeader(); + var ____result = new global::SampleObject(); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + ____result.TupleTest = this.__TupleTestCustomFormatter__.Deserialize(ref reader, options); + break; + default: + reader.Skip(); + break; + } + } + + reader.Depth--; + return ____result; + } + } +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..ea583ace1 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/GenericCustomFormatter/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) + { + { typeof(global::SampleObject), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + switch (closedKey) + { + case 0: return new global::SampleObject.SampleObjectFormatter(); + default: return null; // unreachable + }; + } + + return null; + } + } +} + +}
custom formatters code source generator error Thank you for your hard work. I was using 2.5.172 originally, but when I upgraded to 3.0.134-beta, the parts using custom formatters stopped working. I thought it might be a problem with how I was using it, so I tried using the sample built-in formatters as shown below, but it doesn't seem to work either. ``` using MessagePack; using MessagePack.Formatters; using System; namespace SP.Runtime { [MessagePackObject] public partial class SampleObject { [Key(0)] public string Name { get; set; } [Key(1)] public int At { get; set; } [Key(2)] [MessagePackFormatter(typeof(ValueTupleFormatter<string>))] private ValueTuple<string> TupleTest; } public sealed class ValueTupleFormatter<T1> : IMessagePackFormatter<ValueTuple<T1>> { public void Serialize(ref MessagePackWriter writer, ValueTuple<T1> value, MessagePackSerializerOptions options) { writer.WriteArrayHeader(1); IFormatterResolver resolver = options.Resolver; resolver.GetFormatterWithVerify<T1>().Serialize(ref writer, value.Item1, options); } public ValueTuple<T1> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.IsNil) { throw new MessagePackSerializationException("Nil"); //throw MessagePackSerializationException.ThrowUnexpectedNilWhileDeserializing<ValueTuple<T1>>(); } else { var count = reader.ReadArrayHeader(); if (count != 1) { throw new MessagePackSerializationException("Invalid ValueTuple count"); } IFormatterResolver resolver = options.Resolver; options.Security.DepthStep(ref reader); try { T1 item1 = resolver.GetFormatterWithVerify<T1>().Deserialize(ref reader, options); return new ValueTuple<T1>(item1); } finally { reader.Depth--; } } } } } ``` .g.cs ``` private readonly global::MessagePack.Formatters.TupleFormatter<string> __TupleTestCustomFormatter__ = new global::MessagePack.Formatters.TupleFormatter<T1>(); ``` Unity 6000.0.10f1 Message Pack v3.0.134-beta
> the parts using custom formatters stopped working. Can you please provide more detail? What "stopped working"? Did you get a compile error? Runtime error? Did it run but serialize as something unexpected? Please provide any error messages you see. > I thought it might be a problem with how I was using it, so I tried using the sample built-in formatters as shown below, but it doesn't seem to work either. It looks like your code snippet is only for the second thing you tried. Providing code for the *first* think you tried would be helpful. Your code snippet uses `Tuple<string>` but then defines a formatter for `ValueTuple<T>`, which doesn't match and makes me suspicious that the failure is on your end. And again, please tell me more about what doesn't work. And BTW, I don't use unity. So if you can provide a sample that doesn't involve unity-specific code, I'm far more likely to be able to diagnose and fix the problem. Sorry This is not a hang but a compilation error I'm very sorry for the mistake in the above description I have corrected the above description I have also updated it to remove any references to Unity I will also share the auto-output code that caused the compilation error Do you understand the reason? ``` // <auto-generated /> #pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 #pragma warning disable CS8669 // We may leak nullable annotations into generated code. using MsgPack = global::MessagePack; namespace SP.Runtime { partial class SampleObject { internal sealed class SampleObjectFormatter : MsgPack::Formatters.IMessagePackFormatter<global::SP.Runtime.SampleObject> { private readonly global::SP.Runtime.ValueTupleFormatter<string> __TupleTestCustomFormatter__ = new global::SP.Runtime.ValueTupleFormatter<T1>(); public void Serialize(ref MsgPack::MessagePackWriter writer, global::SP.Runtime.SampleObject value, MsgPack::MessagePackSerializerOptions options) { if (value == null) { writer.WriteNil(); return; } MsgPack::IFormatterResolver formatterResolver = options.Resolver; writer.WriteArrayHeader(3); MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Serialize(ref writer, value.Name, options); writer.Write(value.At); this.__TupleTestCustomFormatter__.Serialize(ref writer, value.TupleTest, options); } public global::SP.Runtime.SampleObject Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) { if (reader.TryReadNil()) { return null; } options.Security.DepthStep(ref reader); MsgPack::IFormatterResolver formatterResolver = options.Resolver; var length = reader.ReadArrayHeader(); var ____result = new global::SP.Runtime.SampleObject(); for (int i = 0; i < length; i++) { switch (i) { case 0: ____result.Name = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Deserialize(ref reader, options); break; case 1: ____result.At = reader.ReadInt32(); break; case 2: ____result.TupleTest = this.__TupleTestCustomFormatter__.Deserialize(ref reader, options); break; default: reader.Skip(); break; } } reader.Depth--; return ____result; } } } } ``` You _still_ haven't given me the compile error message. A good bug report includes repro instructions, what you expected, and what you actually saw *in detail*. That's why our bug template looks like this: ![image](https://github.com/user-attachments/assets/0426383e-6fe7-406f-8a5c-b2edc0d75428) I was able to repro the problem to get the error message myself. This is what would have been great to include in your original bug description: > 1>C:\temp\ClassLibrary3\ClassLibrary3\obj\Debug\net8.0\MessagePack.SourceGenerator\MessagePack.SourceGenerator.MessagePackGenerator\Formatters.SP.Runtime.SampleObject.SampleObjectFormatter.g.cs(14,141,14,143): error CS0246: The type or namespace name 'T1' could not be found (are you missing a using directive or an assembly reference?) L14 of the generated file: ```cs private readonly global::SP.Runtime.ValueTupleFormatter<string> __TupleTestCustomFormatter__ = new global::SP.Runtime.ValueTupleFormatter<T1>(); ``` **Analysis** The custom type's generated formatter uses the type parameter T1 as the type argument for the custom `ValueTupleFormatter<T1>` instead of the type argument given in the `MessagePackFormatterAttribute`, which was given `ValueTupleFormatter<string>`.
2024-10-22T14:58:12Z
0.1
['GenerationTests.GenericCustomFormatter']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2023
e88df8a75dcfe186e31a9217192d93f667d720b8
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 861720149..e077e5999 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -936,7 +936,14 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) item.Name); if (reportedDiagnostics.Add(diagnostic)) { - this.reportDiagnostic?.Invoke(diagnostic); + if (nonPublicMembersAreSerialized || (item.DeclaredAccessibility & Accessibility.Public) == Accessibility.Public) + { + this.reportDiagnostic?.Invoke(diagnostic); + } + else + { + deferredDiagnosticsForNonPublicMembers.Add(diagnostic); + } } } } @@ -1088,7 +1095,14 @@ void ReportNonUniqueNameIfApplicable(ISymbol item, string stringKey) item.Name); if (reportedDiagnostics.Add(diagnostic)) { - this.reportDiagnostic?.Invoke(diagnostic); + if (nonPublicMembersAreSerialized || (item.DeclaredAccessibility & Accessibility.Public) == Accessibility.Public) + { + this.reportDiagnostic?.Invoke(diagnostic); + } + else + { + deferredDiagnosticsForNonPublicMembers.Add(diagnostic); + } } } }
diff --git a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs index b35682b7a..3a421f7bf 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs @@ -878,6 +878,34 @@ public class B await VerifyCS.VerifyAnalyzerAsync(test); } + [Fact] + public async Task PrivateMembersInBaseClassNeedNoAttribution() + { + string test = /* lang=c#-test */ """ + using MessagePack; + + [MessagePackObject] + public class A + { + private int somePrivateField; + + [Key(0)] + public int SomePublicProp { get; set; } + + private int SomePrivateProp { get; set; } + } + + [MessagePackObject] + public class B : A + { + [Key(1)] + public int SomePublicProp2 { get; set; } + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } + [Fact] public async Task NameCollisionsInForceMapMode() { @@ -903,8 +931,7 @@ public class Derived : Base public new string {|MsgPack018:TwoFaced|}; } - """ - ; + """; await VerifyCS.VerifyAnalyzerAsync(test); }
MsgPack004 Analyzer triggering on not attributed private property on base class eventhough source generator shouldn't include private properties #### Bug description When using non-partial classes forcing the source generator to only include public fields and removing the need to place attributes on non-public properties/fields, the MessagePackAnalyzer complains about not attributed private properties on the base class. #### Repro steps Create the following code: ```csharp [MessagePackObject(AllowPrivate = false)] public class A { [Key(0)] public int SomePublicProp { get; set; } private int somePrivateProp { get; set; } } [MessagePackObject(AllowPrivate = false)] public class B : A // Error is placed here { [Key(1)] public int SomePublicProp2 { get; set; } } ``` #### Expected behavior The project should compile without issues. #### Actual behavior The compiler throws an error: | Severity | Code | Description | |----------------|-------------|-------------------------------------------------------------------| | Error | MsgPack0004 | Properties and fields of base types of MessagePackObject-attributed types require either KeyAttribute or IgnoreMemberAttribute: global::A.somePrivateProp | - Version used: 3.0.208-rc-0001 - Runtime: .NET 8 #### Additional context The source generator seems to generate the intended formatter without issues ```csharp // <auto-generated /> #pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 #pragma warning disable CS8669 // We may leak nullable annotations into generated code. using MsgPack = global::MessagePack; namespace MessagePack { partial class GeneratedMessagePackResolver { internal sealed class BFormatter : MsgPack::Formatters.IMessagePackFormatter<global::B> { public void Serialize(ref MsgPack::MessagePackWriter writer, global::B value, MsgPack::MessagePackSerializerOptions options) { if (value == null) { writer.WriteNil(); return; } writer.WriteArrayHeader(2); writer.Write(value.SomePublicProp); writer.Write(value.SomePublicProp2); } public global::B Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) { if (reader.TryReadNil()) { return null; } options.Security.DepthStep(ref reader); var length = reader.ReadArrayHeader(); var ____result = new global::B(); for (int i = 0; i < length; i++) { switch (i) { case 0: ____result.SomePublicProp = reader.ReadInt32(); break; case 1: ____result.SomePublicProp2 = reader.ReadInt32(); break; default: reader.Skip(); break; } } reader.Depth--; return ____result; } } } } ```
null
2024-10-18T23:14:30Z
0.1
['MsgPack00xAnalyzerTests.PrivateMembersInBaseClassNeedNoAttribution']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2022
f5e104eec56d53df064126de8dd5bd4e533e7ea8
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs index 4d8567fef..4832023ec 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs @@ -218,6 +218,12 @@ public record FormatterDescriptor(QualifiedNamedTypeName Name, string? InstanceP /// <returns><see langword="true"/> if <paramref name="type"/> represents a formatter.</returns> public static bool TryCreate(INamedTypeSymbol type, [NotNullWhen(true)] out FormatterDescriptor? formatter) { + if (type.IsAbstract) + { + formatter = null; + return false; + } + var formattedTypes = AnalyzerUtilities.SearchTypeForFormatterImplementations(type) .Select(i => new FormattableType(i, type.ContainingAssembly))
diff --git a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs index 54d8dda01..b35682b7a 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs @@ -908,4 +908,27 @@ public class Derived : Base await VerifyCS.VerifyAnalyzerAsync(test); } + + [Fact] + public async Task AbstractFormatterDoesNotAttractAttention() + { + string test = /* lang=c#-test */ """ + using MessagePack; + using MessagePack.Formatters; + + public abstract class AbstractFormatter1 : IMessagePackFormatter<object> + { + public abstract void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); + public abstract object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); + } + + public abstract class AbstractFormatter2 : IMessagePackFormatter<object> + { + public abstract void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options); + public abstract object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options); + } + """; + + await VerifyCS.VerifyAnalyzerAsync(test); + } }
MsgPack013 should not report diagnostics on abstract classes The following class declaration produced an MsgPack013 diagnostic: ```cs public abstract class Deserializer : IMessagePackFormatter<object?> ``` This doesn't make sense though because as an abstract type, the resolver could never use it anyway. `MsgPack009` also mis-fires by counting abstract classes as bona fide formatters.
null
2024-10-18T23:00:15Z
0.1
['MsgPack00xAnalyzerTests.AbstractFormatterDoesNotAttractAttention']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-2002
85c44d648799d6ccaee10489136ec504754f9a10
diff --git a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs index 0db4bbda0..f22b5f18f 100644 --- a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs +++ b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs @@ -166,7 +166,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer title: "Deserializing constructors", category: Category, messageFormat: "Deserializing constructor parameter count mismatch", - description: "Constructor parameter count must meet or exceed the number of serialized members or the highest key index.", + description: "The deserializing constructor parameter count must meet or exceed the number of serialized members.", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 4a84b7afa..80d24ad91 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -5,6 +5,7 @@ #pragma warning disable SA1649 // File name should match first type name using System.Collections.Immutable; +using System.ComponentModel; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; @@ -682,6 +683,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr { var isClass = !formattedType.IsValueType; bool nestedFormatterRequired = false; + List<IPropertySymbol> nestedFormatterRequiredIfPropertyIsNotSetByDeserializingCtor = new(); AttributeData? contractAttr = formattedType.GetAttributes().FirstOrDefault(x => x.AttributeClass.ApproximatelyEqual(this.typeReferences.MessagePackObjectAttribute)); @@ -875,7 +877,10 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr nonPublicMembersAreSerialized |= (item.DeclaredAccessibility & Accessibility.Public) != Accessibility.Public; nestedFormatterRequired |= item.GetMethod is not null && IsPartialTypeRequired(item.GetMethod.DeclaredAccessibility); - nestedFormatterRequired |= item.SetMethod is not null && IsPartialTypeRequired(item.SetMethod.DeclaredAccessibility); + if (item.SetMethod is not null && IsPartialTypeRequired(item.SetMethod.DeclaredAccessibility)) + { + nestedFormatterRequiredIfPropertyIsNotSetByDeserializingCtor.Add(item); + } var intKey = key is { Value: int intKeyValue } ? intKeyValue : default(int?); var stringKey = key is { Value: string stringKeyValue } ? stringKeyValue : default; @@ -1062,6 +1067,9 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr nestedFormatterRequired |= IsPartialTypeRequired(ctor.DeclaredAccessibility); var constructorLookupDictionary = stringMembers.ToLookup(x => x.Value.Info.Name, x => x, StringComparer.OrdinalIgnoreCase); + IReadOnlyDictionary<int, (MemberSerializationInfo Info, ITypeSymbol TypeSymbol)> ctorParamIndexIntMembersDictionary = intMembers + .OrderBy(x => x.Key).Select((x, i) => (Key: x.Value, Index: i)) + .ToDictionary(x => x.Index, x => x.Key); do { constructorParameters.Clear(); @@ -1070,7 +1078,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr { if (isIntKey) { - if (intMembers.TryGetValue(ctorParamIndex, out (MemberSerializationInfo Info, ITypeSymbol TypeSymbol) member)) + if (ctorParamIndexIntMembersDictionary.TryGetValue(ctorParamIndex, out (MemberSerializationInfo Info, ITypeSymbol TypeSymbol) member)) { if (this.compilation.ClassifyConversion(member.TypeSymbol, item.Type) is { IsImplicit: true } && member.Info.IsReadable) { @@ -1204,6 +1212,13 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr return null; } + // If any property had a private setter and does not appear in the deserializing constructor signature, + // we'll need a nested formatter. + foreach (IPropertySymbol property in nestedFormatterRequiredIfPropertyIsNotSetByDeserializingCtor) + { + nestedFormatterRequired |= !constructorParameters.Any(m => m.Name == property.Name); + } + if (nestedFormatterRequired && nonPublicMembersAreSerialized) { // If the data type or any nesting types are not declared with partial, we cannot emit the formatter as a nested type within the data type
diff --git a/tests/MessagePack.SourceGenerator.ExecutionTests/DeserializingConstructorStartsWithIdx1.cs b/tests/MessagePack.SourceGenerator.ExecutionTests/DeserializingConstructorStartsWithIdx1.cs new file mode 100644 index 000000000..d0f0857b9 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.ExecutionTests/DeserializingConstructorStartsWithIdx1.cs @@ -0,0 +1,14 @@ +// Copyright (c) All contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +[MessagePackObject] +public class DeserializingConstructorStartsWithIdx1 : IEquatable<DeserializingConstructorStartsWithIdx1> +{ + [Key(1)] // 1 instead of 0. Works on v2. Test case from https://github.com/MessagePack-CSharp/MessagePack-CSharp/issues/1993 + public string Name { get; } + + [SerializationConstructor] + public DeserializingConstructorStartsWithIdx1(string name) => Name = name; + + public bool Equals(DeserializingConstructorStartsWithIdx1? other) => other is not null && this.Name == other.Name; +} diff --git a/tests/MessagePack.SourceGenerator.ExecutionTests/ExecutionTests.cs b/tests/MessagePack.SourceGenerator.ExecutionTests/ExecutionTests.cs index 320838c58..a3dc5c411 100644 --- a/tests/MessagePack.SourceGenerator.ExecutionTests/ExecutionTests.cs +++ b/tests/MessagePack.SourceGenerator.ExecutionTests/ExecutionTests.cs @@ -64,6 +64,12 @@ public void ClassWithRequiredMembers() this.AssertRoundtrip(new HasRequiredMembers { A = 1, B = 4, C = 5, D = 6 }); } + [Fact] + public void DeserializingConstructorStartsWithIdx1() + { + this.AssertRoundtrip(new DeserializingConstructorStartsWithIdx1("foo")); + } + #if !FORCE_MAP_MODE // forced map mode simply doesn't support private fields at all as it only notices internal and public members. [Fact] public void PrivateFieldIsSerialized() diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index bdea9aee6..05e7a8c9d 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -672,4 +672,24 @@ class A { ExpectedDiagnostics = { DiagnosticResult.CompilerError("MsgPack007").WithLocation(0) }, }.RunDefaultAsync(this.testOutputHelper); } + + [Fact] + public async Task NoPrivateAccessNeeded() + { + // Test case came from https://github.com/MessagePack-CSharp/MessagePack-CSharp/issues/1993 + string testSource = /* lang=c#-test */ """ + using MessagePack; + + [MessagePackObject] + public class Test3 + { + [Key(0)] + public string Name { get; private set; } + + [SerializationConstructor] + public Test3(string name) => Name = name; + } + """; + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/Formatters.MessagePack.GeneratedMessagePackResolver.Test3Formatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/Formatters.MessagePack.GeneratedMessagePackResolver.Test3Formatter.g.cs new file mode 100644 index 000000000..145490a71 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/Formatters.MessagePack.GeneratedMessagePackResolver.Test3Formatter.g.cs @@ -0,0 +1,59 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +namespace MessagePack { +partial class GeneratedMessagePackResolver { + + internal sealed class Test3Formatter : MsgPack::Formatters.IMessagePackFormatter<global::Test3> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::Test3 value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + writer.WriteArrayHeader(1); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Serialize(ref writer, value.Name, options); + } + + public global::Test3 Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + var length = reader.ReadArrayHeader(); + var __Name__ = default(string); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + __Name__ = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Deserialize(ref reader, options); + break; + default: + reader.Skip(); + break; + } + } + + var ____result = new global::Test3(__Name__); + reader.Depth--; + return ____result; + } + } +} +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..c7531dfa5 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/NoPrivateAccessNeeded/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new global::System.Collections.Generic.Dictionary<global::System.Type, int>(1) + { + { typeof(global::Test3), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + switch (closedKey) + { + case 0: return new global::MessagePack.GeneratedMessagePackResolver.Test3Formatter(); + default: return null; // unreachable + }; + } + + return null; + } + } +} + +}
Analyzers (and possibly AOT) adds requirement for Key/ctor ordering I have tried MessagePack `3.0.134-beta` on my project. So far new analyzer detections force a very strict style that requires a lot of refactoring to get it going. This might be not the best code, but on large code base refactoring is always a matter of time you can spend for this. Analyzer for `2.5.172` was fine with that code. Questions: 1. `Test1` - Why are we forced to start with `0` for constructor params? For me it is not always the case and I cannot change that. 2. `Test2`, `Test3` - Requirement to make `partial` class doesn't make sense. Code gen still has to use constructor. 3. `Test4` - Maybe analyzer should detect private member not annotated with attributes only when class is `partial`? Common patterns detected: ```cs [MessagePackObject] public class Test1 { [Key(1)] //[Key("1")]// works fine with string keys public string Name { get; } [SerializationConstructor] public Test1(string name) => Name = name; } [MessagePackObject] public class Test2 { private readonly string _name; [Key(0)] public string Name => _name; [SerializationConstructor] public Test2(string name) => _name = name; } // another way Test2 can implemented [MessagePackObject] public class Test3 { [Key(0)] public string Name { get; private set; } [SerializationConstructor] public Test3(string name) => Name = name; } [MessagePackObject] public class Test4 { private int? _cachedValue;// not serialized by design [Key(0)] public string Name { get; set; } } ```
Thanks for trying out the beta and sharing your feedback. This is great to hear as we're closing down v3 and we want to identify adoption blockers. > Test1 - Why are we forced to start with 0 for constructor params? For me it is not always the case and I cannot change that. I don't recall intentionally changing this behavior, but as I'm surprised that what you had worked in the first place, I may have inadvertently made the change. I thought for ordinal indexed members, the indexes had to match the constructor parameter positions. And apparently the diagnostic is simply in error, because on v3 it works as you have it written. But that's using the `DynamicObjectResolver`. Maybe the AOT source generation has more strict requirements. I'll have to look into that. > Test2, Test3 - Requirement to make partial class doesn't make sense. Code gen still has to use constructor. Quite right. And I'm pleased to say that I just recently made fixes that makes these tests work the way you expect without any warnings. (#1990) > Test4 - Maybe analyzer should detect private member not annotated with attributes only when class is partial? Also fixed by #1990. Not the way you propose, but the attributes are only required on public members by default. Once you start annotating non-public members, or use `[MessagePackObject(AllowPrivate=true)]`, diagnostics for the non-public members start asking for you to apply them to all private members. So all up, not too bad. Just Test1 survives as an issue to be fixed. :) Actually, Test3 still repros. I wasn't testing with the analyzers turned on, because evidently we have a bug where the analyzers aren't always brought in. But I agree we should get that fixed too.
2024-10-15T18:05:41Z
0.1
['ExecutionTests.DeserializingConstructorStartsWithIdx1', 'GenerationTests.NoPrivateAccessNeeded']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1962
b0e770756434993da40e722102833e4029f9c623
diff --git a/src/MessagePack.Annotations/Attributes.cs b/src/MessagePack.Annotations/Attributes.cs index 0d5ad5d2d..5072776fd 100644 --- a/src/MessagePack.Annotations/Attributes.cs +++ b/src/MessagePack.Annotations/Attributes.cs @@ -14,7 +14,7 @@ public class MessagePackObjectAttribute : Attribute /// <summary> /// Gets a value indicating whether to automatically serialize all internal and public fields and properties using their property name as the key in a map. /// </summary> - public bool KeyAsPropertyName { get; private set; } + public bool KeyAsPropertyName { get; } /// <summary> /// Initializes a new instance of the <see cref="MessagePackObjectAttribute"/> class. @@ -46,9 +46,9 @@ public MessagePackObjectAttribute(bool keyAsPropertyName = false) [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class KeyAttribute : Attribute { - public int? IntKey { get; private set; } + public int? IntKey { get; } - public string? StringKey { get; private set; } + public string? StringKey { get; } public KeyAttribute(int x) { @@ -72,12 +72,12 @@ public class UnionAttribute : Attribute /// <summary> /// Gets the distinguishing value that identifies a particular subtype. /// </summary> - public int Key { get; private set; } + public int Key { get; } /// <summary> /// Gets the derived or implementing type. /// </summary> - public Type SubType { get; private set; } + public Type SubType { get; } /// <summary> /// Initializes a new instance of the <see cref="UnionAttribute"/> class. @@ -110,9 +110,9 @@ public class SerializationConstructorAttribute : Attribute [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = true)] public class MessagePackFormatterAttribute : Attribute { - public Type FormatterType { get; private set; } + public Type FormatterType { get; } - public object?[]? Arguments { get; private set; } + public object?[]? Arguments { get; } public MessagePackFormatterAttribute(Type formatterType) { diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index d70aab0c4..aad9b3c6d 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -721,7 +721,8 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr foreach (IPropertySymbol item in formattedType.GetAllMembers().OfType<IPropertySymbol>()) { - if (item.GetAttributes().Any(x => (x.AttributeClass.ApproximatelyEqual(this.typeReferences.IgnoreAttribute) || x.AttributeClass?.Name == this.typeReferences.IgnoreDataMemberAttribute?.Name)) || + ImmutableArray<AttributeData> attributes = item.GetAttributes(); + if (attributes.Any(x => (x.AttributeClass.ApproximatelyEqual(this.typeReferences.IgnoreAttribute) || x.AttributeClass?.Name == this.typeReferences.IgnoreDataMemberAttribute?.Name)) || item.IsStatic || item.IsOverride || item.IsImplicitlyDeclared || @@ -737,10 +738,13 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr continue; } + AttributeData? keyAttribute = attributes.FirstOrDefault(attributes => attributes.AttributeClass.ApproximatelyEqual(this.typeReferences.KeyAttribute)); + string stringKey = keyAttribute?.ConstructorArguments.Length == 1 && keyAttribute.ConstructorArguments[0].Value is string name ? name : item.Name; + includesPrivateMembers |= item.GetMethod is not null && !IsAllowedAccessibility(item.GetMethod.DeclaredAccessibility); includesPrivateMembers |= item.SetMethod is not null && !IsAllowedAccessibility(item.SetMethod.DeclaredAccessibility); FormatterDescriptor? specialFormatter = GetSpecialFormatter(item); - var member = new MemberSerializationInfo(true, isWritable, isReadable, hiddenIntKey++, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); + MemberSerializationInfo member = new(true, isWritable, isReadable, hiddenIntKey++, stringKey, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); stringMembers.Add(member.StringKey, (member, item.Type)); if (specialFormatter is null) @@ -751,7 +755,8 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr foreach (IFieldSymbol item in formattedType.GetAllMembers().OfType<IFieldSymbol>()) { - if (item.GetAttributes().Any(x => (x.AttributeClass.ApproximatelyEqual(this.typeReferences.IgnoreAttribute) || x.AttributeClass?.Name == this.typeReferences.IgnoreDataMemberAttribute?.Name)) || + ImmutableArray<AttributeData> attributes = item.GetAttributes(); + if (attributes.Any(x => (x.AttributeClass.ApproximatelyEqual(this.typeReferences.IgnoreAttribute) || x.AttributeClass?.Name == this.typeReferences.IgnoreDataMemberAttribute?.Name)) || item.IsStatic || item.IsImplicitlyDeclared || item.DeclaredAccessibility < minimumAccessibility) @@ -759,8 +764,11 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr continue; } + AttributeData? keyAttribute = attributes.FirstOrDefault(attributes => attributes.AttributeClass.ApproximatelyEqual(this.typeReferences.KeyAttribute)); + string stringKey = keyAttribute?.ConstructorArguments.Length == 1 && keyAttribute.ConstructorArguments[0].Value is string name ? name : item.Name; + FormatterDescriptor? specialFormatter = GetSpecialFormatter(item); - var member = new MemberSerializationInfo(false, IsWritable: !item.IsReadOnly, IsReadable: true, hiddenIntKey++, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); + MemberSerializationInfo member = new(false, IsWritable: !item.IsReadOnly, IsReadable: true, hiddenIntKey++, stringKey, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); stringMembers.Add(member.StringKey, (member, item.Type)); if (specialFormatter is null) {
diff --git a/tests/MessagePack.SourceGenerator.MapModeExecutionTests/StringKeyOverrideTests.cs b/tests/MessagePack.SourceGenerator.MapModeExecutionTests/StringKeyOverrideTests.cs new file mode 100644 index 000000000..48858e4d3 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.MapModeExecutionTests/StringKeyOverrideTests.cs @@ -0,0 +1,83 @@ +// Copyright (c) All contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +public class StringKeyOverrideTests(ITestOutputHelper logger) +{ + [Fact] + public void KeyOnSettableProperty() + { + SettableProperty original = new() { TheMessage = "hi" }; + var deserialized = AssertSerializedName(original); + Assert.Equal(original.TheMessage, deserialized.TheMessage); + } + + [Fact] + public void KeyOnReadOnlyProperty() + { + ReadOnlyProperty original = new("hi"); + var deserialized = AssertSerializedName(original); + Assert.Equal(original.TheMessage, deserialized.TheMessage); + } + + [Fact] + public void KeyOnReadOnlyField() + { + ReadOnlyField original = new("hi"); + var deserialized = AssertSerializedName(original); + Assert.Equal(original.TheMessage, deserialized.TheMessage); + } + + [Fact] + public void KeyOnSettableField() + { + SettableField original = new() { TheMessage = "hi" }; + var deserialized = AssertSerializedName(original); + Assert.Equal(original.TheMessage, deserialized.TheMessage); + } + + private T AssertSerializedName<T>(T value) + { + byte[] msgpack = MessagePackSerializer.Serialize(value, MessagePackSerializerOptions.Standard); + + logger.WriteLine(MessagePackSerializer.ConvertToJson(msgpack)); + + MessagePackReader reader = new(msgpack); + Assert.Equal(1, reader.ReadMapHeader()); + Assert.Equal("message", reader.ReadString()); + return MessagePackSerializer.Deserialize<T>(msgpack, MessagePackSerializerOptions.Standard); + } + + [MessagePackObject] + public struct ReadOnlyProperty + { + [Key("message")] + public string TheMessage { get; } + + [SerializationConstructor] + public ReadOnlyProperty(string theMessage) => this.TheMessage = theMessage; + } + + [MessagePackObject] + public struct SettableProperty + { + [Key("message")] + public string TheMessage { get; set; } + } + + [MessagePackObject] + public struct ReadOnlyField + { + [Key("message")] + public readonly string TheMessage; + + [SerializationConstructor] + public ReadOnlyField(string theMessage) => this.TheMessage = theMessage; + } + + [MessagePackObject] + public struct SettableField + { + [Key("message")] + public string TheMessage; + } +}
Array of arrays member in MessagePackObject-annotated class causes build failure with NuGet package version >=v3.0.111-alpha #### Bug description Trying to build a project that has a class with an array of arrays member fails when the >=v3.0.111-alpha NuGet package is used. v3.0.54-alpha is the last working v3 version. What's strange to me, is that I tried to bisect the commit where this broke, checked out the v3.0.134-beta tag, added it as a `ProjectReference`, and the build succeeded. So this happens only with the NuGet package, and I have no idea how to dig further. To summarize what I observerd: - v3.0.54-alpha is the last version not affected by this. - v2.x.x versions are not affected. - The build error happens only with the NuGet package. - I have observed the build failure only with array of arrays (simple (`[]`), and multidimensional (`[,]`) arrays work as expected). #### Repro steps The following code can be used to reproduce the build failure: Program.cs: ```c# using MessagePack; A a = new(); [MessagePackObject] public class A { public int[][]? M { get; set; } }; ``` MessagePackTest.csproj: ```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <!-- Build fails with the NuGet package --> <PackageReference Include="MessagePack" Version="3.0.134-beta" /> <!-- Build succeeds with referencing the checked-out 3.0.134-beta tag --> <!-- <ProjectReference Include="..\MessagePack-CSharp\src\MessagePack\MessagePack.csproj" /> --> </ItemGroup> </Project> ``` #### Expected behavior `dotnet build` succeeds. #### Actual behavior `dotnet build` fails with the following error message: ``` /home/sghctoma/projects/misc/dotnet/MessagePackTest/obj/Debug/net8.0/MessagePack.SourceGenerator/MessagePack.SourceGenerator.MessagePackGenerator/MessagePack.GeneratedMessagePackResolver.g.cs(47,21): error CS1001: Identifier expected [/home/sghctoma/projects/misc/dotnet/MessagePackTest/MessagePackTest.csproj] ``` The file the message refers to does not even exist. In fact, there's no `obj/Debug/net8.0/MessagePack.SourceGenerator` folder. - Version used: v3.0.111-alpha, v3.0.129-beta, v3.0.134-beta - Runtime: .NET Core 8.0
This seems to repro on 3.0.54-alpha too, for me.
2024-09-25T15:06:37Z
0.1
['StringKeyOverrideTests.KeyOnSettableProperty', 'StringKeyOverrideTests.KeyOnReadOnlyProperty', 'StringKeyOverrideTests.KeyOnReadOnlyField', 'StringKeyOverrideTests.KeyOnSettableField']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1910
2b3779b5d3a6032c372dc6fd1b7e85c6efe4bf27
diff --git a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/FormatterCodeFixProvider.cs b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/FormatterCodeFixProvider.cs index 3c52fa540..9e37611da 100644 --- a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/FormatterCodeFixProvider.cs +++ b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/FormatterCodeFixProvider.cs @@ -1,6 +1,8 @@ // Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Diagnostics.CodeAnalysis; + namespace MessagePack.Analyzers.CodeFixes; [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SimpleBaseTypeSyntax)), Shared] @@ -75,9 +77,21 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) private static Task<Document> AddPartialModifierAsync(Document document, SyntaxNode syntaxRoot, BaseTypeDeclarationSyntax typeDecl, Diagnostic diagnostic, CancellationToken cancellationToken) { - SyntaxNode? modifiedSyntax = syntaxRoot.ReplaceNode( - typeDecl, - typeDecl.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword))); + SyntaxNode? modifiedSyntax = syntaxRoot; + if (TryAddPartialModifier(typeDecl, out BaseTypeDeclarationSyntax? modified)) + { + modifiedSyntax = modifiedSyntax.ReplaceNode(typeDecl, modified); + } + + foreach (Location addlLocation in diagnostic.AdditionalLocations) + { + BaseTypeDeclarationSyntax? addlType = modifiedSyntax.FindNode(addlLocation.SourceSpan) as BaseTypeDeclarationSyntax; + if (addlType is not null && TryAddPartialModifier(addlType, out modified)) + { + modifiedSyntax = modifiedSyntax.ReplaceNode(addlType, modified); + } + } + document = document.WithSyntaxRoot(modifiedSyntax); return Task.FromResult(document); } @@ -145,4 +159,16 @@ private static SyntaxTokenList AddInternalVisibility(SyntaxTokenList modifiers) SyntaxToken ReplaceModifier(SyntaxToken original) => internalKeywordToken.WithLeadingTrivia(original.LeadingTrivia).WithTrailingTrivia(original.TrailingTrivia); SyntaxTokenList ReplaceModifierInList(int index) => modifiers.Replace(modifiers[index], ReplaceModifier(modifiers[index])); } + + private static bool TryAddPartialModifier(BaseTypeDeclarationSyntax typeDeclaration, [NotNullWhen(true)] out BaseTypeDeclarationSyntax? modified) + { + if (typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword)) + { + modified = null; + return false; + } + + modified = typeDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); + return true; + } } diff --git a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs index 1c2d5e612..fe898a4d8 100644 --- a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs +++ b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs @@ -25,10 +25,10 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer internal const string Category = "Usage"; - internal const string MessagePackObjectAttributeShortName = Constants.MessagePackObjectAttributeName; - internal const string KeyAttributeShortName = "KeyAttribute"; - internal const string IgnoreShortName = "IgnoreMemberAttribute"; - internal const string IgnoreDataMemberShortName = "IgnoreDataMemberAttribute"; + public const string MessagePackObjectAttributeShortName = Constants.MessagePackObjectAttributeName; + public const string KeyAttributeShortName = "KeyAttribute"; + public const string IgnoreShortName = "IgnoreMemberAttribute"; + public const string IgnoreDataMemberShortName = "IgnoreDataMemberAttribute"; private const string InvalidMessagePackObjectTitle = "MessagePackObject validation"; private const DiagnosticSeverity InvalidMessagePackObjectSeverity = DiagnosticSeverity.Error; @@ -239,8 +239,8 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer id: PartialTypeRequiredId, title: "Partial type required", category: Category, - messageFormat: "Types with private, serializable members must be declared as partial", - description: "When a data type has serializable members that may only be accessible to the class itself (e.g. private or protected members), the type must be declared as partial to allow source generation of the formatter as a nested type.", + messageFormat: "Types with private, serializable members must be declared as partial, including nesting types", + description: "When a data type has serializable members that may only be accessible to the class itself (e.g. private or protected members), the type must be declared as partial to allow source generation of the formatter as a nested type. When a data type is itself a nested type, its declaring types must also be partial.", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(PartialTypeRequiredId)); diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 587545fd1..38a2f5020 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -1093,9 +1093,13 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr // If the data type or any nesting types are not declared with partial, we cannot emit the formatter as a nested type within the data type // as required in order to access the private members. bool anyNonPartialTypesFound = false; - foreach (BaseTypeDeclarationSyntax? decl in FindNonPartialTypes(formattedType)) + BaseTypeDeclarationSyntax[] nonPartialTypes = FindNonPartialTypes(formattedType).ToArray(); + if (nonPartialTypes.Length > 0) { - this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.PartialTypeRequired, decl.Identifier.GetLocation())); + BaseTypeDeclarationSyntax? targetType = formattedType.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as BaseTypeDeclarationSyntax; + Location? primaryLocation = targetType?.Identifier.GetLocation(); + Location[]? addlLocations = nonPartialTypes.Where(t => t != targetType).Select(t => t.Identifier.GetLocation()).ToArray(); + this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.PartialTypeRequired, primaryLocation, (IEnumerable<Location>?)addlLocations)); anyNonPartialTypesFound = true; } diff --git a/src/MessagePack.SourceGenerator/Properties/AssemblyInfo.cs b/src/MessagePack.SourceGenerator/Properties/AssemblyInfo.cs deleted file mode 100644 index 9ae3dbb6b..000000000 --- a/src/MessagePack.SourceGenerator/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) All contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("MessagePack.Analyzers.CodeFixes, PublicKey=" + ThisAssembly.PublicKey)] -[assembly: InternalsVisibleTo("MessagePack.Analyzers.CodeFixes.Unity, PublicKey=" + ThisAssembly.PublicKey)]
diff --git a/tests/MessagePack.SourceGenerator.Tests/MsgPack011PartialTypeRequiredTests.cs b/tests/MessagePack.SourceGenerator.Tests/MsgPack011PartialTypeRequiredTests.cs index 258bbdc1e..82f94ea3a 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MsgPack011PartialTypeRequiredTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MsgPack011PartialTypeRequiredTests.cs @@ -1,6 +1,8 @@ // Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using MessagePack.SourceGenerator.Analyzers; +using Microsoft.CodeAnalysis.Testing; using VerifyCS = CSharpCodeFixVerifier<MessagePack.SourceGenerator.Analyzers.MsgPack00xMessagePackAnalyzer, MessagePack.Analyzers.CodeFixes.FormatterCodeFixProvider>; public class MsgPack011PartialTypeRequiredTests @@ -34,4 +36,102 @@ partial class MyObject await VerifyCS.VerifyCodeFixAsync(testSource, fixedSource); } + + [Fact] + public async Task NestedPartialTypeRequiresPartialSelfAndDeclaringType() + { + string testSource = """ + using MessagePack; + + [MessagePackObject] + class {|#1:Outer|} + { + [MessagePackObject] + internal class {|#0:Inner|} + { + [Key(0)] + private Outer Value { get; set; } + } + } + """; + + string fixedSource = """ + using MessagePack; + + [MessagePackObject] + partial class Outer + { + [MessagePackObject] + internal partial class Inner + { + [Key(0)] + private Outer Value { get; set; } + } + } + """; + + await new VerifyCS.Test + { + TestState = + { + Sources = { testSource }, + ExpectedDiagnostics = + { + DiagnosticResult.CompilerError(MsgPack00xMessagePackAnalyzer.PartialTypeRequired.Id) + .WithLocation(0) + .WithLocation(1), + }, + }, + FixedCode = fixedSource, + }.RunAsync(); + } + + [Fact] + public async Task NestedPartialTypeRequiresPartialDeclaringType() + { + string testSource = """ + using MessagePack; + + [MessagePackObject] + class {|#1:Outer|} + { + [MessagePackObject] + internal partial class {|#0:Inner|} + { + [Key(0)] + private Outer Value { get; set; } + } + } + """; + + string fixedSource = """ + using MessagePack; + + [MessagePackObject] + partial class Outer + { + [MessagePackObject] + internal partial class Inner + { + [Key(0)] + private Outer Value { get; set; } + } + } + """; + + await new VerifyCS.Test + { + TestState = + { + Sources = { testSource }, + ExpectedDiagnostics = + { + DiagnosticResult.CompilerError(MsgPack00xMessagePackAnalyzer.PartialTypeRequired.Id) + .WithLocation(0) + .WithLocation(1), + }, + }, + FixedCode = fixedSource, + }.RunAsync(); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/PrivateMemberAccessTests.cs b/tests/MessagePack.SourceGenerator.Tests/PrivateMemberAccessTests.cs index b9c001256..59f99d5f7 100644 --- a/tests/MessagePack.SourceGenerator.Tests/PrivateMemberAccessTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/PrivateMemberAccessTests.cs @@ -90,10 +90,10 @@ public async Task FormatterForClassWithPrivateMembers_Nested_NonPartialTypes(str using System; using MessagePack; - {{type}} {|MsgPack011:Outer|} + {{type}} Outer { [MessagePackObject] - internal partial {{type}} MyObject + internal partial {{type}} {|MsgPack011:MyObject|} { [Key(0)] private int value;
MsgPack011 issues when flagging nesting types When MsgPack011 reports a diagnostic on a nest_ing_ type, it works at the command line. But in the IDE, the error tends to disappear from the error list, and the code fix isn't offered in the quick actions menu. A unit test to reproduce the problem throws with "Code fix is attempting to provide a fix for a non-local analyzer diagnostic".
null
2024-07-29T21:56:46Z
0.1
['MsgPack011PartialTypeRequiredTests.NestedPartialTypeRequiresPartialSelfAndDeclaringType', 'MsgPack011PartialTypeRequiredTests.NestedPartialTypeRequiresPartialDeclaringType']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1907
4788d1af88f2e8b3054fafd6e155a723bed53bba
diff --git a/sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj b/sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj index 9a73030a9..ed83e60a6 100644 --- a/sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj +++ b/sandbox/DynamicCodeDumper/DynamicCodeDumper.csproj @@ -10,6 +10,9 @@ <Compile Include="..\..\src\MessagePack.Annotations\Attributes.cs"> <Link>Code\Attributes.cs</Link> </Compile> + <Compile Include="..\..\src\MessagePack.Annotations\AnalyzerAttributes.cs"> + <Link>Code\AnalyzerAttributes.cs</Link> + </Compile> <Compile Include="..\..\src\MessagePack\BufferWriter.cs"> <Link>Code\BufferWriter.cs</Link> </Compile> diff --git a/sandbox/SharedData/Class1.cs b/sandbox/SharedData/Class1.cs index c2e856cb7..b206c02f5 100644 --- a/sandbox/SharedData/Class1.cs +++ b/sandbox/SharedData/Class1.cs @@ -100,9 +100,8 @@ public void Serialize(ref MessagePackWriter writer, int value, MessagePackSerial } } -#pragma warning disable MsgPack013 // no default constructor + [ExcludeFormatterFromSourceGeneratedResolver] public class OreOreFormatter2 : IMessagePackFormatter<ulong> -#pragma warning restore MsgPack013 // no default constructor { public OreOreFormatter2(int x, string y) { @@ -844,9 +843,8 @@ public DynamicArgumentTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 } } -#pragma warning disable MsgPack013 // no default constructor + [ExcludeFormatterFromSourceGeneratedResolver] public class DynamicArgumentTupleFormatter<T1, T2, T3, T4, T5, T6, T7, T8, T9> : IMessagePackFormatter<DynamicArgumentTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>> -#pragma warning restore MsgPack013 // no default constructor { private readonly T1 default1; private readonly T2 default2; diff --git a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs index eaab08734..1c2d5e612 100644 --- a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs +++ b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs @@ -312,7 +312,7 @@ private void AnalyzeSymbol(SymbolAnalysisContext context, ReferenceSymbols typeR context.ReportDiagnostic(Diagnostic.Create(CollidingFormatters, declaredSymbol.Locations[0], formattableType.Name.GetQualifiedName(Qualifiers.Namespace))); } - if (formatter.InaccessibleDescriptor is { } inaccessible) + if (!formatter.ExcludeFromSourceGeneratedResolver && formatter.InaccessibleDescriptor is { } inaccessible) { context.ReportDiagnostic(Diagnostic.Create(inaccessible, declaredSymbol.Locations[0])); } diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs index a1016e2cf..478ec30ef 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs @@ -41,6 +41,11 @@ public ImmutableHashSet<FormatterDescriptor> KnownFormatters bool collisionsEncountered = false; foreach (FormatterDescriptor formatter in value) { + if (formatter.ExcludeFromSourceGeneratedResolver) + { + continue; + } + foreach (FormattableType dataType in formatter.FormattableTypes) { if (formattableTypes.ContainsKey(dataType))
diff --git a/tests/MessagePack.SourceGenerator.Tests/ImplicitResolverForCustomFormattersTests.cs b/tests/MessagePack.SourceGenerator.Tests/ImplicitResolverForCustomFormattersTests.cs index 494d73122..26de2da45 100644 --- a/tests/MessagePack.SourceGenerator.Tests/ImplicitResolverForCustomFormattersTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/ImplicitResolverForCustomFormattersTests.cs @@ -79,6 +79,32 @@ internal class {|MsgPack009:IntFormatter2|} : IMessagePackFormatter<int> await VerifyCS.Test.RunDefaultAsync(this.logger, testSource); } + [Fact] + public async Task MultipleFunctionalCustomFormattersForType_OnlyOneNonExcluded() + { + string testSource = """ + using System; + using MessagePack; + using MessagePack.Formatters; + using MessagePack.Resolvers; + + [ExcludeFormatterFromSourceGeneratedResolver] + internal class IntFormatter1 : IMessagePackFormatter<int> + { + public void Serialize(ref MessagePackWriter writer, int value, MessagePackSerializerOptions options) => writer.Write(value); + public int Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => reader.ReadInt32(); + } + + internal class IntFormatter2 : IMessagePackFormatter<int> + { + public void Serialize(ref MessagePackWriter writer, int value, MessagePackSerializerOptions options) => writer.Write(value); + public int Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => reader.ReadInt32(); + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.logger, testSource); + } + [Fact] public async Task MultipleFunctionalCustomFormattersForType_MultiFormatter() { @@ -135,4 +161,25 @@ public IntFormatter(int value) { } // non-default constructor causes problem }, }.RunDefaultAsync(this.logger); } + + [Fact] + public async Task CustomFormatterWithoutDefaultConstructor_Excluded() + { + string testSource = """ + using System; + using MessagePack; + using MessagePack.Formatters; + using MessagePack.Resolvers; + + [ExcludeFormatterFromSourceGeneratedResolver] + internal class IntFormatter : IMessagePackFormatter<int> + { + public IntFormatter(int value) { } // non-default constructor causes problem + public void Serialize(ref MessagePackWriter writer, int value, MessagePackSerializerOptions options) => writer.Write(value); + public int Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => reader.ReadInt32(); + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.logger, testSource); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/MultipleFunctionalCustomFormattersForType_OnlyOneNonExcluded/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/MultipleFunctionalCustomFormattersForType_OnlyOneNonExcluded/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..b54a5cdd1 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/MultipleFunctionalCustomFormattersForType_OnlyOneNonExcluded/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(1) + { + { typeof(global::System.Int32), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new global::IntFormatter2(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +}
MsgPack013 should not fire for formatters with ExcludeFormatterFromSourceGeneratedResolver A formatter that must be created with a particular configuration and thus cannot have a default constructor will use the `[ExcludeFormatterFromSourceGeneratedResolver]` attribute to exclude itself from the source generated resolver. In which case, MsgPack013 should not flag that formatter as requiring a default constructor.
null
2024-07-29T16:58:27Z
0.1
['ImplicitResolverForCustomFormattersTests.MultipleFunctionalCustomFormattersForType_OnlyOneNonExcluded', 'ImplicitResolverForCustomFormattersTests.CustomFormatterWithoutDefaultConstructor_Excluded']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1905
6522b9ea066a0b5bb62e8f5a4d7796c1ddaca026
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index cc38d870d..587545fd1 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; namespace MessagePack.SourceGenerator.CodeAnalysis; @@ -653,8 +654,8 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } var isIntKey = true; - var intMembers = new Dictionary<int, MemberSerializationInfo>(); - var stringMembers = new Dictionary<string, MemberSerializationInfo>(); + var intMembers = new Dictionary<int, (MemberSerializationInfo Info, ITypeSymbol TypeSymbol)>(); + var stringMembers = new Dictionary<string, (MemberSerializationInfo Info, ITypeSymbol TypeSymbol)>(); FormatterDescriptor? GetSpecialFormatter(ISymbol member) { @@ -705,7 +706,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr includesPrivateMembers |= item.SetMethod is not null && !IsAllowedAccessibility(item.SetMethod.DeclaredAccessibility); FormatterDescriptor? specialFormatter = GetSpecialFormatter(item); var member = new MemberSerializationInfo(true, isWritable, isReadable, hiddenIntKey++, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - stringMembers.Add(member.StringKey, member); + stringMembers.Add(member.StringKey, (member, item.Type)); if (specialFormatter is null) { @@ -725,7 +726,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr FormatterDescriptor? specialFormatter = GetSpecialFormatter(item); var member = new MemberSerializationInfo(false, IsWritable: !item.IsReadOnly, IsReadable: true, hiddenIntKey++, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - stringMembers.Add(member.StringKey, member); + stringMembers.Add(member.StringKey, (member, item.Type)); if (specialFormatter is null) { this.CollectCore(item.Type); // recursive collect @@ -827,7 +828,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } var member = new MemberSerializationInfo(true, isWritable, isReadable, intKey!.Value, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - intMembers.Add(member.IntKey, member); + intMembers.Add(member.IntKey, (member, item.Type)); } else if (stringKey is not null) { @@ -837,7 +838,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } var member = new MemberSerializationInfo(true, isWritable, isReadable, hiddenIntKey++, stringKey!, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - stringMembers.Add(member.StringKey, member); + stringMembers.Add(member.StringKey, (member, item.Type)); } } @@ -914,7 +915,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } var member = new MemberSerializationInfo(true, IsWritable: !item.IsReadOnly, IsReadable: true, intKey!.Value, item.Name, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - intMembers.Add(member.IntKey, member); + intMembers.Add(member.IntKey, (member, item.Type)); } else { @@ -924,7 +925,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } var member = new MemberSerializationInfo(true, IsWritable: !item.IsReadOnly, IsReadable: true, hiddenIntKey++, stringKey!, item.Name, item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Type.ToDisplayString(BinaryWriteFormat), specialFormatter); - stringMembers.Add(member.StringKey, member); + stringMembers.Add(member.StringKey, (member, item.Type)); } } @@ -934,10 +935,13 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr // GetConstructor var ctorEnumerator = default(IEnumerator<IMethodSymbol>); - var ctor = formattedType.Constructors.Where(x => IsAllowedAccessibility(x.DeclaredAccessibility)).SingleOrDefault(x => x.GetAttributes().Any(y => y.AttributeClass != null && y.AttributeClass.ApproximatelyEqual(this.typeReferences.SerializationConstructorAttribute))); - if (ctor == null) + var ctor = formattedType.Constructors.SingleOrDefault(x => x.GetAttributes().Any(y => y.AttributeClass != null && y.AttributeClass.ApproximatelyEqual(this.typeReferences.SerializationConstructorAttribute))); + if (ctor is null) { - ctorEnumerator = formattedType.Constructors.Where(x => IsAllowedAccessibility(x.DeclaredAccessibility)).OrderByDescending(x => x.Parameters.Length).GetEnumerator(); + ctorEnumerator = formattedType.Constructors + .OrderByDescending(x => x.DeclaredAccessibility) + .ThenByDescending(x => x.Parameters.Length) + .GetEnumerator(); if (ctorEnumerator.MoveNext()) { @@ -946,29 +950,31 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr } // struct allows null ctor - if (ctor == null && isClass) + if (ctor is null && isClass) { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.NoDeserializingConstructor, GetIdentifierLocation(formattedType))); + return null; } var constructorParameters = new List<MemberSerializationInfo>(); - if (ctor != null) + if (ctor is not null) { - var constructorLookupDictionary = stringMembers.ToLookup(x => x.Value.Name, x => x, StringComparer.OrdinalIgnoreCase); + includesPrivateMembers |= !IsAllowedAccessibility(ctor.DeclaredAccessibility); + + var constructorLookupDictionary = stringMembers.ToLookup(x => x.Value.Info.Name, x => x, StringComparer.OrdinalIgnoreCase); do { constructorParameters.Clear(); var ctorParamIndex = 0; foreach (IParameterSymbol item in ctor!.Parameters) { - MemberSerializationInfo paramMember; if (isIntKey) { - if (intMembers.TryGetValue(ctorParamIndex, out paramMember!)) + if (intMembers.TryGetValue(ctorParamIndex, out (MemberSerializationInfo Info, ITypeSymbol TypeSymbol) member)) { - if (item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == paramMember.Type && paramMember.IsReadable) + if (this.compilation.ClassifyConversion(member.TypeSymbol, item.Type) is { IsImplicit: true } && member.Info.IsReadable) { - constructorParameters.Add(paramMember); + constructorParameters.Add(member.Info); } else { @@ -980,6 +986,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr else { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.DeserializingConstructorParameterTypeMismatch, GetLocation(item))); + return null; } } } @@ -993,12 +1000,13 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr else { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.DeserializingConstructorParameterIndexMissing, GetParameterListLocation(ctor))); + return null; } } } else { - IEnumerable<KeyValuePair<string, MemberSerializationInfo>> hasKey = constructorLookupDictionary[item.Name]; + IEnumerable<KeyValuePair<string, (MemberSerializationInfo Info, ITypeSymbol TypeSymbol)>> hasKey = constructorLookupDictionary[item.Name]; using var enumerator = hasKey.GetEnumerator(); // hasKey.Count() == 0 @@ -1007,6 +1015,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr if (ctorEnumerator == null) { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.DeserializingConstructorParameterNameMissing, GetParameterListLocation(ctor))); + return null; } ctor = null; @@ -1021,13 +1030,14 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr if (ctorEnumerator == null) { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.DeserializingConstructorParameterNameDuplicate, GetLocation(item))); + return null; } ctor = null; continue; } - paramMember = first; + MemberSerializationInfo paramMember = first.Info; if (item.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == paramMember.Type && paramMember.IsReadable) { constructorParameters.Add(paramMember); @@ -1037,6 +1047,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr if (ctorEnumerator == null) { this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.DeserializingConstructorParameterTypeMismatch, GetLocation(item))); + return null; } ctor = null; @@ -1102,7 +1113,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr genericTypeParameters: formattedType.IsGenericType ? formattedType.TypeParameters.Select(ToGenericTypeParameterInfo).ToArray() : Array.Empty<GenericTypeParameterInfo>(), constructorParameters: constructorParameters.ToArray(), isIntKey: isIntKey, - members: isIntKey ? intMembers.Values.ToArray() : stringMembers.Values.ToArray(), + members: isIntKey ? intMembers.Values.Select(v => v.Info).ToArray() : stringMembers.Values.Select(v => v.Info).ToArray(), hasIMessagePackSerializationCallbackReceiver: hasSerializationConstructor, needsCastOnAfter: needsCastOnAfter, needsCastOnBefore: needsCastOnBefore,
diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index 9f17cc324..3ce8fdf53 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -3,6 +3,7 @@ using MessagePack.SourceGenerator.Tests; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Testing; using VerifyCS = CSharpSourceGeneratorVerifier<MessagePack.SourceGenerator.MessagePackGenerator>; public class GenerationTests @@ -583,4 +584,70 @@ public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializ // This test is *not* expected to produce any generated files. await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); } + + [Fact] + public async Task NonDefaultDeserializingConstructor_Private() + { + string testSource = """ + using MessagePack; + [MessagePackObject] + partial class A { + [SerializationConstructor] + A(int x) => this.X = x; + + [Key(0)] + internal int X { get; } + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } + + [Fact] + public async Task DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType() + { + string testSource = """ + using MessagePack; + using System.Linq; + using System.Collections.Generic; + [MessagePackObject] + class A { + [SerializationConstructor] + internal A(IReadOnlyList<int> x) => this.X = x.ToList(); + + [Key(0)] + internal List<int> X { get; } + } + """; + + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } + + [Fact] + public async Task DeserializingConstructorParameterMemberTypeAssignability_Incompatible() + { + string testSource = """ + using MessagePack; + using System.Linq; + using System.Collections.Generic; + using System.Collections.Immutable; + [MessagePackObject] + class A { + [SerializationConstructor] + internal A({|#0:ImmutableList<int> x|}) => this.X = x.ToList(); + + [Key(0)] + internal List<int> X { get; } + } + """; + + await new VerifyCS.Test + { + TestState = + { + Sources = { testSource }, + }, + ExpectedDiagnostics = { DiagnosticResult.CompilerError("MsgPack007").WithLocation(0) }, + }.RunDefaultAsync(this.testOutputHelper); + } } diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_Incompatible/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_Incompatible/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..363286fe6 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_Incompatible/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(1) + { + { typeof(global::System.Collections.Generic.List<int>), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new MsgPack::Formatters.ListFormatter<int>(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs new file mode 100644 index 000000000..43f5630e2 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/Formatters.MessagePack.GeneratedMessagePackResolver.AFormatter.g.cs @@ -0,0 +1,59 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +namespace MessagePack { +partial class GeneratedMessagePackResolver { + + internal sealed class AFormatter : MsgPack::Formatters.IMessagePackFormatter<global::A> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::A value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + writer.WriteArrayHeader(1); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.Generic.List<int>>(formatterResolver).Serialize(ref writer, value.X, options); + } + + public global::A Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + MsgPack::IFormatterResolver formatterResolver = options.Resolver; + var length = reader.ReadArrayHeader(); + var __X__ = default(global::System.Collections.Generic.List<int>); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + __X__ = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<global::System.Collections.Generic.List<int>>(formatterResolver).Deserialize(ref reader, options); + break; + default: + reader.Skip(); + break; + } + } + + var ____result = new global::A(__X__); + reader.Depth--; + return ____result; + } + } +} +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..d07ffe633 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,65 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(2) + { + { typeof(global::System.Collections.Generic.List<int>), 0 }, + { typeof(global::A), 1 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new MsgPack::Formatters.ListFormatter<int>(), + 1 => new global::MessagePack.GeneratedMessagePackResolver.AFormatter(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/Formatters.A.AFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/Formatters.A.AFormatter.g.cs new file mode 100644 index 000000000..5666b90b8 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/Formatters.A.AFormatter.g.cs @@ -0,0 +1,55 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +#pragma warning disable CS8669 // We may leak nullable annotations into generated code. + +using MsgPack = global::MessagePack; + +partial class A { + + internal sealed class AFormatter : MsgPack::Formatters.IMessagePackFormatter<global::A> + { + + public void Serialize(ref MsgPack::MessagePackWriter writer, global::A value, MsgPack::MessagePackSerializerOptions options) + { + if (value == null) + { + writer.WriteNil(); + return; + } + + writer.WriteArrayHeader(1); + writer.Write(value.X); + } + + public global::A Deserialize(ref MsgPack::MessagePackReader reader, MsgPack::MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + var length = reader.ReadArrayHeader(); + var __X__ = default(int); + + for (int i = 0; i < length; i++) + { + switch (i) + { + case 0: + __X__ = reader.ReadInt32(); + break; + default: + reader.Skip(); + break; + } + } + + var ____result = new global::A(__X__); + reader.Depth--; + return ____result; + } + } +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..5b00f9cf1 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/NonDefaultDeserializingConstructor_Private/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(1) + { + { typeof(global::A), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new global::A.AFormatter(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +}
Generated code expects data type to have default ctor despite having `[SerializationConstructor]` attribute When migrating the vs-mef repo to v3, the `PropertyRef`, `MethodRef`, `FieldRef` and `DiscoveredParts` classes all have non-default constructors and the `[SerializationConstructor]` attribute on a non-default constructor. But the build fails because the source generated formatter tries to invoke a non-existent default constructor. Attributed private constructors are apparently ignored, which explains the failures of the first 3 listed types. AOT formatter should be more flexible for member/parameter types The generated AOT formatter is invalid for the following class: ```cs [SerializationConstructor] public DiscoveredParts(IEnumerable<ComposablePartDefinition> parts, IEnumerable<PartDiscoveryException> discoveryErrors) { this.Parts = ImmutableHashSet.CreateRange(parts); this.DiscoveryErrors = ImmutableList.CreateRange(discoveryErrors); } [Key(0)] public ImmutableHashSet<ComposablePartDefinition> Parts { get; private set; } [Key(1)] public ImmutableList<PartDiscoveryException> DiscoveryErrors { get; private set; } ``` The formatter is correct when the parameter types match the member types, but it would be great if the formatter could deal with the parameter types being different from the member types, particularly when the member type is assignable to the parameter type (although the reverse would also be great to support, where the deserializer would just create the more derived type). Generated code expects data type to have default ctor despite having `[SerializationConstructor]` attribute When migrating the vs-mef repo to v3, the `PropertyRef`, `MethodRef`, `FieldRef` and `DiscoveredParts` classes all have non-default constructors and the `[SerializationConstructor]` attribute on a non-default constructor. But the build fails because the source generated formatter tries to invoke a non-existent default constructor. Attributed private constructors are apparently ignored, which explains the failures of the first 3 listed types. AOT formatter should be more flexible for member/parameter types The generated AOT formatter is invalid for the following class: ```cs [SerializationConstructor] public DiscoveredParts(IEnumerable<ComposablePartDefinition> parts, IEnumerable<PartDiscoveryException> discoveryErrors) { this.Parts = ImmutableHashSet.CreateRange(parts); this.DiscoveryErrors = ImmutableList.CreateRange(discoveryErrors); } [Key(0)] public ImmutableHashSet<ComposablePartDefinition> Parts { get; private set; } [Key(1)] public ImmutableList<PartDiscoveryException> DiscoveryErrors { get; private set; } ``` The formatter is correct when the parameter types match the member types, but it would be great if the formatter could deal with the parameter types being different from the member types, particularly when the member type is assignable to the parameter type (although the reverse would also be great to support, where the deserializer would just create the more derived type).
2024-07-26T23:38:00Z
0.1
['GenerationTests.NonDefaultDeserializingConstructor_Private', 'GenerationTests.DeserializingConstructorParameterMemberTypeAssignability_MemberAssignsToParamType', 'GenerationTests.DeserializingConstructorParameterMemberTypeAssignability_Incompatible']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1898
dcb2801d561f0b7c896b7f93eccf86c77b39c7e8
diff --git a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs index a0491a2e4..90c0e83e4 100644 --- a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs +++ b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs @@ -6,22 +6,25 @@ namespace MessagePack.Analyzers.CodeFixes; [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MessagePackCodeFixProvider)), Shared] public class MessagePackCodeFixProvider : CodeFixProvider { - public sealed override ImmutableArray<string> FixableDiagnosticIds + public const string AddKeyAttributeEquivanceKey = "MessagePackAnalyzer.AddKeyAttribute"; + public const string AddIgnoreMemberAttributeEquivalenceKey = "MessagePackAnalyzer.AddIgnoreMemberAttribute"; + + public override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create( - MsgPack00xMessagePackAnalyzer.PublicMemberNeedsKey.Id, + MsgPack00xMessagePackAnalyzer.MemberNeedsKey.Id, MsgPack00xMessagePackAnalyzer.TypeMustBeMessagePackObject.Id); } } - public sealed override FixAllProvider GetFixAllProvider() + public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false) as CompilationUnitSyntax; if (root is null) @@ -112,29 +115,43 @@ myTypeInfo.Type as INamedTypeSymbol ?? } } - var action = CodeAction.Create("Add MessagePack KeyAttribute", c => AddKeyAttributeAsync(context.Document, namedSymbol, c), "MessagePackAnalyzer.AddKeyAttribute"); + CodeAction addKeyAction = CodeAction.Create("Add MessagePack KeyAttribute", c => AddKeyAttributeAsync(context.Document, namedSymbol, c), AddKeyAttributeEquivanceKey); + context.RegisterCodeFix(addKeyAction, context.Diagnostics.First()); - context.RegisterCodeFix(action, context.Diagnostics.First()); // use single. + foreach (Diagnostic diagnostic in context.Diagnostics) + { + SyntaxNode? diagnosticTargetNode = root.FindNode(diagnostic.Location.SourceSpan); + if (diagnosticTargetNode?.AncestorsAndSelf().FirstOrDefault(n => n is FieldDeclarationSyntax or PropertyDeclarationSyntax) is MemberDeclarationSyntax fieldOrProperty) + { + context.RegisterCodeFix( + CodeAction.Create( + "Add MessagePack [IgnoreMember]", + ct => AddIgnoreMemberAttributeAsync(context.Document, fieldOrProperty, ct), + AddIgnoreMemberAttributeEquivalenceKey), + diagnostic); + } + } } + private static IEnumerable<ISymbol> FindMembersMissingAttributes(INamedTypeSymbol type) => type.GetAllMembers() + .Where(x => x.Kind == SymbolKind.Property || x.Kind == SymbolKind.Field) + .Where(x => x.GetAttributes().FindAttributeShortName(MsgPack00xMessagePackAnalyzer.IgnoreShortName) == null && x.GetAttributes().FindAttributeShortName(MsgPack00xMessagePackAnalyzer.IgnoreDataMemberShortName) == null) + .Where(x => !x.IsStatic) + .Where(x => + { + return x switch + { + IPropertySymbol p => p.ExplicitInterfaceImplementations.Length == 0, + IFieldSymbol f => !f.IsImplicitlyDeclared, + _ => throw new NotSupportedException("Unsupported member type."), + }; + }); + private static async Task<Solution> AddKeyAttributeAsync(Document document, INamedTypeSymbol type, CancellationToken cancellationToken) { var solutionEditor = new SolutionEditor(document.Project.Solution); - var targets = type.GetAllMembers() - .Where(x => x.Kind == SymbolKind.Property || x.Kind == SymbolKind.Field) - .Where(x => x.GetAttributes().FindAttributeShortName(MsgPack00xMessagePackAnalyzer.IgnoreShortName) == null && x.GetAttributes().FindAttributeShortName(MsgPack00xMessagePackAnalyzer.IgnoreDataMemberShortName) == null) - .Where(x => !x.IsStatic) - .Where(x => - { - return x switch - { - IPropertySymbol p => p.ExplicitInterfaceImplementations.Length == 0, - IFieldSymbol f => !f.IsImplicitlyDeclared, - _ => throw new NotSupportedException("Unsupported member type."), - }; - }) - .ToArray(); + var targets = FindMembersMissingAttributes(type).ToArray(); var startOrder = targets .Select(x => x.GetAttributes().FindAttributeShortName(MsgPack00xMessagePackAnalyzer.KeyAttributeShortName)) @@ -174,4 +191,15 @@ private static async Task<Solution> AddKeyAttributeAsync(Document document, INam return solutionEditor.GetChangedSolution(); } + + private static async Task<Solution> AddIgnoreMemberAttributeAsync(Document document, MemberDeclarationSyntax memberDecl, CancellationToken cancellationToken) + { + SolutionEditor solutionEditor = new(document.Project.Solution); + DocumentEditor documentEditor = await solutionEditor.GetDocumentEditorAsync(document.Id, cancellationToken); + SyntaxGenerator syntaxGenerator = SyntaxGenerator.GetGenerator(documentEditor.OriginalDocument); + + documentEditor.AddAttribute(memberDecl, syntaxGenerator.Attribute("MessagePack.IgnoreMemberAttribute")); + + return solutionEditor.GetChangedSolution(); + } } diff --git a/src/MessagePack.SourceGenerator/AnalyzerReleases.Unshipped.md b/src/MessagePack.SourceGenerator/AnalyzerReleases.Unshipped.md index fa6a05e42..3f9ba4001 100644 --- a/src/MessagePack.SourceGenerator/AnalyzerReleases.Unshipped.md +++ b/src/MessagePack.SourceGenerator/AnalyzerReleases.Unshipped.md @@ -8,7 +8,7 @@ Rule ID | Category | Severity | Notes MsgPack001 | Reliability | Disabled | MsgPack001SpecifyOptionsAnalyzer MsgPack002 | Reliability | Disabled | MsgPack002UseConstantOptionsAnalyzer MsgPack003 | Usage | Error | MsgPack00xMessagePackAnalyzer -MsgPack004 | Usage | Error | MsgPack00xMessagePackAnalyzer +MsgPack004 | Usage | Error | Member needs Key or IgnoreMember attribute MsgPack005 | Usage | Error | MsgPack00xMessagePackAnalyzer MsgPack006 | Usage | Error | MsgPack00xMessagePackAnalyzer MsgPack007 | Usage | Error | MsgPack00xMessagePackAnalyzer diff --git a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs index b47e81019..eaab08734 100644 --- a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs +++ b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs @@ -53,7 +53,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(MessagePackFormatterMustBeMessagePackFormatterId)); - public static readonly DiagnosticDescriptor PublicMemberNeedsKey = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor MemberNeedsKey = new DiagnosticDescriptor( id: AttributeMessagePackObjectMembersId, title: "Attribute properties and fields of MessagePack objects", category: Category, @@ -258,7 +258,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( TypeMustBeMessagePackObject, MessageFormatterMustBeMessagePackFormatter, - PublicMemberNeedsKey, + MemberNeedsKey, BaseTypeContainsUnattributedPublicMembers, InvalidMessagePackObject, BothStringAndIntKeyAreNull, diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 47b27f731..cc38d870d 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -779,7 +779,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr var syntax = item.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); var identifier = (syntax as PropertyDeclarationSyntax)?.Identifier ?? (syntax as ParameterSyntax)?.Identifier; - this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.PublicMemberNeedsKey, identifier?.GetLocation(), formattedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Name)); + this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.MemberNeedsKey, identifier?.GetLocation(), formattedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Name)); } else if (formattedType.BaseType is not null) { @@ -881,7 +881,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr { if (contractAttr is not null) { - this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.PublicMemberNeedsKey, item.DeclaringSyntaxReferences[0].GetSyntax().GetLocation(), formattedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Name)); + this.reportDiagnostic?.Invoke(Diagnostic.Create(MsgPack00xMessagePackAnalyzer.MemberNeedsKey, item.DeclaringSyntaxReferences[0].GetSyntax().GetLocation(), formattedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), item.Name)); } } else
diff --git a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs index e356fe63a..91cca522c 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs @@ -1,7 +1,7 @@ // Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using MessagePack.SourceGenerator.Analyzers; +using MessagePack.Analyzers.CodeFixes; using Microsoft.CodeAnalysis.Testing; using VerifyCS = CSharpCodeFixVerifier<MessagePack.SourceGenerator.Analyzers.MsgPack00xMessagePackAnalyzer, MessagePack.Analyzers.CodeFixes.MessagePackCodeFixProvider>; @@ -118,6 +118,43 @@ public class Foo TestCode = input, FixedCode = output, MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); + } + + [Fact] + public async Task AddIgnoreAttributesToMembers() + { + string input = Preamble + @" +[MessagePackObject] +public class Foo +{ + internal string {|MsgPack004:member1 = null|}; + internal string {|MsgPack004:member2 = null|}; + [Key(0)] + public string Member3 { get; set; } +} +"; + + string output = Preamble + @" +[MessagePackObject] +public class Foo +{ + [IgnoreMember] + internal string member1 = null; + [IgnoreMember] + internal string member2 = null; + [Key(0)] + public string Member3 { get; set; } +} +"; + + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddIgnoreMemberAttributeEquivalenceKey, }.RunAsync(); } @@ -148,6 +185,7 @@ public class Foo TestCode = input, FixedCode = output, MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, }.RunAsync(); } @@ -185,7 +223,13 @@ public class Bar } "; - await VerifyCS.VerifyCodeFixAsync(input, output); + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); } [Fact] @@ -222,7 +266,13 @@ public record Bar } "; - await VerifyCS.VerifyCodeFixAsync(input, output); + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); } [Fact] @@ -259,7 +309,13 @@ public record Bar } "; - await VerifyCS.VerifyCodeFixAsync(input, output); + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); } [Fact] @@ -302,7 +358,13 @@ internal static class IsExternalInit } "; - await VerifyCS.VerifyCodeFixAsync(input, output); + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); } [Fact] @@ -353,6 +415,7 @@ public class Bar : Foo Sources = { output1, output2 }, }, MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, }.RunAsync(); } @@ -396,6 +459,12 @@ public class Bar } """; - await VerifyCS.VerifyCodeFixAsync(input, output); + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + CodeActionEquivalenceKey = MessagePackCodeFixProvider.AddKeyAttributeEquivanceKey, + }.RunAsync(); } }
Offer code fix for MsgPack004: attribute all members As folks migrate to v3, non-public fields and properties on all data types will be flagged as requiring a `Key` or `IgnoreMember` attribute. A bulk code fix should be offered that adds `IgnoreMember` everywhere necessary to ease the migration.
null
2024-07-22T21:51:31Z
0.1
['MessagePackAnalyzerTests.AddIgnoreAttributesToMembers']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1859
ceab2d78ccc76e11a361c7e2c4358d4aff52154d
diff --git a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs index 63a7851f8..eb915c795 100644 --- a/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs +++ b/src/MessagePack.SourceGenerator/Analyzers/MsgPack00xMessagePackAnalyzer.cs @@ -32,7 +32,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer private const string InvalidMessagePackObjectTitle = "MessagePackObject validation"; private const DiagnosticSeverity InvalidMessagePackObjectSeverity = DiagnosticSeverity.Error; - internal static readonly DiagnosticDescriptor TypeMustBeMessagePackObject = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor TypeMustBeMessagePackObject = new DiagnosticDescriptor( id: UseMessagePackObjectAttributeId, title: "Use MessagePackObjectAttribute", category: Category, @@ -42,7 +42,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(UseMessagePackObjectAttributeId)); - internal static readonly DiagnosticDescriptor MessageFormatterMustBeMessagePackFormatter = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor MessageFormatterMustBeMessagePackFormatter = new DiagnosticDescriptor( id: MessagePackFormatterMustBeMessagePackFormatterId, title: "Must be IMessageFormatter", category: Category, @@ -52,7 +52,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(MessagePackFormatterMustBeMessagePackFormatterId)); - internal static readonly DiagnosticDescriptor PublicMemberNeedsKey = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor PublicMemberNeedsKey = new DiagnosticDescriptor( id: AttributeMessagePackObjectMembersId, title: "Attribute properties and fields of MessagePack objects", category: Category, @@ -62,7 +62,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(AttributeMessagePackObjectMembersId)); - internal static readonly DiagnosticDescriptor BaseTypeContainsUnattributedPublicMembers = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor BaseTypeContainsUnattributedPublicMembers = new DiagnosticDescriptor( id: AttributeMessagePackObjectMembersId, title: "Attribute properties and fields of MessagePack objects", category: Category, @@ -72,7 +72,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(AttributeMessagePackObjectMembersId)); - internal static readonly DiagnosticDescriptor InvalidMessagePackObject = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor InvalidMessagePackObject = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -82,7 +82,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId)); - internal static readonly DiagnosticDescriptor BothStringAndIntKeyAreNull = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor BothStringAndIntKeyAreNull = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -92,7 +92,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId)); - internal static readonly DiagnosticDescriptor DoNotMixStringAndIntKeys = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor DoNotMixStringAndIntKeys = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -102,7 +102,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId)); - internal static readonly DiagnosticDescriptor KeysMustBeUnique = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor KeysMustBeUnique = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -112,7 +112,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId)); - internal static readonly DiagnosticDescriptor UnionAttributeRequired = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor UnionAttributeRequired = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -124,7 +124,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer // This is important because [Key] on a private member still will not be serialized, which is very confusing until // one realizes the type is serializing in map mode. - internal static readonly DiagnosticDescriptor KeyAnnotatedMemberInMapMode = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor KeyAnnotatedMemberInMapMode = new DiagnosticDescriptor( id: InvalidMessagePackObjectId, title: InvalidMessagePackObjectTitle, category: Category, @@ -134,7 +134,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InvalidMessagePackObjectId)); - internal static readonly DiagnosticDescriptor NoDeserializingConstructor = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor NoDeserializingConstructor = new DiagnosticDescriptor( id: DeserializingConstructorId, title: "Deserializing constructors", category: Category, @@ -144,7 +144,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); - internal static readonly DiagnosticDescriptor DeserializingConstructorParameterTypeMismatch = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor DeserializingConstructorParameterTypeMismatch = new DiagnosticDescriptor( id: DeserializingConstructorId, title: "Deserializing constructors", category: Category, @@ -154,7 +154,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); - internal static readonly DiagnosticDescriptor DeserializingConstructorParameterIndexMissing = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor DeserializingConstructorParameterIndexMissing = new DiagnosticDescriptor( id: DeserializingConstructorId, title: "Deserializing constructors", category: Category, @@ -164,7 +164,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); - internal static readonly DiagnosticDescriptor DeserializingConstructorParameterNameMissing = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor DeserializingConstructorParameterNameMissing = new DiagnosticDescriptor( id: DeserializingConstructorId, title: "Deserializing constructors", category: Category, @@ -174,7 +174,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); - internal static readonly DiagnosticDescriptor DeserializingConstructorParameterNameDuplicate = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor DeserializingConstructorParameterNameDuplicate = new DiagnosticDescriptor( id: DeserializingConstructorId, title: "Deserializing constructors", category: Category, @@ -184,7 +184,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(DeserializingConstructorId)); - internal static readonly DiagnosticDescriptor AotUnionAttributeRequiresTypeArg = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor AotUnionAttributeRequiresTypeArg = new DiagnosticDescriptor( id: AOTLimitationsId, title: "AOT limitations", category: Category, @@ -194,7 +194,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTLimitationsId)); - internal static readonly DiagnosticDescriptor AotArrayRankTooHigh = new DiagnosticDescriptor( + public static readonly DiagnosticDescriptor AotArrayRankTooHigh = new DiagnosticDescriptor( id: AOTLimitationsId, title: "AOT limitations", category: Category, @@ -204,7 +204,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(AOTLimitationsId)); - internal static readonly DiagnosticDescriptor CollidingFormatters = new( + public static readonly DiagnosticDescriptor CollidingFormatters = new( id: CollidingFormattersId, title: "Colliding formatters", category: Category, @@ -234,7 +234,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(InaccessibleFormatterId)); - internal static readonly DiagnosticDescriptor PartialTypeRequired = new( + public static readonly DiagnosticDescriptor PartialTypeRequired = new( id: PartialTypeRequiredId, title: "Partial type required", category: Category, @@ -244,7 +244,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer isEnabledByDefault: true, helpLinkUri: AnalyzerUtilities.GetHelpLink(PartialTypeRequiredId)); - internal static readonly DiagnosticDescriptor InaccessibleDataType = new( + public static readonly DiagnosticDescriptor InaccessibleDataType = new( id: InaccessibleDataTypeId, title: "Internally accessible data type required", category: Category, diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 46469e3f2..215b190b3 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -574,8 +574,7 @@ private bool CollectGeneric(INamedTypeSymbol type) if (type.IsDefinition) { this.CollectGenericUnion(type); - this.CollectObject(type); - return true; + return this.CollectObject(type); } else { @@ -585,7 +584,10 @@ private bool CollectGeneric(INamedTypeSymbol type) this.GetObjectInfo(type); // Collect generic type definition, that is not collected when it is defined outside target project. - this.CollectCore(type.OriginalDefinition); + if (!this.CollectCore(type.OriginalDefinition)) + { + return false; + } } // Collect substituted types for the type parameters (e.g. Bar in Foo<Bar>)
diff --git a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs index c77bb52ab..e356fe63a 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs @@ -1,6 +1,7 @@ // Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using MessagePack.SourceGenerator.Analyzers; using Microsoft.CodeAnalysis.Testing; using VerifyCS = CSharpCodeFixVerifier<MessagePack.SourceGenerator.Analyzers.MsgPack00xMessagePackAnalyzer, MessagePack.Analyzers.CodeFixes.MessagePackCodeFixProvider>; @@ -354,4 +355,47 @@ public class Bar : Foo MarkupOptions = MarkupOptions.UseFirstDescriptor, }.RunAsync(); } + + [Fact] + public async Task AddAttributeToGenericType() + { + string input = Preamble + """ + public class Foo<T> + { + public T Member { get; set; } + } + + [MessagePackObject] + public class Bar + { + [Key(0)] + public {|MsgPack003:Foo<int>|} MemberUserGeneric { get; set; } + + [Key(1)] + public System.Collections.Generic.List<int> MemberKnownGeneric { get; set; } + } + """; + + string output = Preamble + """ + + [MessagePackObject] + public class Foo<T> + { + [Key(0)] + public T Member { get; set; } + } + + [MessagePackObject] + public class Bar + { + [Key(0)] + public Foo<int> MemberUserGeneric { get; set; } + + [Key(1)] + public System.Collections.Generic.List<int> MemberKnownGeneric { get; set; } + } + """; + + await VerifyCS.VerifyCodeFixAsync(input, output); + } }
MsgPack003 is not reported on generic typed members #### Bug description The Analyzer does not detect properly missing attributes on generic types. #### Repro steps ```csharp public class Foo<T> { public T Member { get; set; } } [MessagePack.MessagePackObject] public class Bar { [MessagePack.Key(0)] public Foo<int> MemberUserGeneric { get; set; } [MessagePack.Key(1)] public System.Collections.Generic.List<int> MemberKnownGeneric { get; set; } } static void Test() { MessagePackSerializer.Serialize(new Bar()); } ``` #### Expected behavior The analyzer should detect an error and propose according changes. #### Actual behavior Analyzer does not detect any issue nor propose code change, issue is generated at runtime only as FormatterNotRegisteredException
null
2024-06-26T14:11:14Z
0.1
['MessagePackAnalyzerTests.AddAttributeToGenericType']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1842
7280ce1aa61ca0c8309df6c10dfe96e6f6107b48
diff --git a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs index 428f711aa..0e9d0bb96 100644 --- a/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs +++ b/src/MessagePack.Analyzers.CodeFixes/CodeFixes/MessagePackCodeFixProvider.cs @@ -1,12 +1,8 @@ // Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using System; using System.Collections.Immutable; using System.Composition; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using MessagePack.SourceGenerator; using MessagePack.SourceGenerator.Analyzers; using Microsoft.CodeAnalysis; @@ -168,6 +164,13 @@ private static async Task<Solution> AddKeyAttributeAsync(Document document, INam var node = await member.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var documentEditor = await solutionEditor.GetDocumentEditorAsync(document.Project.Solution.GetDocumentId(node.SyntaxTree), cancellationToken).ConfigureAwait(false); var syntaxGenerator = SyntaxGenerator.GetGenerator(documentEditor.OriginalDocument); + + // Preserve comments on fields. + if (node is VariableDeclaratorSyntax) + { + node = node.Parent; + } + documentEditor.AddAttribute(node, syntaxGenerator.Attribute("MessagePack.KeyAttribute", syntaxGenerator.LiteralExpression(startOrder++))); } }
diff --git a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs index c8b3bab9f..c77bb52ab 100644 --- a/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/MessagePackAnalyzerTests.cs @@ -120,6 +120,36 @@ public class Foo }.RunAsync(); } + [Fact] + public async Task AddAttributeToField_WithComment() + { + string input = Preamble + @" +[MessagePackObject] +public class Foo +{ + // comment + public string {|MsgPack004:Member1|}; +} +"; + + string output = Preamble + @" +[MessagePackObject] +public class Foo +{ + // comment + [Key(0)] + public string Member1; +} +"; + + await new VerifyCS.Test + { + TestCode = input, + FixedCode = output, + MarkupOptions = MarkupOptions.UseFirstDescriptor, + }.RunAsync(); + } + [Fact] public async Task AddAttributeToType() {
MessagePackAnalyzer MessagePackCodeFix Will overwrite comments #### Bug description Using Message PackCodeFix to fix code may result in missing comments #### Repro steps Execute Message PackCodeFix #### Expected behavior Just adding new attributes without affecting comments #### Actual behavior Code comments are overwritten - Version used: 2.5.140 - Runtime: Unity 2021.3.38
![image](https://github.com/MessagePack-CSharp/MessagePack-CSharp/assets/19683667/130f44e6-4138-4b26-a98e-c25887d3e0bf) Actual behavior: ![image](https://github.com/MessagePack-CSharp/MessagePack-CSharp/assets/19683667/3dde48dc-c2a9-4f81-9bd2-8e9b68b01725) Expected behavior: ![image](https://github.com/MessagePack-CSharp/MessagePack-CSharp/assets/19683667/4be9a9cb-a7fd-43cc-a6b7-c0f3378b1a6c) Do you have any improvement ideas? I am not familiar with RoslynAnalyzer and tried to make some changes myself, but it was not successful. If there is any solution, I can quickly test it. Thank you for your report. Yes, I've dealt with bugs like this with other code fixes and plan to fix this. Interesting... it only repros with _fields_. Properties retain their comments.
2024-06-06T01:47:59Z
0.1
['MessagePackAnalyzerTests.AddAttributeToTypeForRecord1', 'MessagePackAnalyzerTests.AddAttributeToField_WithComment']
['MessagePackAnalyzerTests.AddAttributeToTypeForRecord1', 'MessagePackAnalyzerTests.AddAttributeToTypeForRecord2', 'MessagePackAnalyzerTests.AddAttributeToTypeForRecordPrimaryConstructor', 'MessagePackAnalyzerTests.AddAttributeToType', 'MessagePackAnalyzerTests.CodeFixAppliesAcrossFiles', 'MessagePackAnalyzerTests.InvalidMessageFormatterType', 'MessagePackAnalyzerTests.AddAttributesToMembers', 'MessagePackAnalyzerTests.NullStringKey', 'MessagePackAnalyzerTests.NoMessagePackReference', 'MessagePackAnalyzerTests.MessageFormatterAttribute']
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1824
6e73bf0649af5cf0cc4448276895e33650a7f215
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs index 337955c14..d607c995c 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/AnalyzerOptions.cs @@ -189,6 +189,8 @@ public static bool TryCreate(INamedTypeSymbol type, [NotNullWhen(true)] out Cust CodeAnalysisUtilities.FindInaccessibleTypes(type).Any() ? MsgPack00xMessagePackAnalyzer.InaccessibleFormatterType : instanceProvidingMember is null ? MsgPack00xMessagePackAnalyzer.InaccessibleFormatterInstance : null, + ExcludeFromSourceGeneratedResolver = + type.GetAttributes().Any(a => a.AttributeClass?.Name == Constants.ExcludeFormatterFromSourceGeneratedResolverAttributeName && a.AttributeClass?.ContainingNamespace.Name == Constants.AttributeNamespace), }; return true; @@ -196,6 +198,8 @@ public static bool TryCreate(INamedTypeSymbol type, [NotNullWhen(true)] out Cust public DiagnosticDescriptor? InaccessibleDescriptor { get; init; } + public bool ExcludeFromSourceGeneratedResolver { get; init; } + public virtual bool Equals(CustomFormatter other) { return this.Name.Equals(other.Name) diff --git a/src/MessagePack.SourceGenerator/MessagePackGenerator.cs b/src/MessagePack.SourceGenerator/MessagePackGenerator.cs index fc412a67f..f9b413f6d 100644 --- a/src/MessagePack.SourceGenerator/MessagePackGenerator.cs +++ b/src/MessagePack.SourceGenerator/MessagePackGenerator.cs @@ -31,7 +31,9 @@ public void Initialize(IncrementalGeneratorInitializationContext context) predicate: static (node, ct) => node is ClassDeclarationSyntax { BaseList.Types.Count: > 0 }, transform: (ctxt, ct) => { - return ctxt.SemanticModel.GetDeclaredSymbol(ctxt.Node, ct) is INamedTypeSymbol symbol && CustomFormatter.TryCreate(symbol, out CustomFormatter? formatter) + return ctxt.SemanticModel.GetDeclaredSymbol(ctxt.Node, ct) is INamedTypeSymbol symbol + && CustomFormatter.TryCreate(symbol, out CustomFormatter? formatter) + && !formatter.ExcludeFromSourceGeneratedResolver ? formatter : null; }).Collect(); diff --git a/src/MessagePack.SourceGenerator/Utils/Constants.cs b/src/MessagePack.SourceGenerator/Utils/Constants.cs index b2d26c6cd..28ea3456c 100644 --- a/src/MessagePack.SourceGenerator/Utils/Constants.cs +++ b/src/MessagePack.SourceGenerator/Utils/Constants.cs @@ -9,6 +9,7 @@ internal static class Constants internal const string CompositeResolverAttributeName = "CompositeResolverAttribute"; internal const string GeneratedMessagePackResolverAttributeName = "GeneratedMessagePackResolverAttribute"; internal const string MessagePackKnownFormatterAttributeName = "MessagePackKnownFormatterAttribute"; + internal const string ExcludeFormatterFromSourceGeneratedResolverAttributeName = "ExcludeFormatterFromSourceGeneratedResolverAttribute"; internal const string MessagePackAssumedFormattableAttributeName = "MessagePackAssumedFormattableAttribute"; internal const string MessagePackObjectAttributeName = "MessagePackObjectAttribute"; internal const string MessagePackUnionAttributeName = "UnionAttribute"; diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Annotations/AnalyzerAttributes.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Annotations/AnalyzerAttributes.cs index 2b6f6099f..4a5c8888f 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Annotations/AnalyzerAttributes.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Annotations/AnalyzerAttributes.cs @@ -55,4 +55,18 @@ public MessagePackAssumedFormattableAttribute(Type formattableType) /// </summary> public Type FormattableType { get; } } + + /// <summary> + /// Causes the source generated resolver, which typically includes all implementations of <c>IMessagePackFormatter&lt;T&gt;</c>, + /// to exclude this particular formatter. + /// </summary> + /// <remarks> + /// This is useful when the formatter is intended for special case members, + /// which may apply the <see cref="MessagePackFormatterAttribute"/> to select the private formatter. + /// </remarks> + [AttributeUsage(AttributeTargets.Class)] + [Conditional("NEVERDEFINED")] + public class ExcludeFormatterFromSourceGeneratedResolverAttribute : Attribute + { + } }
diff --git a/tests/MessagePack.SourceGenerator.ExecutionTests/ExcludedCustomFormatter.cs b/tests/MessagePack.SourceGenerator.ExecutionTests/ExcludedCustomFormatter.cs new file mode 100644 index 000000000..6b0dcd0f8 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.ExecutionTests/ExcludedCustomFormatter.cs @@ -0,0 +1,34 @@ +// Copyright (c) All contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using MessagePack.Formatters; + +public class ExcludedCustomFormatter +{ + [Fact] + public void ExcludedFormatterIsIgnored() + { + // This would normally succeed because of our custom formatter and the auto-generated resolver, + // but because of the attribute applied to the formatter, it should not be included in the resolver, + // and thus our custom type should fail to serialize as an unknown type. + Assert.Throws<MessagePackSerializationException>( + () => MessagePackSerializer.Serialize(default(CustomType), MessagePackSerializerOptions.Standard)); + } + + internal struct CustomType; + + [ExcludeFormatterFromSourceGeneratedResolver] + internal class CustomFormatter : IMessagePackFormatter<CustomType> + { + public CustomType Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + { + reader.Skip(); + return default; + } + + public void Serialize(ref MessagePackWriter writer, CustomType value, MessagePackSerializerOptions options) + { + writer.WriteNil(); + } + } +} diff --git a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs index d83633313..187b4cf2e 100644 --- a/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs +++ b/tests/MessagePack.SourceGenerator.Tests/GenerationTests.cs @@ -545,4 +545,22 @@ public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializ """; await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); } + + [Fact] + public async Task ExcludeFormatterFromSourceGeneratedResolver() + { + string testSource = """ + using MessagePack; + using MessagePack.Formatters; + class A {} + [ExcludeFormatterFromSourceGeneratedResolver] + class F : IMessagePackFormatter<A> { + public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializerOptions options) {} + public A Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => default; + } + """; + + // This test is *not* expected to produce any generated files. + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } }
We need a proper way to exclude a custom formatter from automatic inclusion in the resolver Since #1739, custom formatters will get included in the resolver. But that breaks the custom formatter that is only intended for explicit opt-in via the `MessagePackFormatterAttribute` applied to a particular member. We need a `IgnoreFormatterAttribute` or something that the source generator will recognize and honor by not adding the formatter to the resolver.
null
2024-05-22T18:36:59Z
0.1
['GenerationTests.ExcludeFormatterFromSourceGeneratedResolver', 'ExcludedCustomFormatter.ExcludedFormatterIsIgnored']
[]
MessagePack-CSharp/MessagePack-CSharp
messagepack-csharp__messagepack-csharp-1798
b7be200180fb06ccee8327d24f10503206114c75
diff --git a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs index 6c405688d..2fe531b0e 100644 --- a/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs +++ b/src/MessagePack.SourceGenerator/CodeAnalysis/TypeCollector.cs @@ -933,7 +933,7 @@ private bool CheckValidMessagePackFormatterAttribute(AttributeData formatterAttr var constructorParameters = new List<MemberSerializationInfo>(); if (ctor != null) { - var constructorLookupDictionary = stringMembers.ToLookup(x => x.Key, x => x, StringComparer.OrdinalIgnoreCase); + var constructorLookupDictionary = stringMembers.ToLookup(x => x.Value.Name, x => x, StringComparer.OrdinalIgnoreCase); do { constructorParameters.Clear();
diff --git a/tests/MessagePack.SourceGenerator.Tests/CustomStringKeyFormatterTests.cs b/tests/MessagePack.SourceGenerator.Tests/CustomStringKeyFormatterTests.cs new file mode 100644 index 000000000..e5e2c631b --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/CustomStringKeyFormatterTests.cs @@ -0,0 +1,61 @@ +// Copyright (c) All contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using VerifyCS = CSharpSourceGeneratorVerifier<MessagePack.SourceGenerator.MessagePackGenerator>; + +public class CustomStringKeyFormatterTests +{ + private readonly ITestOutputHelper testOutputHelper; + + public CustomStringKeyFormatterTests(ITestOutputHelper testOutputHelper) + { + this.testOutputHelper = testOutputHelper; + } + + [Fact] + public async Task RecordWithPrimaryConstructor() + { + string testSource = """ +using System; +using System.Collections.Generic; +using MessagePack; + +namespace TempProject +{ + [MessagePackObject] + public record MyMessagePackObject([property: Key("p")] string PhoneNumber, [property: Key("c")] int Count); +} +"""; + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } + + [Fact] + public async Task RecordWithWithInitOnlyProps() + { + string testSource = """ +using System; +using System.Collections.Generic; +using MessagePack; + +namespace TempProject +{ + [MessagePackObject] + public class MyMessagePackObject + { + public MyMessagePackObject(string phoneNumber, int count) + { + PhoneNumber = phoneNumber; + Count = count; + } + + [Key("p")] + public string PhoneNumber { get; set; } + + [Key("c")] + public int Count { get; set; } + }; +} +"""; + await VerifyCS.Test.RunDefaultAsync(this.testOutputHelper, testSource); + } +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs new file mode 100644 index 000000000..8a81a7655 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs @@ -0,0 +1,79 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +namespace MessagePack { + +using MsgPack = global::MessagePack; + +partial class GeneratedMessagePackResolver +{ +private partial class TempProject { + internal sealed class MyMessagePackObjectFormatter : global::MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyMessagePackObject> + { + // p + private static global::System.ReadOnlySpan<byte> GetSpan_PhoneNumber() => new byte[1 + 1] { 161, 112 }; + // c + private static global::System.ReadOnlySpan<byte> GetSpan_Count() => new byte[1 + 1] { 161, 99 }; + + public void Serialize(ref global::MessagePack.MessagePackWriter writer, global::TempProject.MyMessagePackObject value, global::MessagePack.MessagePackSerializerOptions options) + { + if (value is null) + { + writer.WriteNil(); + return; + } + + var formatterResolver = options.Resolver; + writer.WriteMapHeader(2); + writer.WriteRaw(GetSpan_PhoneNumber()); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Serialize(ref writer, value.PhoneNumber, options); + writer.WriteRaw(GetSpan_Count()); + writer.Write(value.Count); + } + + public global::TempProject.MyMessagePackObject Deserialize(ref global::MessagePack.MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + var formatterResolver = options.Resolver; + var length = reader.ReadMapHeader(); + var __PhoneNumber__ = default(string); + var __Count__ = default(int); + + for (int i = 0; i < length; i++) + { + var stringKey = global::MessagePack.Internal.CodeGenHelpers.ReadStringSpan(ref reader); + switch (stringKey.Length) + { + default: + FAIL: + reader.Skip(); + continue; + case 1: + switch (global::MessagePack.Internal.AutomataKeyGen.GetKey(ref stringKey)) + { + default: goto FAIL; + case 112UL: + __PhoneNumber__ = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Deserialize(ref reader, options); + continue; + case 99UL: + __Count__ = reader.ReadInt32(); + continue; + } + + } + } + + var ____result = new global::TempProject.MyMessagePackObject(__PhoneNumber__, __Count__); + reader.Depth--; + return ____result; + } + } +}} + +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..ff202b65b --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithPrimaryConstructor/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(1) + { + { typeof(global::TempProject.MyMessagePackObject), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new TempProject.MyMessagePackObjectFormatter(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs new file mode 100644 index 000000000..8a81a7655 --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/Formatters.TempProject.MyMessagePackObjectFormatter.g.cs @@ -0,0 +1,79 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +namespace MessagePack { + +using MsgPack = global::MessagePack; + +partial class GeneratedMessagePackResolver +{ +private partial class TempProject { + internal sealed class MyMessagePackObjectFormatter : global::MessagePack.Formatters.IMessagePackFormatter<global::TempProject.MyMessagePackObject> + { + // p + private static global::System.ReadOnlySpan<byte> GetSpan_PhoneNumber() => new byte[1 + 1] { 161, 112 }; + // c + private static global::System.ReadOnlySpan<byte> GetSpan_Count() => new byte[1 + 1] { 161, 99 }; + + public void Serialize(ref global::MessagePack.MessagePackWriter writer, global::TempProject.MyMessagePackObject value, global::MessagePack.MessagePackSerializerOptions options) + { + if (value is null) + { + writer.WriteNil(); + return; + } + + var formatterResolver = options.Resolver; + writer.WriteMapHeader(2); + writer.WriteRaw(GetSpan_PhoneNumber()); + MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Serialize(ref writer, value.PhoneNumber, options); + writer.WriteRaw(GetSpan_Count()); + writer.Write(value.Count); + } + + public global::TempProject.MyMessagePackObject Deserialize(ref global::MessagePack.MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) + { + if (reader.TryReadNil()) + { + return null; + } + + options.Security.DepthStep(ref reader); + var formatterResolver = options.Resolver; + var length = reader.ReadMapHeader(); + var __PhoneNumber__ = default(string); + var __Count__ = default(int); + + for (int i = 0; i < length; i++) + { + var stringKey = global::MessagePack.Internal.CodeGenHelpers.ReadStringSpan(ref reader); + switch (stringKey.Length) + { + default: + FAIL: + reader.Skip(); + continue; + case 1: + switch (global::MessagePack.Internal.AutomataKeyGen.GetKey(ref stringKey)) + { + default: goto FAIL; + case 112UL: + __PhoneNumber__ = MsgPack::FormatterResolverExtensions.GetFormatterWithVerify<string>(formatterResolver).Deserialize(ref reader, options); + continue; + case 99UL: + __Count__ = reader.ReadInt32(); + continue; + } + + } + } + + var ____result = new global::TempProject.MyMessagePackObject(__PhoneNumber__, __Count__); + reader.Depth--; + return ____result; + } + } +}} + +} diff --git a/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/MessagePack.GeneratedMessagePackResolver.g.cs b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/MessagePack.GeneratedMessagePackResolver.g.cs new file mode 100644 index 000000000..ff202b65b --- /dev/null +++ b/tests/MessagePack.SourceGenerator.Tests/Resources/RecordWithWithInitOnlyProps/MessagePack.GeneratedMessagePackResolver.g.cs @@ -0,0 +1,63 @@ +// <auto-generated /> + +#pragma warning disable 618, 612, 414, 168, CS1591, SA1129, SA1309, SA1312, SA1403, SA1649 + +using MsgPack = global::MessagePack; + +[assembly: MsgPack::Internal.GeneratedAssemblyMessagePackResolverAttribute(typeof(MessagePack.GeneratedMessagePackResolver), 3, 0)] + +namespace MessagePack { + +/// <summary>A MessagePack resolver that uses generated formatters for types in this assembly.</summary> +partial class GeneratedMessagePackResolver : MsgPack::IFormatterResolver +{ + /// <summary>An instance of this resolver that only returns formatters specifically generated for types in this assembly.</summary> + public static readonly MsgPack::IFormatterResolver Instance = new GeneratedMessagePackResolver(); + + private GeneratedMessagePackResolver() + { + } + + public MsgPack::Formatters.IMessagePackFormatter<T> GetFormatter<T>() + { + return FormatterCache<T>.Formatter; + } + + private static class FormatterCache<T> + { + internal static readonly MsgPack::Formatters.IMessagePackFormatter<T> Formatter; + + static FormatterCache() + { + var f = GeneratedMessagePackResolverGetFormatterHelper.GetFormatter(typeof(T)); + if (f != null) + { + Formatter = (MsgPack::Formatters.IMessagePackFormatter<T>)f; + } + } + } + + private static class GeneratedMessagePackResolverGetFormatterHelper + { + private static readonly global::System.Collections.Generic.Dictionary<global::System.Type, int> closedTypeLookup = new(1) + { + { typeof(global::TempProject.MyMessagePackObject), 0 }, + }; + + internal static object GetFormatter(global::System.Type t) + { + if (closedTypeLookup.TryGetValue(t, out int closedKey)) + { + return closedKey switch + { + 0 => new TempProject.MyMessagePackObjectFormatter(), + _ => null, // unreachable + }; + } + + return null; + } + } +} + +}
Wrong type of formatter for record with string keys #### Bug description Source generator generates formatter with errors (unable to build) for record with one primary constructor. Only when string used as a key, with int everything works as expected. #### Repro steps just to use this to generate the code. ```c# [MessagePackObject] public record Record([property: Key("c")] string SomeId); ``` But it works if Key == Parameter name, btw ive seen that it was tested with similar record when key and name are the same ```c# [MessagePackObject] public record Record([property: Key("SomeId")] string SomeId); ``` #### Expected behavior Formatter should create an object and put all args to constructor #### Actual behavior Formatter tries to create an object without parameters and then tries to set it. #### Additional context Investigated and have found that when it collect Member info it use string key as dictionary key https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/43f1b1c874bd224943a16555a483d6dc9de00c6c/src/MessagePack.GeneratorCore/CodeAnalysis/TypeCollector.cs#L806-L812 then it creates lookup by this string key https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/43f1b1c874bd224943a16555a483d6dc9de00c6c/src/MessagePack.GeneratorCore/CodeAnalysis/TypeCollector.cs#L841 and then it tries to get member info using prop name https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/43f1b1c874bd224943a16555a483d6dc9de00c6c/src/MessagePack.GeneratorCore/CodeAnalysis/TypeCollector.cs#L885 It seems to me that the solution is to simply use the property name in the stringMembers dictionary.
Thanks for your report and your proposed fix. Would you please try our `develop` branch? `mpc` is gone, replaced with a proper C# source generator. Much of the code is the same, but a lot of refactoring has taken place. If it repros in `develop` and you're interested, we'd be delighted if you'd add a test and a pull request to fix it. Thanks that mentioned develop i tried to find source gen in master =) i checked develop, its almost the same in that place, will fix that and create pr.
2024-04-13T05:22:50Z
0.1
['CustomStringKeyFormatterTests.RecordWithPrimaryConstructor', 'CustomStringKeyFormatterTests.RecordWithWithInitOnlyProps']
[]
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2307
f32a2e753251afa7efb67f57fdbda1b18d5869fb
diff --git a/docs/articles/samples/IntroCategoryDiscoverer.md b/docs/articles/samples/IntroCategoryDiscoverer.md new file mode 100644 index 0000000000..0f268ac913 --- /dev/null +++ b/docs/articles/samples/IntroCategoryDiscoverer.md @@ -0,0 +1,26 @@ +--- +uid: BenchmarkDotNet.Samples.IntroCategoryDiscoverer +--- + +## Sample: IntroCategoryDiscoverer + +The category discovery strategy can be overridden using an instance of `ICategoryDiscoverer`. + +### Source code + +[!code-csharp[IntroCategoryDiscoverer.cs](../../../samples/BenchmarkDotNet.Samples/IntroCategoryDiscoverer.cs)] + +### Output + +```markdown +| Method | Categories | Mean | Error | +|------- |----------- |---------:|------:| +| Bar | All,B | 126.5 us | NA | +| Foo | All,F | 114.0 us | NA | +``` + +### Links + +* The permanent link to this sample: @BenchmarkDotNet.Samples.IntroCategoryDiscoverer + +--- \ No newline at end of file diff --git a/docs/articles/samples/toc.yml b/docs/articles/samples/toc.yml index 098e457dd8..e5c84fee1d 100644 --- a/docs/articles/samples/toc.yml +++ b/docs/articles/samples/toc.yml @@ -12,6 +12,8 @@ href: IntroCategories.md - name: IntroCategoryBaseline href: IntroCategoryBaseline.md +- name: IntroCategoryDiscoverer + href: IntroCategoryDiscoverer.md - name: IntroColdStart href: IntroColdStart.md - name: IntroComparableComplexParam diff --git a/samples/BenchmarkDotNet.Samples/IntroCategoryDiscoverer.cs b/samples/BenchmarkDotNet.Samples/IntroCategoryDiscoverer.cs new file mode 100644 index 0000000000..92383eb2c8 --- /dev/null +++ b/samples/BenchmarkDotNet.Samples/IntroCategoryDiscoverer.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Running; + +namespace BenchmarkDotNet.Samples +{ + [DryJob] + [CategoriesColumn] + [CustomCategoryDiscoverer] + public class IntroCategoryDiscoverer + { + private class CustomCategoryDiscoverer : DefaultCategoryDiscoverer + { + public override string[] GetCategories(MethodInfo method) + { + var categories = new List<string>(); + categories.AddRange(base.GetCategories(method)); + categories.Add("All"); + categories.Add(method.Name.Substring(0, 1)); + return categories.ToArray(); + } + } + + [AttributeUsage(AttributeTargets.Class)] + private class CustomCategoryDiscovererAttribute : Attribute, IConfigSource + { + public CustomCategoryDiscovererAttribute() + { + Config = ManualConfig.CreateEmpty() + .WithCategoryDiscoverer(new CustomCategoryDiscoverer()); + } + + public IConfig Config { get; } + } + + + [Benchmark] + public void Foo() { } + + [Benchmark] + public void Bar() { } + } +} \ No newline at end of file diff --git a/src/BenchmarkDotNet.Annotations/Attributes/BenchmarkCategoryAttribute.cs b/src/BenchmarkDotNet.Annotations/Attributes/BenchmarkCategoryAttribute.cs index 50935d7132..f386d6cae4 100644 --- a/src/BenchmarkDotNet.Annotations/Attributes/BenchmarkCategoryAttribute.cs +++ b/src/BenchmarkDotNet.Annotations/Attributes/BenchmarkCategoryAttribute.cs @@ -3,7 +3,7 @@ namespace BenchmarkDotNet.Attributes { - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public class BenchmarkCategoryAttribute : Attribute { public string[] Categories { get; } diff --git a/src/BenchmarkDotNet/Attributes/CategoryDiscovererAttribute.cs b/src/BenchmarkDotNet/Attributes/CategoryDiscovererAttribute.cs new file mode 100644 index 0000000000..764042df28 --- /dev/null +++ b/src/BenchmarkDotNet/Attributes/CategoryDiscovererAttribute.cs @@ -0,0 +1,17 @@ +using System; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Running; + +namespace BenchmarkDotNet.Attributes +{ + [AttributeUsage(AttributeTargets.Class)] + public class CategoryDiscovererAttribute : Attribute, IConfigSource + { + public CategoryDiscovererAttribute(bool inherit = true) + { + Config = ManualConfig.CreateEmpty().WithCategoryDiscoverer(new DefaultCategoryDiscoverer(inherit)); + } + + public IConfig Config { get; } + } +} \ No newline at end of file diff --git a/src/BenchmarkDotNet/Configs/DebugConfig.cs b/src/BenchmarkDotNet/Configs/DebugConfig.cs index 764d798933..2cbdff2461 100644 --- a/src/BenchmarkDotNet/Configs/DebugConfig.cs +++ b/src/BenchmarkDotNet/Configs/DebugConfig.cs @@ -12,6 +12,7 @@ using BenchmarkDotNet.Order; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; using BenchmarkDotNet.Toolchains.InProcess.Emit; using BenchmarkDotNet.Validators; @@ -66,6 +67,7 @@ public abstract class DebugConfig : IConfig public IEnumerable<IColumnHidingRule> GetColumnHidingRules() => Array.Empty<IColumnHidingRule>(); public IOrderer Orderer => DefaultOrderer.Instance; + public ICategoryDiscoverer? CategoryDiscoverer => DefaultCategoryDiscoverer.Instance; public SummaryStyle SummaryStyle => SummaryStyle.Default; public ConfigUnionRule UnionRule => ConfigUnionRule.Union; public TimeSpan BuildTimeout => DefaultConfig.Instance.BuildTimeout; diff --git a/src/BenchmarkDotNet/Configs/DefaultConfig.cs b/src/BenchmarkDotNet/Configs/DefaultConfig.cs index 9a8f0345f0..8d1df6285b 100644 --- a/src/BenchmarkDotNet/Configs/DefaultConfig.cs +++ b/src/BenchmarkDotNet/Configs/DefaultConfig.cs @@ -13,6 +13,7 @@ using BenchmarkDotNet.Order; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; namespace BenchmarkDotNet.Configs @@ -72,6 +73,7 @@ public IEnumerable<IValidator> GetValidators() } public IOrderer Orderer => null; + public ICategoryDiscoverer? CategoryDiscoverer => null; public ConfigUnionRule UnionRule => ConfigUnionRule.Union; diff --git a/src/BenchmarkDotNet/Configs/IConfig.cs b/src/BenchmarkDotNet/Configs/IConfig.cs index beb30a33e6..46a53692c2 100644 --- a/src/BenchmarkDotNet/Configs/IConfig.cs +++ b/src/BenchmarkDotNet/Configs/IConfig.cs @@ -10,6 +10,7 @@ using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Order; using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; using JetBrains.Annotations; @@ -30,6 +31,7 @@ public interface IConfig IEnumerable<IColumnHidingRule> GetColumnHidingRules(); IOrderer? Orderer { get; } + ICategoryDiscoverer? CategoryDiscoverer { get; } SummaryStyle SummaryStyle { get; } @@ -57,4 +59,4 @@ public interface IConfig /// </summary> IReadOnlyList<Conclusion> ConfigAnalysisConclusion { get; } } -} +} \ No newline at end of file diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs index d4a1cfd47a..b5d84eaf56 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs @@ -14,7 +14,6 @@ using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; -using JetBrains.Annotations; using RunMode = BenchmarkDotNet.Diagnosers.RunMode; namespace BenchmarkDotNet.Configs @@ -50,6 +49,7 @@ internal ImmutableConfig( string artifactsPath, CultureInfo cultureInfo, IOrderer orderer, + ICategoryDiscoverer categoryDiscoverer, SummaryStyle summaryStyle, ConfigOptions options, TimeSpan buildTimeout, @@ -70,6 +70,7 @@ internal ImmutableConfig( ArtifactsPath = artifactsPath; CultureInfo = cultureInfo; Orderer = orderer; + CategoryDiscoverer = categoryDiscoverer; SummaryStyle = summaryStyle; Options = options; BuildTimeout = buildTimeout; @@ -81,6 +82,7 @@ internal ImmutableConfig( public CultureInfo CultureInfo { get; } public ConfigOptions Options { get; } public IOrderer Orderer { get; } + public ICategoryDiscoverer CategoryDiscoverer { get; } public SummaryStyle SummaryStyle { get; } public TimeSpan BuildTimeout { get; } diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs index 42c05f77ef..e85abf926d 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs @@ -7,6 +7,7 @@ using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Order; using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; namespace BenchmarkDotNet.Configs @@ -69,6 +70,7 @@ public static ImmutableConfig Create(IConfig source) source.ArtifactsPath ?? DefaultConfig.Instance.ArtifactsPath, source.CultureInfo, source.Orderer ?? DefaultOrderer.Instance, + source.CategoryDiscoverer ?? DefaultCategoryDiscoverer.Instance, source.SummaryStyle ?? SummaryStyle.Default, source.Options, source.BuildTimeout, diff --git a/src/BenchmarkDotNet/Configs/ManualConfig.cs b/src/BenchmarkDotNet/Configs/ManualConfig.cs index 9f632c03d0..27eca81863 100644 --- a/src/BenchmarkDotNet/Configs/ManualConfig.cs +++ b/src/BenchmarkDotNet/Configs/ManualConfig.cs @@ -13,6 +13,7 @@ using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Order; using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; using BenchmarkDotNet.Validators; using JetBrains.Annotations; @@ -51,6 +52,7 @@ public class ManualConfig : IConfig [PublicAPI] public string ArtifactsPath { get; set; } [PublicAPI] public CultureInfo CultureInfo { get; set; } [PublicAPI] public IOrderer Orderer { get; set; } + [PublicAPI] public ICategoryDiscoverer CategoryDiscoverer { get; set; } [PublicAPI] public SummaryStyle SummaryStyle { get; set; } [PublicAPI] public TimeSpan BuildTimeout { get; set; } = DefaultConfig.Instance.BuildTimeout; @@ -92,6 +94,12 @@ public ManualConfig WithOrderer(IOrderer orderer) return this; } + public ManualConfig WithCategoryDiscoverer(ICategoryDiscoverer categoryDiscoverer) + { + CategoryDiscoverer = categoryDiscoverer; + return this; + } + public ManualConfig WithBuildTimeout(TimeSpan buildTimeout) { BuildTimeout = buildTimeout; @@ -247,6 +255,7 @@ public void Add(IConfig config) hardwareCounters.AddRange(config.GetHardwareCounters()); filters.AddRange(config.GetFilters()); Orderer = config.Orderer ?? Orderer; + CategoryDiscoverer = config.CategoryDiscoverer ?? CategoryDiscoverer; ArtifactsPath = config.ArtifactsPath ?? ArtifactsPath; CultureInfo = config.CultureInfo ?? CultureInfo; SummaryStyle = config.SummaryStyle ?? SummaryStyle; diff --git a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs index 1179daae02..dbe350b2c8 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs @@ -51,7 +51,8 @@ private static BenchmarkRunInfo MethodsToBenchmarksWithFullConfig(Type type, Met var iterationSetupMethods = GetAttributedMethods<IterationSetupAttribute>(allMethods, "IterationSetup"); var iterationCleanupMethods = GetAttributedMethods<IterationCleanupAttribute>(allMethods, "IterationCleanup"); - var targets = GetTargets(benchmarkMethods, type, globalSetupMethods, globalCleanupMethods, iterationSetupMethods, iterationCleanupMethods).ToArray(); + var targets = GetTargets(benchmarkMethods, type, globalSetupMethods, globalCleanupMethods, iterationSetupMethods, iterationCleanupMethods, + configPerType).ToArray(); var parameterDefinitions = GetParameterDefinitions(type); var parameterInstancesList = parameterDefinitions.Expand(configPerType.SummaryStyle); @@ -115,7 +116,8 @@ private static IEnumerable<Descriptor> GetTargets( Tuple<MethodInfo, TargetedAttribute>[] globalSetupMethods, Tuple<MethodInfo, TargetedAttribute>[] globalCleanupMethods, Tuple<MethodInfo, TargetedAttribute>[] iterationSetupMethods, - Tuple<MethodInfo, TargetedAttribute>[] iterationCleanupMethods) + Tuple<MethodInfo, TargetedAttribute>[] iterationCleanupMethods, + IConfig config) { return targetMethods .Select(methodInfo => CreateDescriptor(type, @@ -125,7 +127,8 @@ private static IEnumerable<Descriptor> GetTargets( GetTargetedMatchingMethod(methodInfo, iterationSetupMethods), GetTargetedMatchingMethod(methodInfo, iterationCleanupMethods), methodInfo.ResolveAttribute<BenchmarkAttribute>(), - targetMethods)); + targetMethods, + config)); } private static MethodInfo GetTargetedMatchingMethod(MethodInfo benchmarkMethod, Tuple<MethodInfo, TargetedAttribute>[] methods) @@ -152,8 +155,10 @@ private static Descriptor CreateDescriptor( MethodInfo iterationSetupMethod, MethodInfo iterationCleanupMethod, BenchmarkAttribute attr, - MethodInfo[] targetMethods) + MethodInfo[] targetMethods, + IConfig config) { + var categoryDiscoverer = config.CategoryDiscoverer ?? DefaultCategoryDiscoverer.Instance; var target = new Descriptor( type, methodInfo, @@ -163,7 +168,7 @@ private static Descriptor CreateDescriptor( iterationCleanupMethod, attr.Description, baseline: attr.Baseline, - categories: GetCategories(methodInfo), + categories: categoryDiscoverer.GetCategories(methodInfo), operationsPerInvoke: attr.OperationsPerInvoke, methodIndex: Array.IndexOf(targetMethods, methodInfo)); AssertMethodHasCorrectSignature("Benchmark", methodInfo); @@ -245,21 +250,6 @@ private static IEnumerable<ParameterInstances> GetArgumentsDefinitions(MethodInf yield return SmartParamBuilder.CreateForArguments(benchmark, parameterDefinitions, valuesInfo, sourceIndex, summaryStyle); } - private static string[] GetCategories(MethodInfo method) - { - var attributes = new List<BenchmarkCategoryAttribute>(); - attributes.AddRange(method.GetCustomAttributes(typeof(BenchmarkCategoryAttribute), false).OfType<BenchmarkCategoryAttribute>()); - var type = method.DeclaringType; - if (type != null) - { - attributes.AddRange(type.GetTypeInfo().GetCustomAttributes(typeof(BenchmarkCategoryAttribute), false).OfType<BenchmarkCategoryAttribute>()); - attributes.AddRange(type.GetTypeInfo().Assembly.GetCustomAttributes().OfType<BenchmarkCategoryAttribute>()); - } - if (attributes.Count == 0) - return Array.Empty<string>(); - return attributes.SelectMany(attr => attr.Categories).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - } - private static ImmutableArray<BenchmarkCase> GetFilteredBenchmarks(IEnumerable<BenchmarkCase> benchmarks, IEnumerable<IFilter> filters) => benchmarks.Where(benchmark => filters.All(filter => filter.Predicate(benchmark))).ToImmutableArray(); diff --git a/src/BenchmarkDotNet/Running/DefaultCategoryDiscoverer.cs b/src/BenchmarkDotNet/Running/DefaultCategoryDiscoverer.cs new file mode 100644 index 0000000000..f883fbe744 --- /dev/null +++ b/src/BenchmarkDotNet/Running/DefaultCategoryDiscoverer.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BenchmarkDotNet.Attributes; + +namespace BenchmarkDotNet.Running +{ + public class DefaultCategoryDiscoverer : ICategoryDiscoverer + { + public static readonly ICategoryDiscoverer Instance = new DefaultCategoryDiscoverer(); + + private readonly bool inherit; + + public DefaultCategoryDiscoverer(bool inherit = true) + { + this.inherit = inherit; + } + + public virtual string[] GetCategories(MethodInfo method) + { + var attributes = new List<BenchmarkCategoryAttribute>(); + attributes.AddRange(method.GetCustomAttributes(typeof(BenchmarkCategoryAttribute), inherit).OfType<BenchmarkCategoryAttribute>()); + var type = method.ReflectedType; + if (type != null) + { + attributes.AddRange(type.GetTypeInfo().GetCustomAttributes(typeof(BenchmarkCategoryAttribute), inherit).OfType<BenchmarkCategoryAttribute>()); + attributes.AddRange(type.GetTypeInfo().Assembly.GetCustomAttributes().OfType<BenchmarkCategoryAttribute>()); + } + if (attributes.Count == 0) + return Array.Empty<string>(); + return attributes.SelectMany(attr => attr.Categories).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + } + } +} \ No newline at end of file diff --git a/src/BenchmarkDotNet/Running/ICategoryDiscoverer.cs b/src/BenchmarkDotNet/Running/ICategoryDiscoverer.cs new file mode 100644 index 0000000000..c9904ca97f --- /dev/null +++ b/src/BenchmarkDotNet/Running/ICategoryDiscoverer.cs @@ -0,0 +1,9 @@ +using System.Reflection; + +namespace BenchmarkDotNet.Running +{ + public interface ICategoryDiscoverer + { + string[] GetCategories(MethodInfo method); + } +} \ No newline at end of file
diff --git a/tests/BenchmarkDotNet.Tests/Configs/CategoriesTests.cs b/tests/BenchmarkDotNet.Tests/Configs/CategoriesTests.cs new file mode 100644 index 0000000000..28b0310a34 --- /dev/null +++ b/tests/BenchmarkDotNet.Tests/Configs/CategoriesTests.cs @@ -0,0 +1,136 @@ +using System; +using System.Linq; +using System.Reflection; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Running; +using Xunit; +using Xunit.Abstractions; + +namespace BenchmarkDotNet.Tests.Configs +{ + public class CategoriesTests + { + private readonly ITestOutputHelper output; + + public CategoriesTests(ITestOutputHelper output) + { + this.output = output; + } + + private void Check<T>(params string[] expected) + { + string Format(BenchmarkCase benchmarkCase) => + benchmarkCase.Descriptor.WorkloadMethod.Name + ": " + + string.Join("+", benchmarkCase.Descriptor.Categories.OrderBy(category => category)); + + var actual = BenchmarkConverter + .TypeToBenchmarks(typeof(T)) + .BenchmarksCases + .OrderBy(x => x.Descriptor.WorkloadMethod.Name) + .Select(Format) + .ToList(); + foreach (string s in actual) + output.WriteLine(s); + + Assert.Equal(expected, actual); + } + + [Fact] + public void CategoryInheritanceTest() => + Check<CategoryInheritanceTestScope.DerivedClass>( + "BaseMethod: BaseClassCategory+BaseMethodCategory+DerivedClassCategory", + "DerivedMethod: BaseClassCategory+DerivedClassCategory+DerivedMethodCategory" + ); + + public static class CategoryInheritanceTestScope + { + [BenchmarkCategory("BaseClassCategory")] + public class BaseClass + { + [Benchmark] + [BenchmarkCategory("BaseMethodCategory")] + public void BaseMethod() { } + } + + [BenchmarkCategory("DerivedClassCategory")] + public class DerivedClass : BaseClass + { + [Benchmark] + [BenchmarkCategory("DerivedMethodCategory")] + public void DerivedMethod() { } + } + } + + [Fact] + public void CategoryNoInheritanceTest() => + Check<CategoryNoInheritanceTestScope.DerivedClass>( + "BaseMethod: BaseMethodCategory+DerivedClassCategory", + "DerivedMethod: DerivedClassCategory+DerivedMethodCategory" + ); + + public static class CategoryNoInheritanceTestScope + { + [BenchmarkCategory("BaseClassCategory")] + public class BaseClass + { + [Benchmark] + [BenchmarkCategory("BaseMethodCategory")] + public void BaseMethod() { } + } + + [BenchmarkCategory("DerivedClassCategory")] + [CategoryDiscoverer(false)] + public class DerivedClass : BaseClass + { + [Benchmark] + [BenchmarkCategory("DerivedMethodCategory")] + public void DerivedMethod() { } + } + } + + [Fact] + public void CustomCategoryDiscovererTest() => + Check<CustomCategoryDiscovererTestScope.Benchmarks>( + "Aaa: A+PermanentCategory", + "Bbb: B+PermanentCategory" + ); + + public static class CustomCategoryDiscovererTestScope + { + private class CustomCategoryDiscoverer : ICategoryDiscoverer + { + public string[] GetCategories(MethodInfo method) + { + return new[] + { + "PermanentCategory", + method.Name.Substring(0, 1) + }; + } + } + + [AttributeUsage(AttributeTargets.Class)] + private class CustomCategoryDiscovererAttribute : Attribute, IConfigSource + { + public CustomCategoryDiscovererAttribute() + { + Config = ManualConfig.CreateEmpty().WithCategoryDiscoverer(new CustomCategoryDiscoverer()); + } + + public IConfig Config { get; } + } + + + [CustomCategoryDiscoverer] + public class Benchmarks + { + [Benchmark] + public void Aaa() { } + + [Benchmark] + public void Bbb() { } + } + } + } +} \ No newline at end of file
Allow for benchmark categories composition using inheritance I am writing some benchmarks over generic classes, and to do so I created base generic benchmark, something along these lines ```cs [BenchmarkCategory("Number")] public class MyBenchmark<T> where T : unmanaged, INumberBase<T> { public T V1; public T V2; [BenchmarkCategory("Add")] public T Add() { return V1 + V2; } [BenchmarkCategory("Multiply")] public T Multiply() { return V1 * V2; } [GlobalSetup] public virtual void Setup() { V1 = T.One + T.One; V2 = T.One + T.One + T.One; } } ``` Actual benchmarks are specialized over the generic type ```cs [BenchmarkCategory("Float")] public class MyFloatBenchmark : MyBenchmark<float> { [BenchmarkCategory("Sqrt")] public float Sqrt() { return float.Sqrt(V1); } } ``` The problem is that the category defined on the derived class is not assigned to the methods declared on the base class, because `BenchmarkConverter` [only looks at the method declaring type](https://github.com/dotnet/BenchmarkDotNet/blob/f32a2e753251afa7efb67f57fdbda1b18d5869fb/src/BenchmarkDotNet/Running/BenchmarkConverter.cs#L252). Moreover, the attribute on the derived class replaces the one defined on the base class, because the current resolution strategy [ignores inherited attributes](https://github.com/dotnet/BenchmarkDotNet/blob/f32a2e753251afa7efb67f57fdbda1b18d5869fb/src/BenchmarkDotNet/Running/BenchmarkConverter.cs#L255). Is there a reason why `method.ReflectedType` is not used in this case and inherited attributes are explicitly ignored (both at the class and method level)? So far, the only option is to replicate the categories on both the derived class and overridden method. Would it be possible to add an extension point to the `BenchmarkConverter` (e.g., an `ICategoryResolver` or a `CategoryResolver` delegate) to plug-in a different categories discovery logic?
null
2023-05-14T10:30:20Z
0.2
['BenchmarkDotNet.Tests.Configs.CategoriesTests.CategoryInheritanceTest', 'BenchmarkDotNet.Tests.Configs.CategoriesTests.CategoryNoInheritanceTest', 'BenchmarkDotNet.Tests.Configs.CategoriesTests.CustomCategoryDiscovererTest']
[]
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2304
492e58eb6f1e66ecc7d5b97f0aed6d78a20bccaa
diff --git a/docs/articles/samples/IntroComparableComplexParam.md b/docs/articles/samples/IntroComparableComplexParam.md new file mode 100644 index 0000000000..16319bab9c --- /dev/null +++ b/docs/articles/samples/IntroComparableComplexParam.md @@ -0,0 +1,20 @@ +--- +uid: BenchmarkDotNet.Samples.IntroComparableComplexParam +--- + +## Sample: IntroComparableComplexParam + +You can implement `IComparable` (the non generic version) on your complex parameter class if you want custom ordering behavior for your parameter. + +One use case for this is having a parameter class that overrides `ToString()`, but also providing a custom ordering behavior that isn't the alphabetical order of the result of `ToString()`. + +### Source code + +[!code-csharp[IntroComparableComplexParam.cs](../../../samples/BenchmarkDotNet.Samples/IntroComparableComplexParam.cs)] + +### Links + +* @docs.parameterization +* The permanent link to this sample: @BenchmarkDotNet.Samples.IntroComparableComplexParam + +--- \ No newline at end of file diff --git a/docs/articles/samples/toc.yml b/docs/articles/samples/toc.yml index 9d30bb4c64..098e457dd8 100644 --- a/docs/articles/samples/toc.yml +++ b/docs/articles/samples/toc.yml @@ -14,6 +14,8 @@ href: IntroCategoryBaseline.md - name: IntroColdStart href: IntroColdStart.md +- name: IntroComparableComplexParam + href: IntroComparableComplexParam.md - name: IntroConfigSource href: IntroConfigSource.md - name: IntroConfigUnion diff --git a/samples/BenchmarkDotNet.Samples/IntroComparableComplexParam.cs b/samples/BenchmarkDotNet.Samples/IntroComparableComplexParam.cs new file mode 100644 index 0000000000..4bb5cffb22 --- /dev/null +++ b/samples/BenchmarkDotNet.Samples/IntroComparableComplexParam.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using BenchmarkDotNet.Attributes; + +namespace BenchmarkDotNet.Samples +{ + public class IntroComparableComplexParam + { + [ParamsSource(nameof(ValuesForA))] + public ComplexParam A { get; set; } + + public IEnumerable<ComplexParam> ValuesForA => new[] { new ComplexParam(1, "First"), new ComplexParam(2, "Second") }; + + [Benchmark] + public object Benchmark() => A; + + // Only non generic IComparable is required to provide custom order behavior, but implementing IComparable<> too is customary. + public class ComplexParam : IComparable<ComplexParam>, IComparable + { + public ComplexParam(int value, string name) + { + Value = value; + Name = name; + } + + public int Value { get; set; } + + public string Name { get; set; } + + public override string ToString() => Name; + + public int CompareTo(ComplexParam other) => other == null ? 1 : Value.CompareTo(other.Value); + + public int CompareTo(object obj) => obj is ComplexParam other ? CompareTo(other) : throw new ArgumentException(); + } + } +} \ No newline at end of file diff --git a/src/BenchmarkDotNet/Parameters/ParameterComparer.cs b/src/BenchmarkDotNet/Parameters/ParameterComparer.cs index e5ae86d57b..a1363de073 100644 --- a/src/BenchmarkDotNet/Parameters/ParameterComparer.cs +++ b/src/BenchmarkDotNet/Parameters/ParameterComparer.cs @@ -7,16 +7,6 @@ internal class ParameterComparer : IComparer<ParameterInstances> { public static readonly ParameterComparer Instance = new ParameterComparer(); - // We will only worry about common, basic types, i.e. int, long, double, etc - // (e.g. you can't write [Params(10.0m, 20.0m, 100.0m, 200.0m)], the compiler won't let you!) - private static readonly Comparer PrimitiveComparer = new Comparer(). - Add((string x, string y) => string.CompareOrdinal(x, y)). - Add((int x, int y) => x.CompareTo(y)). - Add((long x, long y) => x.CompareTo(y)). - Add((short x, short y) => x.CompareTo(y)). - Add((float x, float y) => x.CompareTo(y)). - Add((double x, double y) => x.CompareTo(y)); - public int Compare(ParameterInstances x, ParameterInstances y) { if (x == null && y == null) return 0; @@ -24,35 +14,25 @@ public int Compare(ParameterInstances x, ParameterInstances y) if (x == null) return -1; for (int i = 0; i < Math.Min(x.Count, y.Count); i++) { - int compareTo = PrimitiveComparer.CompareTo(x[i]?.Value, y[i]?.Value); + var compareTo = CompareValues(x[i]?.Value, y[i]?.Value); if (compareTo != 0) return compareTo; } return string.CompareOrdinal(x.DisplayInfo, y.DisplayInfo); } - private class Comparer + private int CompareValues(object x, object y) { - private readonly Dictionary<Type, Func<object, object, int>> comparers = - new Dictionary<Type, Func<object, object, int>>(); - - public Comparer Add<T>(Func<T, T, int> compareFunc) - { - comparers.Add(typeof(T), (x, y) => compareFunc((T)x, (T)y)); - return this; - } - - public int CompareTo(object x, object y) + // Detect IComparable implementations. + // This works for all primitive types in addition to user types that implement IComparable. + if (x != null && y != null && x.GetType() == y.GetType() && + x is IComparable xComparable) { - return x != null && y != null && x.GetType() == y.GetType() && comparers.TryGetValue(GetComparisonType(x), out var comparer) - ? comparer(x, y) - : string.CompareOrdinal(x?.ToString(), y?.ToString()); + return xComparable.CompareTo(y); } - private static Type GetComparisonType(object x) => - x.GetType().IsEnum - ? x.GetType().GetEnumUnderlyingType() - : x.GetType(); + // Anything else. + return string.CompareOrdinal(x?.ToString(), y?.ToString()); } } } \ No newline at end of file
diff --git a/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs b/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs index f67e6b3d30..0f01045b5c 100644 --- a/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs +++ b/tests/BenchmarkDotNet.Tests/ParameterComparerTests.cs @@ -122,5 +122,82 @@ public void AlphaNumericComparisionTest() Assert.Equal(1000, sortedData[2].Items[0].Value); Assert.Equal(2000, sortedData[3].Items[0].Value); } + + [Fact] + public void IComparableComparisionTest() + { + var comparer = ParameterComparer.Instance; + + var originalData = new[] + { + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, new ComplexParameter(1, "first"), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, new ComplexParameter(3, "third"), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, new ComplexParameter(2, "second"), null) + }), + new ParameterInstances(new[] + { + new ParameterInstance(sharedDefinition, new ComplexParameter(4, "fourth"), null) + }) + }; + + var sortedData = originalData.OrderBy(d => d, comparer).ToArray(); + + // Check that we sort by numeric value, not string order!! + Assert.Equal(1, ((ComplexParameter)sortedData[0].Items[0].Value).Value); + Assert.Equal(2, ((ComplexParameter)sortedData[1].Items[0].Value).Value); + Assert.Equal(3, ((ComplexParameter)sortedData[2].Items[0].Value).Value); + Assert.Equal(4, ((ComplexParameter)sortedData[3].Items[0].Value).Value); + } + + private class ComplexParameter : IComparable<ComplexParameter>, IComparable + { + public ComplexParameter(int value, string name) + { + Value = value; + Name = name; + } + + public int Value { get; } + + public string Name { get; } + + public override string ToString() + { + return Name; + } + + public int CompareTo(ComplexParameter other) + { + if (other == null) + { + return 1; + } + + return Value.CompareTo(other.Value); + } + + public int CompareTo(object obj) + { + if (obj == null) + { + return 1; + } + + if (obj is not ComplexParameter other) + { + throw new ArgumentException(); + } + + return CompareTo(other); + } + } } } \ No newline at end of file
Custom order of parameters when using complex types I originally had the following `int` parameter: ```cs [Params(1_000, 10_000, 100_000, 1_000_000, 10_000_000)] public int N; ``` This sorted properly using the natural order of the `int`. I then wanted to customize the value names (1K, 1M, etc instead), so I had to wrap the `int` in a complex type to override `ToString()` (just a simple class with an `int` and a `string`, and then using a `ParamsSource` of a list). I now had correct names, but since the parameter is now a complex type, it appears that the display name is used to do an alphabetical sort instead. This causes the order to be something like "100K, 10K, 10M, 1K, etc" , which I definitely don't want. I can see the current implementation of this here: https://github.com/dotnet/BenchmarkDotNet/blob/56c66d01f0a26df676c6bf4ed4219afdc7695c96/src/BenchmarkDotNet/Parameters/ParameterComparer.cs#L31 As far as I can tell, there doesn't seem to be a way to get both a customized display but also ordering according to the integer (or some other custom ordering), without doing something extreme like having to provide an implementation of `IOrderer` for example (which doesn't seem at all feasible to me). I see a mention of a proposed `ParamsOrderPolicy` [here](https://github.com/dotnet/BenchmarkDotNet/issues/660#issuecomment-368267370), but I think that doesn't provide enough flexibility. I'm proposing a change in `ParameterComparer`, where complex params are tested if they're `IComparable`, and then simply use that interface to provide the order behavior. I'm willing to work on this, as I feel it's a must have feature.
> where complex params are tested if they're IComparable, and then simply use that interface to provide the order behavior. It's a great idea, thanks for the suggestion! > I'm willing to work on this, as I feel it's a must have feature. PR is welcome! Great! Will work on a PR soon.
2023-05-09T20:12:32Z
0.2
['BenchmarkDotNet.Tests.ParameterComparerTests.IComparableComparisionTest']
['BenchmarkDotNet.Tests.ParameterComparerTests.BasicComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.AlphaNumericComparisionTest', 'BenchmarkDotNet.Tests.ParameterComparerTests.MultiParameterComparisionTest']
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2280
0772ce21aa32914050ccf4339514e9bc05563ec0
diff --git a/src/BenchmarkDotNet/Configs/DefaultConfig.cs b/src/BenchmarkDotNet/Configs/DefaultConfig.cs index 2ee08c8169..9a8f0345f0 100644 --- a/src/BenchmarkDotNet/Configs/DefaultConfig.cs +++ b/src/BenchmarkDotNet/Configs/DefaultConfig.cs @@ -68,6 +68,7 @@ public IEnumerable<IValidator> GetValidators() yield return GenericBenchmarksValidator.DontFailOnError; yield return DeferredExecutionValidator.FailOnError; yield return ParamsAllValuesValidator.FailOnError; + yield return ParamsValidator.FailOnError; } public IOrderer Orderer => null; diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs index 56a1a6e8c4..ae4aa48b3f 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs @@ -27,7 +27,8 @@ public static class ImmutableConfigBuilder ShadowCopyValidator.DontFailOnError, JitOptimizationsValidator.DontFailOnError, DeferredExecutionValidator.DontFailOnError, - ParamsAllValuesValidator.FailOnError + ParamsAllValuesValidator.FailOnError, + ParamsValidator.FailOnError }; /// <summary> diff --git a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs index d3669d4029..b01d63d1be 100644 --- a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs @@ -3,33 +3,35 @@ using System.Linq; using System.Reflection; using BenchmarkDotNet.Attributes; -using JetBrains.Annotations; namespace BenchmarkDotNet.Extensions { internal static class ReflectionExtensions { - [PublicAPI] - internal static T ResolveAttribute<T>(this Type type) where T : Attribute => + internal static T? ResolveAttribute<T>(this Type? type) where T : Attribute => type?.GetTypeInfo().GetCustomAttributes(typeof(T), false).OfType<T>().FirstOrDefault(); - [PublicAPI] - internal static T ResolveAttribute<T>(this MethodInfo methodInfo) where T : Attribute => - methodInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + internal static T? ResolveAttribute<T>(this MemberInfo? memberInfo) where T : Attribute => + memberInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; - [PublicAPI] - internal static T ResolveAttribute<T>(this PropertyInfo propertyInfo) where T : Attribute => - propertyInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + internal static bool HasAttribute<T>(this MemberInfo? memberInfo) where T : Attribute => + memberInfo.ResolveAttribute<T>() != null; - [PublicAPI] - internal static T ResolveAttribute<T>(this FieldInfo fieldInfo) where T : Attribute => - fieldInfo?.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; + internal static bool IsNullable(this Type type) => Nullable.GetUnderlyingType(type) != null; - [PublicAPI] - internal static bool HasAttribute<T>(this MethodInfo methodInfo) where T : Attribute => - methodInfo.ResolveAttribute<T>() != null; + public static bool IsInitOnly(this PropertyInfo propertyInfo) + { + var setMethodReturnParameter = propertyInfo.SetMethod?.ReturnParameter; + if (setMethodReturnParameter == null) + return false; - internal static bool IsNullable(this Type type) => Nullable.GetUnderlyingType(type) != null; + var isExternalInitType = typeof(System.Runtime.CompilerServices.Unsafe).Assembly + .GetType("System.Runtime.CompilerServices.IsExternalInit"); + if (isExternalInitType == null) + return false; + + return setMethodReturnParameter.GetRequiredCustomModifiers().Contains(isExternalInitType); + } /// <summary> /// returns type name which can be used in generated C# code @@ -183,13 +185,13 @@ internal static (string Name, TAttribute Attribute, bool IsPrivate, bool IsStati return joined; } - internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, object argumentInstance) + internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, object? argumentInstance) { if (argumentInstance == null) return false; // IsByRefLikeAttribute is not exposed for older runtimes, so we need to check it in an ugly way ;) - bool isByRefLike = argumentType.GetCustomAttributes().Any(attribute => attribute.ToString().Contains("IsByRefLike")); + bool isByRefLike = argumentType.GetCustomAttributes().Any(attribute => attribute.ToString()?.Contains("IsByRefLike") ?? false); if (!isByRefLike) return false; diff --git a/src/BenchmarkDotNet/Validators/ParamsValidator.cs b/src/BenchmarkDotNet/Validators/ParamsValidator.cs new file mode 100644 index 0000000000..2a49dac434 --- /dev/null +++ b/src/BenchmarkDotNet/Validators/ParamsValidator.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Extensions; + +namespace BenchmarkDotNet.Validators +{ + public class ParamsValidator : IValidator + { + public static readonly ParamsValidator FailOnError = new (); + + public bool TreatsWarningsAsErrors => true; + + public IEnumerable<ValidationError> Validate(ValidationParameters input) => input.Benchmarks + .Select(benchmark => benchmark.Descriptor.Type) + .Distinct() + .SelectMany(Validate); + + private IEnumerable<ValidationError> Validate(Type type) + { + foreach (var memberInfo in type.GetMembers(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) + { + var attributes = new Attribute[] + { + memberInfo.ResolveAttribute<ParamsAttribute>(), + memberInfo.ResolveAttribute<ParamsAllValuesAttribute>(), + memberInfo.ResolveAttribute<ParamsSourceAttribute>() + } + .Where(attribute => attribute != null) + .ToList(); + if (attributes.IsEmpty()) + continue; + + string name = $"{type.Name}.{memberInfo.Name}"; + string? attributeString = string.Join(", ", attributes.Select(attribute => $"[{attribute.GetType().Name.Replace(nameof(Attribute), "")}]")); + + if (attributes.Count > 1) + yield return new ValidationError(TreatsWarningsAsErrors, + $"Unable to use {name} with {attributeString} at the same time. Please, use a single attribute."); + + if (memberInfo is FieldInfo fieldInfo && (fieldInfo.IsLiteral || fieldInfo.IsInitOnly)) + { + string modifier = fieldInfo.IsInitOnly ? "readonly" : "constant"; + yield return new ValidationError(TreatsWarningsAsErrors, + $"Unable to use {name} with {attributeString} because it's a {modifier} field. Please, remove the {modifier} modifier."); + } + + if (memberInfo is PropertyInfo propertyInfo && propertyInfo.IsInitOnly()) + { + yield return new ValidationError(TreatsWarningsAsErrors, + $"Unable to use {name} with {attributeString} because it's init-only. Please, provide a public setter."); + } + } + } + } +} \ No newline at end of file
diff --git a/tests/BenchmarkDotNet.Tests/Validators/ParamsValidatorTests.cs b/tests/BenchmarkDotNet.Tests/Validators/ParamsValidatorTests.cs new file mode 100644 index 0000000000..c33c0625e6 --- /dev/null +++ b/tests/BenchmarkDotNet.Tests/Validators/ParamsValidatorTests.cs @@ -0,0 +1,206 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Running; +using BenchmarkDotNet.Validators; +using Xunit; +using Xunit.Abstractions; + +namespace BenchmarkDotNet.Tests.Validators +{ + [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")] + [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] + public class ParamsValidatorTests + { + private readonly ITestOutputHelper output; + + public ParamsValidatorTests(ITestOutputHelper output) + { + this.output = output; + } + + private void Check<T>(params string[] messageParts) + { + var typeToBenchmarks = BenchmarkConverter.TypeToBenchmarks(typeof(T)); + Assert.NotEmpty(typeToBenchmarks.BenchmarksCases); + + var validationErrors = ParamsValidator.FailOnError.Validate(typeToBenchmarks).ToList(); + output.WriteLine("Number of validation errors: " + validationErrors.Count); + foreach (var error in validationErrors) + output.WriteLine("* " + error.Message); + + Assert.Single(validationErrors); + foreach (string messagePart in messageParts) + Assert.Contains(messagePart, validationErrors.Single().Message); + } + + private const string P = "[Params]"; + private const string Pa = "[ParamsAllValues]"; + private const string Ps = "[ParamsSource]"; + + [Fact] public void Const1Test() => Check<Const1>(nameof(Const1.Input), "constant", P); + [Fact] public void Const2Test() => Check<Const2>(nameof(Const2.Input), "constant", Pa); + [Fact] public void Const3Test() => Check<Const3>(nameof(Const3.Input), "constant", Ps); + [Fact] public void StaticReadonly1Test() => Check<StaticReadonly1>(nameof(StaticReadonly1.Input), "readonly", P); + [Fact] public void StaticReadonly2Test() => Check<StaticReadonly2>(nameof(StaticReadonly2.Input), "readonly", Pa); + [Fact] public void StaticReadonly3Test() => Check<StaticReadonly3>(nameof(StaticReadonly3.Input), "readonly", Ps); + [Fact] public void NonStaticReadonly1Test() => Check<NonStaticReadonly1>(nameof(NonStaticReadonly1.Input), "readonly", P); + [Fact] public void NonStaticReadonly2Test() => Check<NonStaticReadonly2>(nameof(NonStaticReadonly2.Input), "readonly", Pa); + [Fact] public void NonStaticReadonly3Test() => Check<NonStaticReadonly3>(nameof(NonStaticReadonly3.Input), "readonly", Ps); + [Fact] public void FieldMultiple1Test() => Check<FieldMultiple1>(nameof(FieldMultiple1.Input), "single attribute", P, Pa); + [Fact] public void FieldMultiple2Test() => Check<FieldMultiple2>(nameof(FieldMultiple2.Input), "single attribute", P, Ps); + [Fact] public void FieldMultiple3Test() => Check<FieldMultiple3>(nameof(FieldMultiple3.Input), "single attribute", Pa, Ps); + [Fact] public void FieldMultiple4Test() => Check<FieldMultiple4>(nameof(FieldMultiple4.Input), "single attribute", P, Pa, Ps); + [Fact] public void PropMultiple1Test() => Check<PropMultiple1>(nameof(PropMultiple1.Input), "single attribute", P, Pa); + [Fact] public void PropMultiple2Test() => Check<PropMultiple2>(nameof(PropMultiple2.Input), "single attribute", P, Ps); + [Fact] public void PropMultiple3Test() => Check<PropMultiple3>(nameof(PropMultiple3.Input), "single attribute", Pa, Ps); + [Fact] public void PropMultiple4Test() => Check<PropMultiple4>(nameof(PropMultiple4.Input), "single attribute", P, Pa, Ps); + + public class Base + { + [Benchmark] + public void Foo() { } + + public static IEnumerable<bool> Source() => new[] { false, true }; + } + + public class Const1 : Base + { + [Params(false, true)] + public const bool Input = false; + } + + public class Const2 : Base + { + [ParamsAllValues] + public const bool Input = false; + } + + public class Const3 : Base + { + [ParamsSource(nameof(Source))] + public const bool Input = false; + } + + public class StaticReadonly1 : Base + { + [Params(false, true)] + public static readonly bool Input = false; + } + + public class StaticReadonly2 : Base + { + [ParamsAllValues] + public static readonly bool Input = false; + } + + public class StaticReadonly3 : Base + { + [ParamsSource(nameof(Source))] + public static readonly bool Input = false; + } + + public class NonStaticReadonly1 : Base + { + [Params(false, true)] + public readonly bool Input = false; + } + + public class NonStaticReadonly2 : Base + { + [ParamsAllValues] + public readonly bool Input = false; + } + + public class NonStaticReadonly3 : Base + { + [ParamsSource(nameof(Source))] + public readonly bool Input = false; + } + + public class FieldMultiple1 : Base + { + [Params(false, true)] + [ParamsAllValues] + public bool Input = false; + } + + public class FieldMultiple2 : Base + { + [Params(false, true)] + [ParamsSource(nameof(Source))] + public bool Input = false; + } + + public class FieldMultiple3 : Base + { + [ParamsAllValues] + [ParamsSource(nameof(Source))] + public bool Input = false; + } + + public class FieldMultiple4 : Base + { + [Params(false, true)] + [ParamsAllValues] + [ParamsSource(nameof(Source))] + public bool Input = false; + } + + public class PropMultiple1 : Base + { + [Params(false, true)] + [ParamsAllValues] + public bool Input { get; set; } + } + + public class PropMultiple2 : Base + { + [Params(false, true)] + [ParamsSource(nameof(Source))] + public bool Input { get; set; } + } + + public class PropMultiple3 : Base + { + [ParamsAllValues] + [ParamsSource(nameof(Source))] + public bool Input { get; set; } + } + + public class PropMultiple4 : Base + { + [Params(false, true)] + [ParamsAllValues] + [ParamsSource(nameof(Source))] + public bool Input { get; set; } + } + +#if NET5_0_OR_GREATER + + [Fact] public void InitOnly1Test() => Check<InitOnly1>(nameof(InitOnly1.Input), "init-only", P); + [Fact] public void InitOnly2Test() => Check<InitOnly2>(nameof(InitOnly2.Input), "init-only", Pa); + [Fact] public void InitOnly3Test() => Check<InitOnly3>(nameof(InitOnly3.Input), "init-only", Ps); + + public class InitOnly1 : Base + { + [Params(false, true)] + public bool Input { get; init; } + } + + public class InitOnly2 : Base + { + [ParamsAllValues] + public bool Input { get; init; } + } + + public class InitOnly3 : Base + { + [ParamsSource(nameof(Source))] + public bool Input { get; init; } + } + +#endif + } +} \ No newline at end of file
Any combination of Params/ParamsSource/ParamsAllValues is broken ```C# [DryJob] public class Benchmarks { [Params("a", "b", "c")] [ParamsSource(nameof(Source))] public string Input { get; set; } [Benchmark] public void Test() { if(Input is "ddd" or "eee") Thread.Sleep(700); } public static IEnumerable<string> Source() { yield return "ddd"; yield return "eee"; } } ``` | Method | Input | Mean | |------- |------ |---------:| | Test | a | 702.3 ms | | Test | a | 710.1 ms | | Test | b | 706.1 ms | | Test | b | 714.9 ms | | Test | c | 707.2 ms | | Test | c | 707.1 ms | ### More interesting scenario is for Boolean: ```C# [DryJob] public class Benchmarks { [Params(false)] [ParamsSource(nameof(Source))] [ParamsAllValues] public bool Input { get; set; } [Benchmark] public void Test() { if(Input) Thread.Sleep(700); } public static IEnumerable<bool> Source() { yield return true; yield return true; yield return true; } } ``` | Method | Input | Mean | |------- |------ |-----------:| | Test | False | 1.085 ms | | Test | False | 1.134 ms | | Test | False | 1.261 ms | | Test | False | 705.045 ms | | Test | False | 707.033 ms | | Test | False | 713.798 ms | Some notes: - no `[Params]` or `[Params(true)]` changes all table's Input for true. - `[Params(false, false)` doubles the number of rows in the table. (6 rows for ~1ms, 6 rows for ~700ms) #### Change Source from `true, true, true` to `true, false, true`: | Input | Mean | |------ |-----------:| | False | 1.119 ms | | False | 714.345 ms | | False | 1.277 ms | | False | 1.127 ms | | False | 713.454 ms | | False | 715.087 ms | #### Change Source to `false, false, false`: It equals to `true, true, true`. | Input | Mean | |------ |-----------:| | False | 1.175 ms | | False | 1.456 ms | | False | 1.232 ms | | False | 715.423 ms | | False | 713.352 ms | | False | 707.733 ms | ##### Merry Christmas 🎄
Hi @YegorStepanov I am surprised that BDN is trying to make it work instead of just failing the benchmark validation. @AndreyAkinshin what is your opinion on this? Should we add a mandatory validator that says it's not supported? Or try to make it work?
2023-03-02T13:40:09Z
0.2
['BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.Const1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.Const2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.Const3Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.StaticReadonly1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.StaticReadonly2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.StaticReadonly3Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.NonStaticReadonly1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.NonStaticReadonly2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.NonStaticReadonly3Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.FieldMultiple1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.FieldMultiple2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.FieldMultiple3Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.FieldMultiple4Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.PropMultiple1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.PropMultiple2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.PropMultiple3Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.PropMultiple4Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.InitOnly1Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.InitOnly2Test', 'BenchmarkDotNet.Tests.Validators.ParamsValidatorTests.InitOnly3Test']
[]
dotnet/BenchmarkDotNet
dotnet__benchmarkdotnet-2254
512413ceb24077154bdf6d6306138accffe64c7a
diff --git a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs index e4b730aca3..17a01e87d5 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs @@ -250,6 +250,9 @@ private static IConfig CreateConfig(CommandLineOptions options, IConfig globalCo config.WithOption(ConfigOptions.ApplesToApples, options.ApplesToApples); config.WithOption(ConfigOptions.Resume, options.Resume); + if (config.Options.IsSet(ConfigOptions.GenerateMSBuildBinLog)) + config.Options |= ConfigOptions.KeepBenchmarkFiles; + if (options.MaxParameterColumnWidth.HasValue) config.WithSummaryStyle(SummaryStyle.Default.WithMaxParameterColumnWidth(options.MaxParameterColumnWidth.Value));
diff --git a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs index a0d5c57c3a..427b7d00ce 100644 --- a/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs +++ b/tests/BenchmarkDotNet.Tests/ConfigParserTests.cs @@ -291,7 +291,7 @@ public void DotNetCliParsedCorrectly(string tfm) [InlineData(ConfigOptions.StopOnFirstError, "--stopOnFirstError")] [InlineData(ConfigOptions.DisableLogFile, "--disableLogFile" )] [InlineData(ConfigOptions.LogBuildOutput, "--logBuildOutput")] - [InlineData(ConfigOptions.GenerateMSBuildBinLog, "--generateBinLog")] + [InlineData(ConfigOptions.GenerateMSBuildBinLog | ConfigOptions.KeepBenchmarkFiles, "--generateBinLog")] [InlineData( ConfigOptions.JoinSummary | ConfigOptions.KeepBenchmarkFiles |
msbuild binlog for the benchmark projects gets cleaned up too, making diagnosis of build impossible If you use `--generateBinLog` for wasm benchmarks, you get: ``` /home/helixbot/work/B78C09A9/p/dotnet/dotnet restore --packages "/home/helixbot/work/B78C09A9/w/BCE609B9/e/performance/artifacts/packages" /p:UseSharedCompilation=false /p:BuildInParallel=false /m:1 /p:Deterministic=true /p:Optimize=true -bl:8b197aae-5d64-4019-b6f4-46946d02dc65-restore.binlog in /home/helixbot/work/B78C09A9/w/BCE609B9/e/performance/artifacts/bin/for-running/MicroBenchmarks/8b197aae-5d64-4019-b6f4-46946d02dc65 ``` The binlog gets generated in `/home/helixbot/work/B78C09A9/w/BCE609B9/e/performance/artifacts/bin/for-running/MicroBenchmarks/8b197aae-5d64-4019-b6f4-46946d02dc65`, but that is getting cleaned up at the end, thus it is not retrievable later for diagnosis. It would be useful to maybe use some path in `artifacts` which does not get removed for these files. cc @adamsitnik
And related to that, a command line parameter to skip the cleanup would be useful too.
2023-01-20T08:27:52Z
0.2
[]
['BenchmarkDotNet.Tests.ConfigParserTests.UsersCanSpecifyWithoutOverheadEvalution', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyNoForceGCs', 'BenchmarkDotNet.Tests.ConfigParserTests.InvalidHardwareCounterNameMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanEasilyRequestToRunTheBenchmarkOncePerIteration', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyBuildTimeout', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseInfo', 'BenchmarkDotNet.Tests.ConfigParserTests.NetMonikersAreRecognizedAsNetCoreMonikers', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyCustomMaxParameterColumnWidth', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyEnvironmentVariables', 'BenchmarkDotNet.Tests.ConfigParserTests.DotNetCliParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyHowManyTimesTheBenchmarkShouldBeExecuted', 'BenchmarkDotNet.Tests.ConfigParserTests.SimpleConfigParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.SimpleConfigAlternativeVersionParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenConfigOptionsFlagsAreNotSpecifiedTheyAreNotSet', 'BenchmarkDotNet.Tests.ConfigParserTests.TooManyHardwareCounterNameMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyCustomDefaultJobAndOverwriteItsSettingsViaConsoleArgs', 'BenchmarkDotNet.Tests.ConfigParserTests.NonExistingPathMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanChooseStrategy', 'BenchmarkDotNet.Tests.ConfigParserTests.PackagesPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseDisassemblerWithCustomRecursiveDepth', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenCustomDisassemblerSettingsAreProvidedItsEnabledByDefault', 'BenchmarkDotNet.Tests.ConfigParserTests.CanParseHardwareCounters', 'BenchmarkDotNet.Tests.ConfigParserTests.WhenUserDoesNotSpecifyTimeoutTheDefaultValueIsUsed', 'BenchmarkDotNet.Tests.ConfigParserTests.UserCanSpecifyProcessPlatform', 'BenchmarkDotNet.Tests.ConfigParserTests.IlCompilerPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.ConfigOptionsParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.PlatformSpecificMonikersAreSupported', 'BenchmarkDotNet.Tests.ConfigParserTests.MonoPathParsedCorrectly', 'BenchmarkDotNet.Tests.ConfigParserTests.CanCompareFewDifferentRuntimes', 'BenchmarkDotNet.Tests.ConfigParserTests.InvalidEnvVarAreRecognized', 'BenchmarkDotNet.Tests.ConfigParserTests.EmptyArgsMeansConfigWithoutJobs', 'BenchmarkDotNet.Tests.ConfigParserTests.CanUseStatisticalTestsToCompareFewDifferentRuntimes', 'BenchmarkDotNet.Tests.ConfigParserTests.SpecifyingInvalidStatisticalTestsThresholdMeansFailure', 'BenchmarkDotNet.Tests.ConfigParserTests.NetFrameworkMonikerParsedCorrectly']
App-vNext/Polly
polly-2164
5d81f99ef5f523032c17b6b59b32d575ec9dfb06
diff --git a/src/Polly.Core/Retry/RetryHelper.cs b/src/Polly.Core/Retry/RetryHelper.cs index 35d3e5825eb..1acbbf8f6cc 100644 --- a/src/Polly.Core/Retry/RetryHelper.cs +++ b/src/Polly.Core/Retry/RetryHelper.cs @@ -6,6 +6,11 @@ internal static class RetryHelper private const double ExponentialFactor = 2.0; + // Upper-bound to prevent overflow beyond TimeSpan.MaxValue. Potential truncation during conversion from double to long + // (as described at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions) + // is avoided by the arbitrary subtraction of 1,000. + private static readonly double MaxTimeSpanTicks = (double)TimeSpan.MaxValue.Ticks - 1_000; + public static bool IsValidDelay(TimeSpan delay) => delay >= TimeSpan.Zero; public static TimeSpan GetRetryDelay( @@ -101,20 +106,27 @@ private static TimeSpan DecorrelatedJitterBackoffV2(int attempt, TimeSpan baseDe // This factor allows the median values to fall approximately at 1, 2, 4 etc seconds, instead of 1.4, 2.8, 5.6, 11.2. const double RpScalingFactor = 1 / 1.4d; - // Upper-bound to prevent overflow beyond TimeSpan.MaxValue. Potential truncation during conversion from double to long - // (as described at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/numeric-conversions) - // is avoided by the arbitrary subtraction of 1000. Validated by unit-test Backoff_should_not_overflow_to_give_negative_timespan. - double maxTimeSpanDouble = (double)TimeSpan.MaxValue.Ticks - 1000; - long targetTicksFirstDelay = baseDelay.Ticks; double t = attempt + randomizer(); double next = Math.Pow(ExponentialFactor, t) * Math.Tanh(Math.Sqrt(PFactor * t)); + // At t >=1024, the above will tend to infinity which would otherwise cause the + // ticks to go negative. See https://github.com/App-vNext/Polly/issues/2163. + if (double.IsInfinity(next)) + { + prev = next; + return TimeSpan.FromTicks((long)MaxTimeSpanTicks); + } + double formulaIntrinsicValue = next - prev; prev = next; - return TimeSpan.FromTicks((long)Math.Min(formulaIntrinsicValue * RpScalingFactor * targetTicksFirstDelay, maxTimeSpanDouble)); + long ticks = (long)Math.Min(formulaIntrinsicValue * RpScalingFactor * targetTicksFirstDelay, MaxTimeSpanTicks); + + Debug.Assert(ticks >= 0, "ticks cannot be negative"); + + return TimeSpan.FromTicks(ticks); } #pragma warning disable IDE0047 // Remove unnecessary parentheses which offer less mental gymnastics diff --git a/src/Polly.Core/Retry/RetryResilienceStrategy.cs b/src/Polly.Core/Retry/RetryResilienceStrategy.cs index 0b9dfbacde1..484b78d48cf 100644 --- a/src/Polly.Core/Retry/RetryResilienceStrategy.cs +++ b/src/Polly.Core/Retry/RetryResilienceStrategy.cs @@ -75,6 +75,8 @@ protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func } } + Debug.Assert(delay >= TimeSpan.Zero, "The delay cannot be negative."); + var onRetryArgs = new OnRetryArguments<T>(context, outcome, attempt, delay, executionTime); _telemetry.Report<OnRetryArguments<T>, T>(new(ResilienceEventSeverity.Warning, RetryConstants.OnRetryEvent), onRetryArgs);
diff --git a/test/Polly.Core.Tests/Issues/IssuesTests.InfiniteRetry_2163.cs b/test/Polly.Core.Tests/Issues/IssuesTests.InfiniteRetry_2163.cs new file mode 100644 index 00000000000..518e47549fc --- /dev/null +++ b/test/Polly.Core.Tests/Issues/IssuesTests.InfiniteRetry_2163.cs @@ -0,0 +1,59 @@ +using Microsoft.Extensions.Time.Testing; +using Polly.Retry; + +namespace Polly.Core.Tests.Issues; + +public partial class IssuesTests +{ + [Fact(Timeout = 15_000)] + public async Task InfiniteRetry_Delay_Does_Not_Overflow_2163() + { + // Arrange + int attempts = 0; + int succeedAfter = 2049; + + var options = new RetryStrategyOptions<bool> + { + BackoffType = DelayBackoffType.Exponential, + Delay = TimeSpan.FromSeconds(2), + MaxDelay = TimeSpan.FromSeconds(30), + MaxRetryAttempts = int.MaxValue, + UseJitter = true, + OnRetry = (args) => + { + args.RetryDelay.Should().BeGreaterThan(TimeSpan.Zero, $"RetryDelay is less than zero after {args.AttemptNumber} attempts"); + attempts++; + return default; + }, + ShouldHandle = (args) => new ValueTask<bool>(!args.Outcome.Result), + }; + + var listener = new FakeTelemetryListener(); + var telemetry = TestUtilities.CreateResilienceTelemetry(listener); + var timeProvider = new FakeTimeProvider(); + + var strategy = new RetryResilienceStrategy<bool>(options, timeProvider, telemetry); + var pipeline = strategy.AsPipeline(); + + using var cts = new CancellationTokenSource(Debugger.IsAttached ? TimeSpan.MaxValue : TimeSpan.FromSeconds(10)); + + // Act + var executing = pipeline.ExecuteAsync((_) => + { + return new ValueTask<bool>(attempts >= succeedAfter); + }, cts.Token); + + while (!executing.IsCompleted && !cts.IsCancellationRequested) + { + timeProvider.Advance(TimeSpan.FromSeconds(1)); + } + + // Assert + cts.Token.ThrowIfCancellationRequested(); + + var actual = await executing; + + actual.Should().BeTrue(); + attempts.Should().Be(succeedAfter); + } +} diff --git a/test/Polly.Core.Tests/Retry/RetryHelperTests.cs b/test/Polly.Core.Tests/Retry/RetryHelperTests.cs index b5988eac425..be770eca1e9 100644 --- a/test/Polly.Core.Tests/Retry/RetryHelperTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryHelperTests.cs @@ -8,6 +8,24 @@ public class RetryHelperTests { private Func<double> _randomizer = new RandomUtil(0).NextDouble; + public static TheoryData<int> Attempts() + { +#pragma warning disable IDE0028 + return new() + { + 1, + 2, + 3, + 4, + 10, + 100, + 1_000, + 1_024, + 1_025, + }; +#pragma warning restore IDE0028 + } + [Fact] public void IsValidDelay_Ok() { @@ -187,14 +205,51 @@ public void GetRetryDelay_OverflowWithMaxDelay_ReturnsMaxDelay() RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1000, TimeSpan.FromDays(1), TimeSpan.FromDays(2), ref state, _randomizer).Should().Be(TimeSpan.FromDays(2)); } - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(4)] - [InlineData(10)] - [InlineData(100)] - [InlineData(1000)] [Theory] + [MemberData(nameof(Attempts))] + public void GetRetryDelay_Exponential_Is_Positive_When_No_Maximum_Delay(int attempt) + { + var jitter = true; + var type = DelayBackoffType.Exponential; + + var baseDelay = TimeSpan.FromSeconds(2); + TimeSpan? maxDelay = null; + + var random = new RandomUtil(0).NextDouble; + double state = 0; + + var first = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); + var second = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); + + first.Should().BePositive(); + second.Should().BePositive(); + } + + [Theory] + [MemberData(nameof(Attempts))] + public void GetRetryDelay_Exponential_Does_Not_Exceed_MaxDelay(int attempt) + { + var jitter = true; + var type = DelayBackoffType.Exponential; + + var baseDelay = TimeSpan.FromSeconds(2); + var maxDelay = TimeSpan.FromSeconds(30); + + var random = new RandomUtil(0).NextDouble; + double state = 0; + + var first = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); + var second = RetryHelper.GetRetryDelay(type, jitter, attempt, baseDelay, maxDelay, ref state, random); + + first.Should().BePositive(); + first.Should().BeLessThanOrEqualTo(maxDelay); + + second.Should().BePositive(); + second.Should().BeLessThanOrEqualTo(maxDelay); + } + + [Theory] + [MemberData(nameof(Attempts))] public void ExponentialWithJitter_Ok(int count) { var delay = TimeSpan.FromSeconds(7.8); @@ -203,6 +258,7 @@ public void ExponentialWithJitter_Ok(int count) newDelays.Should().ContainInConsecutiveOrder(oldDelays); newDelays.Should().HaveCount(oldDelays.Count); + newDelays.Should().AllSatisfy(delay => delay.Should().BePositive()); } [Fact] @@ -213,6 +269,7 @@ public void ExponentialWithJitter_EnsureRandomness() var delays2 = GetExponentialWithJitterBackoff(false, delay, 100, RandomUtil.Instance.NextDouble); delays1.SequenceEqual(delays2).Should().BeFalse(); + delays1.Should().AllSatisfy(delay => delay.Should().BePositive()); } private static IReadOnlyList<TimeSpan> GetExponentialWithJitterBackoff(bool contrib, TimeSpan baseDelay, int retryCount, Func<double>? randomizer = null) diff --git a/test/Polly.Core.Tests/Utils/CancellationTokenSourcePoolTests.cs b/test/Polly.Core.Tests/Utils/CancellationTokenSourcePoolTests.cs index 4774aa9844a..b522ad52c34 100644 --- a/test/Polly.Core.Tests/Utils/CancellationTokenSourcePoolTests.cs +++ b/test/Polly.Core.Tests/Utils/CancellationTokenSourcePoolTests.cs @@ -24,7 +24,9 @@ public void ArgValidation_Ok() pool.Get(System.Threading.Timeout.InfiniteTimeSpan).Should().NotBeNull(); } +#pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [MemberData(nameof(TimeProviders))] +#pragma warning restore xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [Theory] public void RentReturn_Reusable_EnsureProperBehavior(object timeProvider) { @@ -48,7 +50,9 @@ public void RentReturn_Reusable_EnsureProperBehavior(object timeProvider) #endif } +#pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [MemberData(nameof(TimeProviders))] +#pragma warning restore xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [Theory] public void RentReturn_NotReusable_EnsureProperBehavior(object timeProvider) { @@ -63,7 +67,9 @@ public void RentReturn_NotReusable_EnsureProperBehavior(object timeProvider) cts2.Token.Should().NotBeNull(); } +#pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [MemberData(nameof(TimeProviders))] +#pragma warning restore xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [Theory] public async Task Rent_Cancellable_EnsureCancelled(object timeProvider) { @@ -80,7 +86,9 @@ public async Task Rent_Cancellable_EnsureCancelled(object timeProvider) await TestUtilities.AssertWithTimeoutAsync(() => cts.IsCancellationRequested.Should().BeTrue()); } +#pragma warning disable xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [MemberData(nameof(TimeProviders))] +#pragma warning restore xUnit1042 // The member referenced by the MemberData attribute returns untyped data rows [Theory] public async Task Rent_NotCancellable_EnsureNotCancelled(object timeProvider) {
[Bug]: `GetRetryDelay` goes NEGATIVE after 1025 attempts [High Risk Issue] ### Describe the bug Retry delay goes negative after 1025 retries causing instant retries for all subsequent retry attempts. The issue stems from the following line which tends to infinity: ``` double next = Math.Pow(ExponentialFactor, t) * Math.Tanh(Math.Sqrt(PFactor * t)); ``` This causes the following `formulaIntrinsicValue = Infinity - Infinity;` which in turn returns `NaN` and leads to the negative timespan result. ### Expected behavior It continues to respect the maximum retry delay and is impossible for a negative retry to be returned from a resilience pipeline. ### Actual behavior The next retry delay goes to maximum negative value which causes the resilience execution to retry instantly. This causes a run away execution pipeline when `Unlimited` number of retries are selected. ### Steps to reproduce Using the class instances from the Polly directly you can replicate the error using the following simple program: ``` var attempt = 1; var state = 0d; var nextTime = TimeSpan.FromSeconds(1); while (nextTime > TimeSpan.Zero) { nextTime = RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, true, attempt++, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(30), ref state, RandomUtil.Instance.NextDouble); Console.WriteLine($"Attempt {attempt}: {nextTime}"); } ``` Generated output: ``` Attempt 1022: 00:00:30 Attempt 1023: 00:00:30 Attempt 1024: 00:00:30 Attempt 1025: 00:00:30 Attempt 1026: -10675199.02:48:05.4775808 ``` ### Exception(s) (if any) _No response_ ### Polly version 8.4.0, main ### .NET Version net8.0 ### Anything else? Work around is to add the following condition to the `DelayGenerator` function to avoid the overflow scenario: ``` retry.DelayGenerator = static args => { if (args.AttemptNumber > 1024) { return ValueTask.FromResult<TimeSpan?>(TimeSpan.FromSeconds(30)); } return new ValueTask<TimeSpan?>((TimeSpan?)null); }; ``` Identified originally when using the following resilience options in production code: ``` private static RetryStrategyOptions DefaultRetryStrategy => new() { BackoffType = DelayBackoffType.Exponential, Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(30), MaxRetryAttempts = int.MaxValue, UseJitter = true }; ```
Example of run away behaviour; logged output from a test server: ``` 2024-06-22T00:45:07.3018022+00:00 [WRN] SignalRClient connection attempt 1021 failed. Retrying in 30 secs. 2024-06-22T00:45:37.3171715+00:00 [WRN] SignalRClient connection attempt 1022 failed. Retrying in 30 secs. 2024-06-22T00:46:07.3226994+00:00 [WRN] SignalRClient connection attempt 1023 failed. Retrying in 30 secs. 2024-06-22T00:46:37.3357127+00:00 [WRN] SignalRClient connection attempt 1024 failed. Retrying in 30 secs. 2024-06-22T00:47:07.4416703+00:00 [WRN] SignalRClient connection attempt 1025 failed. Retrying in -2147483.648 secs. 2024-06-22T00:47:04.5259173+00:00 [WRN] SignalRClient connection attempt 1026 failed. Retrying in -2147483.648 secs. 2024-06-22T00:47:04.5354682+00:00 [WRN] SignalRClient connection attempt 1027 failed. Retrying in -2147483.648 secs. 2024-06-22T00:47:04.5440102+00:00 [WRN] SignalRClient connection attempt 1028 failed. Retrying in -2147483.648 secs. 2024-06-22T00:47:04.5496702+00:00 [WRN] SignalRClient connection attempt 1029 failed. Retrying in -2147483.648 secs. 2024-06-22T00:47:04.5554510+00:00 [WRN] SignalRClient connection attempt 1030 failed. Retrying in -2147483.648 secs. ``` Your suggested workaround won't help here. If you do specify the `DelayGenerator` then there is an explicit null or less than zero check: https://github.com/App-vNext/Polly/blob/5d81f99ef5f523032c17b6b59b32d575ec9dfb06/src/Polly.Core/Retry/RetryResilienceStrategy.cs#L72 ```cs var delay = RetryHelper.GetRetryDelay(BackoffType, UseJitter, attempt, BaseDelay, MaxDelay, ref retryState, _randomizer); if (DelayGenerator is not null) { var delayArgs = new RetryDelayGeneratorArguments<T>(context, outcome, attempt); if (await DelayGenerator(delayArgs).ConfigureAwait(false) is TimeSpan newDelay && RetryHelper.IsValidDelay(newDelay)) { delay = newDelay; } } ``` where the `IsValidDelay` is ```cs public static bool IsValidDelay(TimeSpan delay) => delay >= TimeSpan.Zero; ``` So, if you use `DelayGenerator` then you don't have this problem. ____ @martincostello Please assign me this ticket if it is not super urgent. I will have time on Thursday for this. I was about to pick this up myself, but I'm happy to leave it for you to look into if you want to. @martincostello If you have time for this today then take it.
2024-06-25T09:40:07Z
0.1
['Polly.Core.Tests.Issues.IssuesTests.InfiniteRetry_Delay_Does_Not_Overflow_2163', 'Polly.Core.Tests.Retry.RetryHelperTests.GetRetryDelay_Exponential_Is_Positive_When_No_Maximum_Delay', 'Polly.Core.Tests.Retry.RetryHelperTests.GetRetryDelay_Exponential_Does_Not_Exceed_MaxDelay', 'Polly.Core.Tests.Retry.RetryHelperTests.ExponentialWithJitter_Ok']
[]
App-vNext/Polly
polly-2068
ef8459480e003e5eb97be8f05218cfdafde9e28a
diff --git a/src/Polly.Core/PublicAPI.Unshipped.txt b/src/Polly.Core/PublicAPI.Unshipped.txt index ab058de62d4..e49c0f73fd7 100644 --- a/src/Polly.Core/PublicAPI.Unshipped.txt +++ b/src/Polly.Core/PublicAPI.Unshipped.txt @@ -1,1 +1,4 @@ #nullable enable +static Polly.ResiliencePipelineBuilderExtensions.AddStrategy(this Polly.ResiliencePipelineBuilder! builder, System.Func<Polly.StrategyBuilderContext!, Polly.ResilienceStrategy<object!>!>! factory) -> Polly.ResiliencePipelineBuilder! +static Polly.ResiliencePipelineBuilderExtensions.AddStrategy<TBuilder>(this TBuilder! builder, System.Func<Polly.StrategyBuilderContext!, Polly.ResilienceStrategy!>! factory) -> TBuilder! +static Polly.ResiliencePipelineBuilderExtensions.AddStrategy<TResult>(this Polly.ResiliencePipelineBuilder<TResult>! builder, System.Func<Polly.StrategyBuilderContext!, Polly.ResilienceStrategy<TResult>!>! factory) -> Polly.ResiliencePipelineBuilder<TResult>! diff --git a/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs b/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs index 7b450ccabb9..0b5a4b06160 100644 --- a/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs +++ b/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs @@ -60,13 +60,16 @@ public static ResiliencePipelineBuilder<TResult> AddPipeline<TResult>(this Resil /// <typeparam name="TBuilder">The builder type.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="factory">The factory that creates a resilience strategy.</param> - /// <param name="options">The options associated with the strategy. If none are provided the default instance of <see cref="ResilienceStrategyOptions"/> is created.</param> + /// <param name="options">The options associated with the strategy.</param> /// <returns>The same builder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="factory"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> is invalid.</exception> [RequiresUnreferencedCode(Constants.OptionsValidation)] - public static TBuilder AddStrategy<TBuilder>(this TBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy> factory, ResilienceStrategyOptions options) + public static TBuilder AddStrategy<TBuilder>( + this TBuilder builder, + Func<StrategyBuilderContext, ResilienceStrategy> factory, + ResilienceStrategyOptions options) where TBuilder : ResiliencePipelineBuilderBase { Guard.NotNull(builder); @@ -82,14 +85,15 @@ public static TBuilder AddStrategy<TBuilder>(this TBuilder builder, Func<Strateg /// </summary> /// <param name="builder">The builder instance.</param> /// <param name="factory">The factory that creates a resilience strategy.</param> - /// <param name="options">The options associated with the strategy. If none are provided the default instance of <see cref="ResilienceStrategyOptions"/> is created.</param> + /// <param name="options">The options associated with the strategy.</param> /// <returns>The same builder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="factory"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> is invalid.</exception> [RequiresUnreferencedCode(Constants.OptionsValidation)] public static ResiliencePipelineBuilder AddStrategy( - this ResiliencePipelineBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy<object>> factory, + this ResiliencePipelineBuilder builder, + Func<StrategyBuilderContext, ResilienceStrategy<object>> factory, ResilienceStrategyOptions options) { Guard.NotNull(builder); @@ -106,14 +110,15 @@ public static ResiliencePipelineBuilder AddStrategy( /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="builder">The builder instance.</param> /// <param name="factory">The factory that creates a resilience strategy.</param> - /// <param name="options">The options associated with the strategy. If none are provided the default instance of <see cref="ResilienceStrategyOptions"/> is created.</param> + /// <param name="options">The options associated with the strategy.</param> /// <returns>The same builder instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/>, <paramref name="factory"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> is invalid.</exception> [RequiresUnreferencedCode(Constants.OptionsValidation)] public static ResiliencePipelineBuilder<TResult> AddStrategy<TResult>( - this ResiliencePipelineBuilder<TResult> builder, Func<StrategyBuilderContext, ResilienceStrategy<TResult>> factory, + this ResiliencePipelineBuilder<TResult> builder, + Func<StrategyBuilderContext, ResilienceStrategy<TResult>> factory, ResilienceStrategyOptions options) { Guard.NotNull(builder); @@ -124,6 +129,78 @@ public static ResiliencePipelineBuilder<TResult> AddStrategy<TResult>( return builder; } + /// <summary> + /// Adds a reactive resilience strategy to the builder. + /// </summary> + /// <typeparam name="TBuilder">The builder type.</typeparam> + /// <param name="builder">The builder instance.</param> + /// <param name="factory">The strategy factory.</param> + /// <returns>The same builder instance.</returns> + /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="factory"/> is <see langword="null"/>.</exception> + /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> + [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(EmptyOptions))] + [UnconditionalSuppressMessage( + "Trimming", + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", + Justification = "All options members preserved for the empty options.")] + public static TBuilder AddStrategy<TBuilder>( + this TBuilder builder, + Func<StrategyBuilderContext, ResilienceStrategy> factory) + where TBuilder : ResiliencePipelineBuilderBase + { + Guard.NotNull(builder); + Guard.NotNull(factory); + + return builder.AddStrategy(factory, EmptyOptions.Instance); + } + + /// <summary> + /// Adds a proactive resilience strategy to the builder. + /// </summary> + /// <param name="builder">The builder instance.</param> + /// <param name="factory">The strategy instance.</param> + /// <returns>The same builder instance.</returns> + /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="factory"/> is <see langword="null"/>.</exception> + /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> + [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(EmptyOptions))] + [UnconditionalSuppressMessage( + "Trimming", + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", + Justification = "All options members preserved for the empty options.")] + public static ResiliencePipelineBuilder AddStrategy( + this ResiliencePipelineBuilder builder, + Func<StrategyBuilderContext, ResilienceStrategy<object>> factory) + { + Guard.NotNull(builder); + Guard.NotNull(factory); + + return builder.AddStrategy(factory, EmptyOptions.Instance); + } + + /// <summary> + /// Adds a reactive resilience strategy to the builder. + /// </summary> + /// <typeparam name="TResult">The result type.</typeparam> + /// <param name="builder">The builder instance.</param> + /// <param name="factory">The strategy instance.</param> + /// <returns>The same builder instance.</returns> + /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="factory"/> is <see langword="null"/>.</exception> + /// <exception cref="InvalidOperationException">Thrown when this builder was already used to create a pipeline. The builder cannot be modified after it has been used.</exception> + [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(EmptyOptions))] + [UnconditionalSuppressMessage( + "Trimming", + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", + Justification = "All options members preserved for the empty options.")] + public static ResiliencePipelineBuilder<TResult> AddStrategy<TResult>( + this ResiliencePipelineBuilder<TResult> builder, + Func<StrategyBuilderContext, ResilienceStrategy<TResult>> factory) + { + Guard.NotNull(builder); + Guard.NotNull(factory); + + return builder.AddStrategy(factory, EmptyOptions.Instance); + } + internal sealed class EmptyOptions : ResilienceStrategyOptions { public static readonly EmptyOptions Instance = new();
diff --git a/test/Polly.Core.Tests/GenericResiliencePipelineBuilderTests.cs b/test/Polly.Core.Tests/GenericResiliencePipelineBuilderTests.cs index 5a7a166eec2..62bad5fef7d 100644 --- a/test/Polly.Core.Tests/GenericResiliencePipelineBuilderTests.cs +++ b/test/Polly.Core.Tests/GenericResiliencePipelineBuilderTests.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Time.Testing; using NSubstitute; +using Polly.Testing; using Polly.Utils.Pipeline; namespace Polly.Core.Tests; @@ -63,4 +64,19 @@ public void AddGenericStrategy_Ok() .Should() .Be(strategy); } + + [Fact] + public void AddStrategy_ExplicitInstance_Ok() + { + var builder = new ResiliencePipelineBuilder<string>(); + var strategy = Substitute.For<ResilienceStrategy<string>>(); + + builder.AddStrategy(_ => strategy); + + builder + .Build() + .GetPipelineDescriptor() + .FirstStrategy.StrategyInstance.Should() + .BeSameAs(strategy); + } } diff --git a/test/Polly.Core.Tests/ResiliencePipelineBuilderTests.cs b/test/Polly.Core.Tests/ResiliencePipelineBuilderTests.cs index 43e1b48acd5..160793dc4be 100644 --- a/test/Polly.Core.Tests/ResiliencePipelineBuilderTests.cs +++ b/test/Polly.Core.Tests/ResiliencePipelineBuilderTests.cs @@ -114,6 +114,36 @@ public void AddPipeline_Multiple_Ok() executions.Should().HaveCount(7); } + [Fact] + public void AddStrategy_ExplicitProactiveInstance_Ok() + { + var builder = new ResiliencePipelineBuilder(); + var strategy = new TestResilienceStrategy(); + + builder.AddStrategy(_ => strategy); + + builder + .Build() + .GetPipelineDescriptor() + .FirstStrategy.StrategyInstance.Should() + .BeSameAs(strategy); + } + + [Fact] + public void AddStrategy_ExplicitReactiveInstance_Ok() + { + var builder = new ResiliencePipelineBuilder(); + var strategy = Substitute.For<ResilienceStrategy<object>>(); + + builder.AddStrategy(_ => strategy); + + builder + .Build() + .GetPipelineDescriptor() + .FirstStrategy.StrategyInstance.Should() + .BeSameAs(strategy); + } + [Fact] public void Validator_Ok() {
[Feature request]: Add AddStrategy API with no options ### Is your feature request related to a specific problem? Or an existing feature? The `AddStrategy` extension methods take a `ResilienceStrategyOptions options` argument, which gets validated using DataAnnotations. This makes the method incompatible with trimming and native AOT, and it is annotated as such: https://github.com/App-vNext/Polly/blob/82474bf10b5097d4bf6934100c9daa1efdb02f4b/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs#L68-L70 https://github.com/App-vNext/Polly/blob/82474bf10b5097d4bf6934100c9daa1efdb02f4b/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs#L90-L93 https://github.com/App-vNext/Polly/blob/82474bf10b5097d4bf6934100c9daa1efdb02f4b/src/Polly.Core/ResiliencePipelineBuilderExtensions.cs#L114-L117 Callers who want to use this API in a trim compatible way need to define an empty class derived from `ResilienceStrategyOptions` and suppress the warning from calling this API. ### Describe the solution you'd like We should add overloads to these `AddStrategy` methods that are trim compatible, and don't take an `options` argument. Similar to the `AddPipeline` methods. ```diff [RequiresUnreferencedCode(Constants.OptionsValidation)] public static TBuilder AddStrategy<TBuilder>(this TBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy> factory, ResilienceStrategyOptions options) where TBuilder : ResiliencePipelineBuilderBase {} +public static TBuilder AddStrategy<TBuilder>(this TBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy> factory) + where TBuilder : ResiliencePipelineBuilderBase {} [RequiresUnreferencedCode(Constants.OptionsValidation)] public static ResiliencePipelineBuilder AddStrategy( this ResiliencePipelineBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy<object>> factory, ResilienceStrategyOptions options) {} +public static ResiliencePipelineBuilder AddStrategy( + this ResiliencePipelineBuilder builder, Func<StrategyBuilderContext, ResilienceStrategy<object>> factory) {} [RequiresUnreferencedCode(Constants.OptionsValidation)] public static ResiliencePipelineBuilder<TResult> AddStrategy<TResult>( this ResiliencePipelineBuilder<TResult> builder, Func<StrategyBuilderContext, ResilienceStrategy<TResult>> factory, ResilienceStrategyOptions options) {} + public static ResiliencePipelineBuilder<TResult> AddStrategy<TResult>( + this ResiliencePipelineBuilder<TResult> builder, Func<StrategyBuilderContext, ResilienceStrategy<TResult>> factory) {} ``` ### Additional context This is being used by Microsoft.Extensions.Http.Resilience here: https://github.com/dotnet/extensions/pull/4962#discussion_r1497965809 Adding this API would make the caller simpler. It wouldn't need to declare an empty class, and suppress the trim warning.
Seems reasonable to me, plus would make the API easier to use even without wanting to use AoT. This seems to be actually a bug, at least in the documentation. The `options` parameter in the `ResiliencePipelineBuilderExtensions.AddStrategy` methods is described like this: > The options associated with the strategy. If none are provided the default instance of ResilienceStrategyOptions is created. So one would expect the parameter already to be optional. There is the ´EmptyOptions´ class, but it's internal, so I need to copy it if I don't need any options for my strategy.
2024-04-22T00:24:21Z
0.1
['Polly.Core.Tests.GenericResiliencePipelineBuilderTests.AddStrategy_ExplicitInstance_Ok']
['Polly.Core.Tests.GenericResiliencePipelineBuilderTests.AddGenericStrategy_Ok', 'Polly.Core.Tests.GenericResiliencePipelineBuilderTests.Ctor_EnsureDefaults', 'Polly.Core.Tests.GenericResiliencePipelineBuilderTests.Properties_GetSet_Ok', 'Polly.Core.Tests.GenericResiliencePipelineBuilderTests.Build_Ok']
App-vNext/Polly
polly-1898
ce95e7427ad17bab8add9da93014c4c606238373
diff --git a/src/Polly.Core/CircuitBreaker/BreakDurationGeneratorArguments.cs b/src/Polly.Core/CircuitBreaker/BreakDurationGeneratorArguments.cs index 6b10a0e8d9d..8883f6dd774 100644 --- a/src/Polly.Core/CircuitBreaker/BreakDurationGeneratorArguments.cs +++ b/src/Polly.Core/CircuitBreaker/BreakDurationGeneratorArguments.cs @@ -1,3 +1,5 @@ +using System.ComponentModel; + namespace Polly.CircuitBreaker; #pragma warning disable CA1815 // Override equals and operator equals on value types @@ -16,6 +18,7 @@ public readonly struct BreakDurationGeneratorArguments /// This count is used to determine if the failure threshold has been reached.</param> /// <param name="context">The resilience context providing additional information /// about the execution state and failures.</param> + [EditorBrowsable(EditorBrowsableState.Never)] public BreakDurationGeneratorArguments( double failureRate, int failureCount, @@ -24,6 +27,29 @@ public BreakDurationGeneratorArguments( FailureRate = failureRate; FailureCount = failureCount; Context = context; + HalfOpenAttempts = 0; + } + + /// <summary> + /// Initializes a new instance of the <see cref="BreakDurationGeneratorArguments"/> struct. + /// </summary> + /// <param name="failureRate">The failure rate at which the circuit breaker should trip. + /// It represents the ratio of failed actions to the total executed actions.</param> + /// <param name="failureCount">The number of failures that have occurred. + /// This count is used to determine if the failure threshold has been reached.</param> + /// <param name="context">The resilience context providing additional information + /// about the execution state and failures.</param> + /// <param name="halfOpenAttempts">The number of half-open attempts.</param> + public BreakDurationGeneratorArguments( + double failureRate, + int failureCount, + ResilienceContext context, + int halfOpenAttempts) + { + FailureRate = failureRate; + FailureCount = failureCount; + Context = context; + HalfOpenAttempts = halfOpenAttempts; } /// <summary> @@ -40,4 +66,9 @@ public BreakDurationGeneratorArguments( /// Gets the context that provides additional information about the resilience operation. /// </summary> public ResilienceContext Context { get; } + + /// <summary> + /// Gets the number of half-open attempts. + /// </summary> + public int HalfOpenAttempts { get; } } diff --git a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs index e2333370884..12902f25c85 100644 --- a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs +++ b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs @@ -22,6 +22,7 @@ internal sealed class CircuitStateController<T> : IDisposable private Outcome<T>? _lastOutcome; private Exception? _breakingException; private bool _disposed; + private int _halfOpenAttempts; #pragma warning disable S107 public CircuitStateController( @@ -132,6 +133,7 @@ public ValueTask CloseCircuitAsync(ResilienceContext context) // check if circuit can be half-opened if (_circuitState == CircuitState.Open && PermitHalfOpenCircuitTest_NeedsLock()) { + _halfOpenAttempts++; _circuitState = CircuitState.HalfOpen; _telemetry.Report(new(ResilienceEventSeverity.Warning, CircuitBreakerConstants.OnHalfOpenEvent), context, new OnCircuitHalfOpenedArguments(context)); isHalfOpen = true; @@ -270,6 +272,7 @@ private void CloseCircuit_NeedsLock(Outcome<T> outcome, bool manual, ResilienceC _blockedUntil = DateTimeOffset.MinValue; _lastOutcome = null; + _halfOpenAttempts = 0; CircuitState priorState = _circuitState; _circuitState = CircuitState.Closed; @@ -325,7 +328,7 @@ private void OpenCircuitFor_NeedsLock(Outcome<T> outcome, TimeSpan breakDuration { #pragma warning disable CA2012 #pragma warning disable S1226 - breakDuration = _breakDurationGenerator(new(_behavior.FailureRate, _behavior.FailureCount, context)).GetAwaiter().GetResult(); + breakDuration = _breakDurationGenerator(new(_behavior.FailureRate, _behavior.FailureCount, context, _halfOpenAttempts)).GetAwaiter().GetResult(); #pragma warning restore S1226 #pragma warning restore CA2012 } diff --git a/src/Polly.Core/PublicAPI.Unshipped.txt b/src/Polly.Core/PublicAPI.Unshipped.txt index 6a64f8a1f95..14a878b70e0 100644 --- a/src/Polly.Core/PublicAPI.Unshipped.txt +++ b/src/Polly.Core/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +Polly.CircuitBreaker.BreakDurationGeneratorArguments.BreakDurationGeneratorArguments(double failureRate, int failureCount, Polly.ResilienceContext! context, int halfOpenAttempts) -> void +Polly.CircuitBreaker.BreakDurationGeneratorArguments.HalfOpenAttempts.get -> int Polly.Simmy.Behavior.BehaviorActionArguments Polly.Simmy.Behavior.BehaviorActionArguments.BehaviorActionArguments() -> void Polly.Simmy.Behavior.BehaviorActionArguments.BehaviorActionArguments(Polly.ResilienceContext! context) -> void
diff --git a/test/Polly.Core.Tests/CircuitBreaker/BreakDurationGeneratorArgumentsTests.cs b/test/Polly.Core.Tests/CircuitBreaker/BreakDurationGeneratorArgumentsTests.cs index 5afa53fe6ae..7b0e5378559 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/BreakDurationGeneratorArgumentsTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/BreakDurationGeneratorArgumentsTests.cs @@ -6,7 +6,7 @@ namespace Polly.Core.Tests.CircuitBreaker; public class BreakDurationGeneratorArgumentsTests { [Fact] - public void Constructor_ShouldSetFailureRate() + public void Constructor_Old_Ok() { double expectedFailureRate = 0.5; int failureCount = 10; @@ -15,29 +15,22 @@ public void Constructor_ShouldSetFailureRate() var args = new BreakDurationGeneratorArguments(expectedFailureRate, failureCount, context); args.FailureRate.Should().Be(expectedFailureRate); + args.FailureCount.Should().Be(failureCount); + args.Context.Should().Be(context); } [Fact] - public void Constructor_ShouldSetFailureCount() + public void Constructor_Ok() { - double failureRate = 0.5; - int expectedFailureCount = 10; - var context = new ResilienceContext(); - - var args = new BreakDurationGeneratorArguments(failureRate, expectedFailureCount, context); - - args.FailureCount.Should().Be(expectedFailureCount); - } - - [Fact] - public void Constructor_ShouldSetContext() - { - double failureRate = 0.5; + double expectedFailureRate = 0.5; int failureCount = 10; - var expectedContext = new ResilienceContext(); + var context = new ResilienceContext(); - var args = new BreakDurationGeneratorArguments(failureRate, failureCount, expectedContext); + var args = new BreakDurationGeneratorArguments(expectedFailureRate, failureCount, context, 99); - args.Context.Should().Be(expectedContext); + args.FailureRate.Should().Be(expectedFailureRate); + args.FailureCount.Should().Be(failureCount); + args.Context.Should().Be(context); + args.HalfOpenAttempts.Should().Be(99); } } diff --git a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs index c7b086b0780..6ce574759e8 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs @@ -374,6 +374,41 @@ public async Task OnActionFailureAsync_EnsureBreakDurationGeneration() blockedTill.Should().Be(utcNow + TimeSpan.FromMinutes(42)); } + [Fact] + public async Task BreakDurationGenerator_EnsureHalfOpenAttempts() + { + // arrange + var halfOpenAttempts = new List<int>(); + + _options.BreakDurationGenerator = args => + { + halfOpenAttempts.Add(args.HalfOpenAttempts); + return new ValueTask<TimeSpan>(TimeSpan.Zero); + }; + + using var controller = CreateController(); + + // act + await TransitionToState(controller, CircuitState.Closed); + + for (int i = 0; i < 5; i++) + { + await TransitionToState(controller, CircuitState.Open); + await TransitionToState(controller, CircuitState.HalfOpen); + } + + await TransitionToState(controller, CircuitState.Closed); + + for (int i = 0; i < 3; i++) + { + await TransitionToState(controller, CircuitState.Open); + await TransitionToState(controller, CircuitState.HalfOpen); + } + + // assert + halfOpenAttempts.Should().BeEquivalentTo([0, 1, 2, 3, 4, 0, 1, 2]); + } + [InlineData(true)] [InlineData(false)] [Theory] @@ -502,6 +537,7 @@ private async Task TransitionToState(CircuitStateController<int> controller, Cir switch (state) { case CircuitState.Closed: + await controller.CloseCircuitAsync(ResilienceContextPool.Shared.Get()); break; case CircuitState.Open: await OpenCircuit(controller);
[Question]: Circuit Breaker: Using BreakDurationGenerator to implement exponential backoff of open to half-open state ### What are you wanting to achieve? I'd like to be able to have exponential back-off of break duration via the `BreakDurationGenerator`. For example, when the circuit goes from Closed to Open, I'd like to set a smaller break duration before it goes to Half-Open. As the circuit continues to move from Half-Open, back to Open, I'd like to keep track of the number of times this has happened, and increase the break duration up to a maximum time. ### What code or approach do you have so far? The following works, but it feels incorrect to have to maintain a state variable outside of the Builder ``` var halfOpenAttempts = 0; // <-- holding state outside. return builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<int> { ShouldHandle = args => { return args.Outcome.Exception switch { not null => PredicateResult.True(), _ => PredicateResult.False() }; }, MinimumThroughput = 2, BreakDurationGenerator = args => { var delay = Math.Pow(2, halfOpenAttempts); var fromSeconds = TimeSpan.FromSeconds(Math.Min(delay, 60)); _logger.Debug( "Generating break duration of {timeSpan} after {failureCount} failures.", fromSeconds, args.FailureCount); return new ValueTask<TimeSpan>(fromSeconds); }, OnOpened = args => { _logger.Warning("opened with break duration {breakDuration}", args.BreakDuration); return ValueTask.CompletedTask; }, OnHalfOpened = _ => { // increment each time we "probe" halfOpenAttempts++; return ValueTask.CompletedTask; }, OnClosed = _ => { // reset back to zero when circuit closes. halfOpenAttempts = 0; return ValueTask.CompletedTask; } }); ``` Would it be possible to add the "half-open" attempts to the `BreakDurationGeneratorArguments`? ### Additional context I saw that there was a similar [PR/request ](https://github.com/App-vNext/Polly/issues/653) for the very same thing for v7.x of Polly.
> Would it be possible to add the "half-open" attempts to the BreakDurationGeneratorArguments? Yes, the new design allows us to do these kind of changes quite easily. :)
2024-01-13T16:03:26Z
0.1
['Polly.Core.Tests.CircuitBreaker.BreakDurationGeneratorArgumentsTests.Constructor_Old_Ok']
[]
App-vNext/Polly
polly-1852
9e42b0ce80154fa6412d475530a0633b3c9ae7af
diff --git a/src/Polly.Core/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderExtensions.cs b/src/Polly.Core/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderExtensions.cs index 189d3c5c886..37df92bb498 100644 --- a/src/Polly.Core/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderExtensions.cs +++ b/src/Polly.Core/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderExtensions.cs @@ -85,7 +85,8 @@ internal static CircuitBreakerResilienceStrategy<TResult> CreateStrategy<TResult options.OnHalfOpened, behavior, context.TimeProvider, - context.Telemetry); + context.Telemetry, + options.BreakDurationGenerator); #pragma warning restore CA2000 // Dispose objects before losing scope return new CircuitBreakerResilienceStrategy<TResult>( diff --git a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs index 73fc1010629..a00907ed227 100644 --- a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs +++ b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs @@ -32,7 +32,7 @@ public CircuitStateController( CircuitBehavior behavior, TimeProvider timeProvider, ResilienceStrategyTelemetry telemetry, - Func<BreakDurationGeneratorArguments, ValueTask<TimeSpan>>? breakDurationGenerator = null) + Func<BreakDurationGeneratorArguments, ValueTask<TimeSpan>>? breakDurationGenerator) #pragma warning restore S107 { _breakDuration = breakDuration; diff --git a/src/Snippets/Snippets.csproj b/src/Snippets/Snippets.csproj index d6bf4d3ac66..6fad9e32e13 100644 --- a/src/Snippets/Snippets.csproj +++ b/src/Snippets/Snippets.csproj @@ -8,6 +8,7 @@ <ProjectType>Library</ProjectType> <GenerateDocumentationFile>false</GenerateDocumentationFile> <IsPackable>false</IsPackable> + <IsTestProject>false</IsTestProject> <NoWarn>$(NoWarn);SA1123;SA1515;CA2000;CA2007;CA1303;IDE0021;IDE0017;IDE0060;CS1998;CA1064;S3257;IDE0028;CA1031;CA1848</NoWarn> <NoWarn>$(NoWarn);RS0016;SA1402;SA1600;RS0037;CA1062;SA1204</NoWarn> <RootNamespace>Snippets</RootNamespace>
diff --git a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs index 51c75f9e424..5cee0687360 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs @@ -68,12 +68,66 @@ public void AddCircuitBreaker_IntegrationTest() int closed = 0; int halfOpened = 0; + var breakDuration = TimeSpan.FromSeconds(1); + + var options = new CircuitBreakerStrategyOptions + { + FailureRatio = 0.5, + MinimumThroughput = 10, + SamplingDuration = TimeSpan.FromSeconds(10), + BreakDuration = breakDuration, + ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1), + OnOpened = _ => { opened++; return default; }, + OnClosed = _ => { closed++; return default; }, + OnHalfOpened = (_) => { halfOpened++; return default; } + }; + + var timeProvider = new FakeTimeProvider(); + var strategy = new ResiliencePipelineBuilder { TimeProvider = timeProvider }.AddCircuitBreaker(options).Build(); + + for (int i = 0; i < 10; i++) + { + strategy.Execute(_ => -1); + } + + // Circuit opened + opened.Should().Be(1); + halfOpened.Should().Be(0); + closed.Should().Be(0); + Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); + + // Circuit Half Opened + timeProvider.Advance(breakDuration); + strategy.Execute(_ => -1); + Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); + opened.Should().Be(2); + halfOpened.Should().Be(1); + closed.Should().Be(0); + + // Now close it + timeProvider.Advance(breakDuration); + strategy.Execute(_ => 0); + opened.Should().Be(2); + halfOpened.Should().Be(2); + closed.Should().Be(1); + } + + [Fact] + public void AddCircuitBreaker_IntegrationTest_WithBreakDurationGenerator() + { + int opened = 0; + int closed = 0; + int halfOpened = 0; + + var breakDuration = TimeSpan.FromSeconds(1); + var options = new CircuitBreakerStrategyOptions { FailureRatio = 0.5, MinimumThroughput = 10, SamplingDuration = TimeSpan.FromSeconds(10), - BreakDuration = TimeSpan.FromSeconds(1), + BreakDuration = TimeSpan.FromSeconds(30), // Intentionally long to check it isn't used + BreakDurationGenerator = (_) => new ValueTask<TimeSpan>(breakDuration), ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result is -1), OnOpened = _ => { opened++; return default; }, OnClosed = _ => { closed++; return default; }, @@ -95,7 +149,7 @@ public void AddCircuitBreaker_IntegrationTest() Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); // Circuit Half Opened - timeProvider.Advance(options.BreakDuration); + timeProvider.Advance(breakDuration); strategy.Execute(_ => -1); Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); opened.Should().Be(2); @@ -103,7 +157,7 @@ public void AddCircuitBreaker_IntegrationTest() closed.Should().Be(0); // Now close it - timeProvider.Advance(options.BreakDuration); + timeProvider.Advance(breakDuration); strategy.Execute(_ => 0); opened.Should().Be(2); halfOpened.Should().Be(2); diff --git a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs index 03c7d7c7658..caf1eff9a0b 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs @@ -26,7 +26,8 @@ public CircuitBreakerResilienceStrategyTests() null, _behavior, _timeProvider, - _telemetry); + _telemetry, + null); } [Fact] diff --git a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs index 3a7922c1162..f69f4ca4600 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs @@ -309,26 +309,22 @@ public async Task OnActionFailureAsync_EnsureCorrectBehavior(CircuitState state, public async Task OnActionFailureAsync_EnsureBreakDurationGeneration() { // arrange - using var controller = CreateController(new() + _options.BreakDurationGenerator = static args => { - FailureRatio = 0, - MinimumThroughput = 0, - SamplingDuration = default, - BreakDuration = TimeSpan.FromMinutes(1), - BreakDurationGenerator = static args => new ValueTask<TimeSpan>(TimeSpan.FromMinutes(args.FailureCount)), - OnClosed = null, - OnOpened = null, - OnHalfOpened = null, - ManualControl = null, - StateProvider = null - }); + args.FailureCount.Should().Be(1); + args.FailureRate.Should().Be(0.5); + return new ValueTask<TimeSpan>(TimeSpan.FromMinutes(42)); + }; - await TransitionToState(controller, CircuitState.Closed); + using var controller = CreateController(); - var utcNow = DateTimeOffset.MaxValue; + await TransitionToState(controller, CircuitState.Closed); + var utcNow = new DateTimeOffset(2023, 12, 12, 12, 34, 56, TimeSpan.Zero); _timeProvider.SetUtcNow(utcNow); + _circuitBehavior.FailureCount.Returns(1); + _circuitBehavior.FailureRate.Returns(0.5); _circuitBehavior.When(v => v.OnActionFailure(CircuitState.Closed, out Arg.Any<bool>())) .Do(x => x[1] = true); @@ -337,7 +333,7 @@ public async Task OnActionFailureAsync_EnsureBreakDurationGeneration() // assert var blockedTill = GetBlockedTill(controller); - blockedTill.Should().Be(utcNow); + blockedTill.Should().Be(utcNow + TimeSpan.FromMinutes(42)); } [InlineData(true)] @@ -504,15 +500,6 @@ private async Task OpenCircuit(CircuitStateController<int> controller, Outcome<i _options.OnHalfOpened, _circuitBehavior, _timeProvider, - TestUtilities.CreateResilienceTelemetry(_telemetryListener)); - - private CircuitStateController<int> CreateController(CircuitBreakerStrategyOptions<int> options) => new( - options.BreakDuration, - options.OnOpened, - options.OnClosed, - options.OnHalfOpened, - _circuitBehavior, - _timeProvider, TestUtilities.CreateResilienceTelemetry(_telemetryListener), - options.BreakDurationGenerator); + _options.BreakDurationGenerator); }
BreakDurationGenerator not passed to CircuitStateController There is an issue with this. When you call AddCircuitBreaker(options), having specified BreakDurationGenerator. It does not pass the generate to the CircuitStateController. So the resulting circuitbreaker will use the default 5 seconds fixed duration. _Originally posted by @adminnz in https://github.com/App-vNext/Polly/issues/1776#issuecomment-1846438825_
Not sure what more to add, the BreakDurationGenerator does not get passed to the controller. So if you do: ``` ResiliencePipeline = new ResiliencePipelineBuilder() .AddCircuitBreaker(new CircuitBreakerStrategyOptions { BreakDurationGenerator = args => ValueTask.FromResult(TimeSpan.FromMinutes(args.FailureCount)), MinimumThroughput = Settings.CircuitBreakerMinimumThroughput, FailureRatio = Settings.CircuitBreakerFailureRatio, SamplingDuration = Settings.CircuitBreakerSamplingDuration, StateProvider = CircuitBreakerStateProvider, OnClosed = OnCircuitClosed, OnOpened = OnCircuitOpened, OnHalfOpened = OnHalfOpened }) .Build(); ``` The resulting ResiliencePipline circuit breaker will not use the BreakDurationGenerator. Instead it will use the default 5 second BreakDuration. Thanks - it was a concrete code snippet I was after so that we can use it to build up a unit test.
2023-12-12T12:19:51Z
0.1
['Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreaker_IntegrationTest_WithBreakDurationGenerator']
['Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreakers_WithIsolatedManualControl_ShouldBeIsolated', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreaker_IntegrationTest', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreaker_Validation', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreaker_Configure', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.AddCircuitBreaker_Generic_Configure', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResiliencePipelineBuilderTests.DisposePipeline_EnsureCircuitBreakerDisposed']
App-vNext/Polly
polly-1620
7144f68ab418a9a2e76b2dfda12956dc8cdf7923
diff --git a/src/Polly.Core/PublicAPI.Unshipped.txt b/src/Polly.Core/PublicAPI.Unshipped.txt index 74c19f8c4ed..96906d8113d 100644 --- a/src/Polly.Core/PublicAPI.Unshipped.txt +++ b/src/Polly.Core/PublicAPI.Unshipped.txt @@ -309,6 +309,8 @@ Polly.Retry.RetryStrategyOptions<TResult>.Delay.get -> System.TimeSpan Polly.Retry.RetryStrategyOptions<TResult>.Delay.set -> void Polly.Retry.RetryStrategyOptions<TResult>.DelayGenerator.get -> System.Func<Polly.Retry.RetryDelayGeneratorArguments<TResult>, System.Threading.Tasks.ValueTask<System.TimeSpan?>>? Polly.Retry.RetryStrategyOptions<TResult>.DelayGenerator.set -> void +Polly.Retry.RetryStrategyOptions<TResult>.MaxDelay.get -> System.TimeSpan? +Polly.Retry.RetryStrategyOptions<TResult>.MaxDelay.set -> void Polly.Retry.RetryStrategyOptions<TResult>.MaxRetryAttempts.get -> int Polly.Retry.RetryStrategyOptions<TResult>.MaxRetryAttempts.set -> void Polly.Retry.RetryStrategyOptions<TResult>.OnRetry.get -> System.Func<Polly.Retry.OnRetryArguments<TResult>, System.Threading.Tasks.ValueTask>? diff --git a/src/Polly.Core/Retry/RetryHelper.cs b/src/Polly.Core/Retry/RetryHelper.cs index c2afdcf13bd..333a85d9b88 100644 --- a/src/Polly.Core/Retry/RetryHelper.cs +++ b/src/Polly.Core/Retry/RetryHelper.cs @@ -8,11 +8,26 @@ internal static class RetryHelper public static bool IsValidDelay(TimeSpan delay) => delay >= TimeSpan.Zero; - public static TimeSpan GetRetryDelay(DelayBackoffType type, bool jitter, int attempt, TimeSpan baseDelay, ref double state, Func<double> randomizer) + public static TimeSpan GetRetryDelay( + DelayBackoffType type, + bool jitter, + int attempt, + TimeSpan baseDelay, + TimeSpan? maxDelay, + ref double state, + Func<double> randomizer) { try { - return GetRetryDelayCore(type, jitter, attempt, baseDelay, ref state, randomizer); + var delay = GetRetryDelayCore(type, jitter, attempt, baseDelay, ref state, randomizer); + + // stryker disable once equality : no means to test this + if (maxDelay is TimeSpan maxDelayValue && delay > maxDelayValue) + { + return maxDelay.Value; + } + + return delay; } catch (OverflowException) { @@ -89,7 +104,7 @@ private static TimeSpan DecorrelatedJitterBackoffV2(int attempt, TimeSpan baseDe long targetTicksFirstDelay = baseDelay.Ticks; double t = attempt + randomizer(); - double next = Math.Pow(2, t) * Math.Tanh(Math.Sqrt(PFactor * t)); + double next = Math.Pow(ExponentialFactor, t) * Math.Tanh(Math.Sqrt(PFactor * t)); double formulaIntrinsicValue = next - prev; prev = next; @@ -98,5 +113,11 @@ private static TimeSpan DecorrelatedJitterBackoffV2(int attempt, TimeSpan baseDe } private static TimeSpan ApplyJitter(TimeSpan delay, Func<double> randomizer) - => TimeSpan.FromMilliseconds(delay.TotalMilliseconds + ((delay.TotalMilliseconds * JitterFactor) * randomizer())); + { + var offset = (delay.TotalMilliseconds * JitterFactor) / 2; + var randomDelay = (delay.TotalMilliseconds * JitterFactor * randomizer()) - offset; + var newDelay = delay.TotalMilliseconds + randomDelay; + + return TimeSpan.FromMilliseconds(newDelay); + } } diff --git a/src/Polly.Core/Retry/RetryResilienceStrategy.cs b/src/Polly.Core/Retry/RetryResilienceStrategy.cs index 9eb5f1068c0..0b9dfbacde1 100644 --- a/src/Polly.Core/Retry/RetryResilienceStrategy.cs +++ b/src/Polly.Core/Retry/RetryResilienceStrategy.cs @@ -15,6 +15,7 @@ public RetryResilienceStrategy( { ShouldHandle = options.ShouldHandle; BaseDelay = options.Delay; + MaxDelay = options.MaxDelay; BackoffType = options.BackoffType; RetryCount = options.MaxRetryAttempts; OnRetry = options.OnRetry; @@ -28,6 +29,8 @@ public RetryResilienceStrategy( public TimeSpan BaseDelay { get; } + public TimeSpan? MaxDelay { get; } + public DelayBackoffType BackoffType { get; } public int RetryCount { get; } @@ -61,7 +64,7 @@ protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func return outcome; } - var delay = RetryHelper.GetRetryDelay(BackoffType, UseJitter, attempt, BaseDelay, ref retryState, _randomizer); + var delay = RetryHelper.GetRetryDelay(BackoffType, UseJitter, attempt, BaseDelay, MaxDelay, ref retryState, _randomizer); if (DelayGenerator is not null) { var delayArgs = new RetryDelayGeneratorArguments<T>(context, outcome, attempt); diff --git a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs index fa568480694..70375d07f6c 100644 --- a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs +++ b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs @@ -3,6 +3,8 @@ namespace Polly.Retry; +#pragma warning disable IL2026 // Addressed with DynamicDependency on ValidationHelper.Validate method + /// <summary> /// Represents the options used to configure a retry strategy. /// </summary> @@ -49,7 +51,6 @@ public class RetryStrategyOptions<TResult> : ResilienceStrategyOptions /// </value> public bool UseJitter { get; set; } -#pragma warning disable IL2026 // Addressed with DynamicDependency on ValidationHelper.Validate method /// <summary> /// Gets or sets the base delay between retries. /// </summary> @@ -73,7 +74,20 @@ public class RetryStrategyOptions<TResult> : ResilienceStrategyOptions /// </value> [Range(typeof(TimeSpan), "00:00:00", "1.00:00:00")] public TimeSpan Delay { get; set; } = RetryConstants.DefaultBaseDelay; -#pragma warning restore IL2026 + + /// <summary> + /// Gets or sets the maximum delay between retries. + /// </summary> + /// <remarks> + /// This property is used to cap maximum delay between retries. It is useful when you want to limit the maximum delay after certain + /// number of between retries when it could reach a unreasonably high values, especially if <see cref="DelayBackoffType.Exponential"/> backoff is used. + /// If not specified, the delay is not capped. This property is ignored for delays generated by <see cref="DelayGenerator"/>. + /// </remarks> + /// <value> + /// The default value is <see langword="null"/>. + /// </value> + [Range(typeof(TimeSpan), "00:00:00", "1.00:00:00")] + public TimeSpan? MaxDelay { get; set; } /// <summary> /// Gets or sets a predicate that determines whether the retry should be executed for a given outcome.
diff --git a/test/Polly.Core.Tests/Retry/RetryHelperTests.cs b/test/Polly.Core.Tests/Retry/RetryHelperTests.cs index f5d78eac08e..0deb85d2f7c 100644 --- a/test/Polly.Core.Tests/Retry/RetryHelperTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryHelperTests.cs @@ -28,57 +28,108 @@ public void UnsupportedRetryBackoffType_Throws(bool jitter) Assert.Throws<ArgumentOutOfRangeException>(() => { double state = 0; - return RetryHelper.GetRetryDelay(type, jitter, 0, TimeSpan.FromSeconds(1), ref state, _randomizer); + return RetryHelper.GetRetryDelay(type, jitter, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer); }); } - [InlineData(true)] - [InlineData(false)] - [Theory] - public void Constant_Ok(bool jitter) + [Fact] + public void Constant_Ok() { double state = 0; - if (jitter) - { - _randomizer = () => 0.5; - } - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 0, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 1, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 2, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 0, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 1, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); + } - var expected = !jitter ? TimeSpan.FromSeconds(1) : TimeSpan.FromSeconds(1.25); + [Fact] + public void Constant_Jitter_Ok() + { + double state = 0; - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 0, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(expected); - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 1, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(expected); - RetryHelper.GetRetryDelay(DelayBackoffType.Constant, jitter, 2, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(expected); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 1, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 2, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + + _randomizer = () => 0.0; + RetryHelper + .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(0.75)); + + _randomizer = () => 0.4; + RetryHelper + .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(0.95)); + + _randomizer = () => 0.6; + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, true, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(1.05)); + + _randomizer = () => 1.0; + RetryHelper + .GetRetryDelay(DelayBackoffType.Constant, true, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(1.25)); } - [InlineData(true)] - [InlineData(false)] - [Theory] - public void Linear_Ok(bool jitter) + [Fact] + public void Linear_Ok() { double state = 0; - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 0, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 1, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 2, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 0, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 1, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 2, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); - if (jitter) - { - _randomizer = () => 0.5; + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(2)); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(3)); + } - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 0, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1.25)); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 1, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(2.5)); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 2, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(3.75)); - } - else - { - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 0, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 1, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(2)); - RetryHelper.GetRetryDelay(DelayBackoffType.Linear, jitter, 2, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(3)); - } + [Fact] + public void Linear_Jitter_Ok() + { + double state = 0; + + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 0, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 1, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + + _randomizer = () => 0.0; + RetryHelper + .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(2.25)); + + _randomizer = () => 0.4; + RetryHelper + .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(2.85)); + + _randomizer = () => 0.5; + RetryHelper + .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(3)); + + _randomizer = () => 0.6; + RetryHelper.GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(3.15)); + + _randomizer = () => 1.0; + RetryHelper + .GetRetryDelay(DelayBackoffType.Linear, true, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer) + .Should() + .Be(TimeSpan.FromSeconds(3.75)); } [Fact] @@ -86,13 +137,38 @@ public void Exponential_Ok() { double state = 0; - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.Zero, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.Zero, null, ref state, _randomizer).Should().Be(TimeSpan.Zero); + + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(2)); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.FromSeconds(1), null, ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(4)); + } + + [InlineData(DelayBackoffType.Linear, false)] + [InlineData(DelayBackoffType.Exponential, false)] + [InlineData(DelayBackoffType.Constant, false)] + [InlineData(DelayBackoffType.Linear, true)] + [InlineData(DelayBackoffType.Exponential, true)] + [InlineData(DelayBackoffType.Constant, true)] + [Theory] + public void MaxDelay_Ok(DelayBackoffType type, bool jitter) + { + _randomizer = () => 0.5; + var expected = TimeSpan.FromSeconds(1); + double state = 0; + + RetryHelper.GetRetryDelay(type, jitter, 2, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(expected); + } + + [Fact] + public void MaxDelay_DelayLessThanMaxDelay_Respected() + { + double state = 0; + var expected = TimeSpan.FromSeconds(1); - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 0, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(1)); - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(2)); - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 2, TimeSpan.FromSeconds(1), ref state, _randomizer).Should().Be(TimeSpan.FromSeconds(4)); + RetryHelper.GetRetryDelay(DelayBackoffType.Constant, false, 2, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), ref state, _randomizer).Should().Be(expected); } [Fact] @@ -100,7 +176,7 @@ public void GetRetryDelay_Overflow_ReturnsMaxTimeSpan() { double state = 0; - RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1000, TimeSpan.FromDays(1), ref state, _randomizer).Should().Be(TimeSpan.MaxValue); + RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, false, 1000, TimeSpan.FromDays(1), null, ref state, _randomizer).Should().Be(TimeSpan.MaxValue); } [InlineData(1)] @@ -144,7 +220,7 @@ private static IReadOnlyList<TimeSpan> GetExponentialWithJitterBackoff(bool cont for (int i = 0; i < retryCount; i++) { - result.Add(RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, true, i, baseDelay, ref state, random)); + result.Add(RetryHelper.GetRetryDelay(DelayBackoffType.Exponential, true, i, baseDelay, null, ref state, random)); } return result; diff --git a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs index c41a69ca185..d0727bda922 100644 --- a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs @@ -243,6 +243,30 @@ public async void OnRetry_EnsureCorrectArguments() delays[2].Should().Be(TimeSpan.FromSeconds(6)); } + [Fact] + public async void MaxDelay_EnsureRespected() + { + var delays = new List<TimeSpan>(); + _options.OnRetry = args => + { + delays.Add(args.RetryDelay); + return default; + }; + + _options.ShouldHandle = args => PredicateResult.True(); + _options.MaxRetryAttempts = 3; + _options.BackoffType = DelayBackoffType.Linear; + _options.MaxDelay = TimeSpan.FromMilliseconds(123); + + var sut = CreateSut(); + + await ExecuteAndAdvance(sut); + + delays[0].Should().Be(TimeSpan.FromMilliseconds(123)); + delays[1].Should().Be(TimeSpan.FromMilliseconds(123)); + delays[2].Should().Be(TimeSpan.FromMilliseconds(123)); + } + [Fact] public async Task OnRetry_EnsureExecutionTime() { diff --git a/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs b/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs index c787301799f..f0d3b8f1c7c 100644 --- a/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs @@ -44,7 +44,8 @@ public void InvalidOptions() DelayGenerator = null!, OnRetry = null!, MaxRetryAttempts = -3, - Delay = TimeSpan.MinValue + Delay = TimeSpan.MinValue, + MaxDelay = TimeSpan.FromSeconds(-10) }; options.Invoking(o => ValidationHelper.ValidateObject(new(o, "Invalid Options"))) @@ -56,6 +57,7 @@ Invalid Options Validation Errors: The field MaxRetryAttempts must be between 1 and 2147483647. The field Delay must be between 00:00:00 and 1.00:00:00. + The field MaxDelay must be between 00:00:00 and 1.00:00:00. The ShouldHandle field is required. """); }
Limiting max retry delay when using standard backoff types With current API it's not possible to limit max retry delay while using built-in backoff types. We have a scenario where we infinitely retry failing background operations until recovery. Once the failures start, we want to backoff exponentially using the built-in generators, but eventually limit the calculated delay to some maximum value. Consider adding `TimeSpan MaxRetryDelay?` property to the retry options that will cap the generated delay value. It might be applicable both for built-in and externally provided delay generators. cc @martintmk
I think this is a valid scenario. The changes should be relatively small so we can still squeeze this into v8. Minor comments only: - `MaxRetryDelay` should be `MaxDelay` - because we have the `Delay` property - Maybe not apply the cap on external generators? (as the generation is fully under their control) cc @martincostello
2023-09-22T08:25:48Z
0.2
['Polly.Core.Tests.Retry.RetryHelperTests.MaxDelay_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.Linear_Jitter_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.MaxDelay_DelayLessThanMaxDelay_Respected', 'Polly.Core.Tests.Retry.RetryHelperTests.Constant_Jitter_Ok']
['Polly.Core.Tests.Retry.RetryHelperTests.Exponential_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.ExponentialWithJitter_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.IsValidDelay_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.Linear_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.Constant_Ok', 'Polly.Core.Tests.Retry.RetryHelperTests.ExponentialWithJitter_EnsureRandomness', 'Polly.Core.Tests.Retry.RetryHelperTests.GetRetryDelay_Overflow_ReturnsMaxTimeSpan', 'Polly.Core.Tests.Retry.RetryHelperTests.UnsupportedRetryBackoffType_Throws']
App-vNext/Polly
polly-1579
6999e7c9ab0df7afe45a448d57e519f66b470d87
diff --git a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs index e29c89560da..4493631f8cd 100644 --- a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs +++ b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs @@ -57,14 +57,17 @@ private Builder CreateBuilder() builder.InstanceName = _instanceName; _configure(builder, context); + var timeProvider = builder.TimeProvider; var telemetry = new ResilienceStrategyTelemetry( new ResilienceTelemetrySource(builder.Name, builder.InstanceName, null), builder.TelemetryListener); return new( - () => PipelineComponentFactory.WithDisposableCallbacks( - builder.BuildPipelineComponent(), - context.DisposeCallbacks), + () => + { + var innerComponent = PipelineComponentFactory.WithDisposableCallbacks(builder.BuildPipelineComponent(), context.DisposeCallbacks); + return PipelineComponentFactory.WithExecutionTracking(innerComponent, timeProvider); + }, context.ReloadTokens, telemetry); } diff --git a/src/Polly.Core/Utils/Pipeline/ExecutionTrackingComponent.cs b/src/Polly.Core/Utils/Pipeline/ExecutionTrackingComponent.cs new file mode 100644 index 00000000000..5a03e7f94fc --- /dev/null +++ b/src/Polly.Core/Utils/Pipeline/ExecutionTrackingComponent.cs @@ -0,0 +1,59 @@ +namespace Polly.Utils.Pipeline; + +internal sealed class ExecutionTrackingComponent : PipelineComponent +{ + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + + public static readonly TimeSpan SleepDelay = TimeSpan.FromSeconds(1); + + private readonly TimeProvider _timeProvider; + private int _pendingExecutions; + + public ExecutionTrackingComponent(PipelineComponent component, TimeProvider timeProvider) + { + Component = component; + _timeProvider = timeProvider; + } + + public PipelineComponent Component { get; } + + public bool HasPendingExecutions => Interlocked.CompareExchange(ref _pendingExecutions, 0, 0) > 0; + + internal override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>( + Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, + ResilienceContext context, + TState state) + { + Interlocked.Increment(ref _pendingExecutions); + + try + { + return await Component.ExecuteCore(callback, context, state).ConfigureAwait(context.ContinueOnCapturedContext); + } + finally + { + Interlocked.Decrement(ref _pendingExecutions); + } + } + + public override async ValueTask DisposeAsync() + { + var start = _timeProvider.GetTimestamp(); + var stopwatch = Stopwatch.StartNew(); + + // We don't want to introduce locks or any synchronization primitives to main execution path + // so we will do "dummy" retries until there are no more executions. + while (HasPendingExecutions) + { + await _timeProvider.Delay(SleepDelay).ConfigureAwait(false); + + // stryker disable once equality : no means to test this + if (_timeProvider.GetElapsedTime(start) > Timeout) + { + break; + } + } + + await Component.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs b/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs index 125f742a103..5c992295fc8 100644 --- a/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs +++ b/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs @@ -24,6 +24,8 @@ public static PipelineComponent WithDisposableCallbacks(PipelineComponent compon return new ComponentWithDisposeCallbacks(component, callbacks.ToList()); } + public static PipelineComponent WithExecutionTracking(PipelineComponent component, TimeProvider timeProvider) => new ExecutionTrackingComponent(component, timeProvider); + public static PipelineComponent CreateComposite( IReadOnlyList<PipelineComponent> components, ResilienceStrategyTelemetry telemetry, diff --git a/src/Polly.Testing/ResiliencePipelineExtensions.cs b/src/Polly.Testing/ResiliencePipelineExtensions.cs index 19692182d30..feea4ad59d3 100644 --- a/src/Polly.Testing/ResiliencePipelineExtensions.cs +++ b/src/Polly.Testing/ResiliencePipelineExtensions.cs @@ -40,10 +40,10 @@ private static ResiliencePipelineDescriptor GetPipelineDescriptorCore<T>(Pipelin var components = new List<PipelineComponent>(); component.ExpandComponents(components); - var descriptors = components.Select(s => new ResilienceStrategyDescriptor(s.Options, GetStrategyInstance<T>(s))).ToList(); + var descriptors = components.OfType<BridgeComponentBase>().Select(s => new ResilienceStrategyDescriptor(s.Options, GetStrategyInstance<T>(s))).ToList().AsReadOnly(); return new ResiliencePipelineDescriptor( - descriptors.Where(s => !ShouldSkip(s.StrategyInstance)).ToList().AsReadOnly(), + descriptors, isReloadable: components.Exists(s => s is ReloadableComponent)); } @@ -54,16 +54,9 @@ private static object GetStrategyInstance<T>(PipelineComponent component) return reactiveBridge.Strategy; } - if (component is BridgeComponent nonReactiveBridge) - { - return nonReactiveBridge.Strategy; - } - - return component; + return ((BridgeComponent)component).Strategy; } - private static bool ShouldSkip(object instance) => instance is ReloadableComponent || instance is ComponentWithDisposeCallbacks; - private static void ExpandComponents(this PipelineComponent component, List<PipelineComponent> components) { if (component is CompositeComponent pipeline) @@ -78,6 +71,11 @@ private static void ExpandComponents(this PipelineComponent component, List<Pipe components.Add(reloadable); ExpandComponents(reloadable.Component, components); } + else if (component is ExecutionTrackingComponent tracking) + { + components.Add(tracking); + ExpandComponents(tracking.Component, components); + } else if (component is ComponentWithDisposeCallbacks callbacks) { ExpandComponents(callbacks.Component, components);
diff --git a/test/Polly.Core.Tests/CircuitBreaker/Controller/ScheduledTaskExecutorTests.cs b/test/Polly.Core.Tests/CircuitBreaker/Controller/ScheduledTaskExecutorTests.cs index 4b85dd4fc99..f24b8791324 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/Controller/ScheduledTaskExecutorTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/Controller/ScheduledTaskExecutorTests.cs @@ -123,11 +123,11 @@ public void Dispose_WhenScheduledTaskExecuting() ResilienceContextPool.Shared.Get(), out var task); - ready.WaitOne(TimeSpan.FromSeconds(2)).Should().BeTrue(); + ready.WaitOne(TimeSpan.FromSeconds(10)).Should().BeTrue(); scheduler.Dispose(); disposed.Set(); - scheduler.ProcessingTask.Wait(TimeSpan.FromSeconds(2)).Should().BeTrue(); + scheduler.ProcessingTask.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue(); } [Fact] diff --git a/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs b/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs index 547f1111cb7..23f1d5032dc 100644 --- a/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs +++ b/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs @@ -4,6 +4,7 @@ using Polly.Testing; using Polly.Timeout; using Polly.Utils; +using Polly.Utils.Pipeline; namespace Polly.Core.Tests.Registry; @@ -380,6 +381,20 @@ public void GetOrAddPipeline_Ok() called.Should().Be(1); } + [Fact] + public void GetOrAddPipeline_EnsureCorrectComponents() + { + var id = new StrategyId(typeof(string), "A"); + + using var registry = CreateRegistry(); + + var pipeline = registry.GetOrAddPipeline(id, builder => builder.AddTimeout(TimeSpan.FromSeconds(1))); + pipeline.Component.Should().BeOfType<ExecutionTrackingComponent>().Subject.Component.Should().BeOfType<CompositeComponent>(); + + var genericPipeline = registry.GetOrAddPipeline<string>(id, builder => builder.AddTimeout(TimeSpan.FromSeconds(1))); + pipeline.Component.Should().BeOfType<ExecutionTrackingComponent>().Subject.Component.Should().BeOfType<CompositeComponent>(); + } + [Fact] public void GetOrAddPipeline_Generic_Ok() { diff --git a/test/Polly.Core.Tests/Utils/Pipeline/ExecutionTrackingComponentTests.cs b/test/Polly.Core.Tests/Utils/Pipeline/ExecutionTrackingComponentTests.cs new file mode 100644 index 00000000000..2cebbffc5e3 --- /dev/null +++ b/test/Polly.Core.Tests/Utils/Pipeline/ExecutionTrackingComponentTests.cs @@ -0,0 +1,168 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Time.Testing; +using Polly.Utils.Pipeline; + +namespace Polly.Core.Tests.Utils.Pipeline; + +public class ExecutionTrackingComponentTests +{ + private readonly FakeTimeProvider _timeProvider = new(); + + [Fact] + public async Task DisposeAsync_PendingOperations_Delayed() + { + using var assert = new ManualResetEvent(false); + using var executing = new ManualResetEvent(false); + + await using var inner = new Inner + { + OnExecute = () => + { + executing.Set(); + assert.WaitOne(); + } + }; + + var component = new ExecutionTrackingComponent(inner, _timeProvider); + var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow).Execute(() => { })); + executing.WaitOne(); + + var disposeTask = component.DisposeAsync().AsTask(); + _timeProvider.Advance(ExecutionTrackingComponent.SleepDelay); + inner.Disposed.Should().BeFalse(); + assert.Set(); + + _timeProvider.Advance(ExecutionTrackingComponent.SleepDelay); + await execution; + + _timeProvider.Advance(ExecutionTrackingComponent.SleepDelay); + await disposeTask; + + inner.Disposed.Should().BeTrue(); + } + + [Fact] + public async Task HasPendingExecutions_Ok() + { + using var assert = new ManualResetEvent(false); + using var executing = new ManualResetEvent(false); + + await using var inner = new Inner + { + OnExecute = () => + { + executing.Set(); + assert.WaitOne(); + } + }; + + await using var component = new ExecutionTrackingComponent(inner, _timeProvider); + var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow).Execute(() => { })); + executing.WaitOne(); + + component.HasPendingExecutions.Should().BeTrue(); + assert.Set(); + await execution; + + component.HasPendingExecutions.Should().BeFalse(); + } + + [Fact] + public async Task DisposeAsync_Timeout_Ok() + { + using var assert = new ManualResetEvent(false); + using var executing = new ManualResetEvent(false); + + await using var inner = new Inner + { + OnExecute = () => + { + executing.Set(); + assert.WaitOne(); + } + }; + + var component = new ExecutionTrackingComponent(inner, _timeProvider); + var execution = Task.Run(() => new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow).Execute(() => { })); + executing.WaitOne(); + + var disposeTask = component.DisposeAsync().AsTask(); + inner.Disposed.Should().BeFalse(); + _timeProvider.Advance(ExecutionTrackingComponent.Timeout - TimeSpan.FromSeconds(1)); + inner.Disposed.Should().BeFalse(); + _timeProvider.Advance(TimeSpan.FromSeconds(1)); + _timeProvider.Advance(TimeSpan.FromSeconds(1)); + await disposeTask; + inner.Disposed.Should().BeTrue(); + + assert.Set(); + await execution; + } + + [Fact] + public async Task DisposeAsync_WhenRunningMultipleTasks_Ok() + { + var tasks = new ConcurrentQueue<ManualResetEvent>(); + await using var inner = new Inner + { + OnExecute = () => + { + var ev = new ManualResetEvent(false); + tasks.Enqueue(ev); + ev.WaitOne(); + } + }; + + var component = new ExecutionTrackingComponent(inner, TimeProvider.System); + var pipeline = new ResiliencePipeline(component, Polly.Utils.DisposeBehavior.Allow); + + for (int i = 0; i < 10; i++) + { + _ = Task.Run(() => pipeline.Execute(() => { })); + } + + while (tasks.Count != 10) + { + await Task.Delay(1); + } + + var disposeTask = component.DisposeAsync().AsTask(); + + while (tasks.Count > 1) + { + tasks.TryDequeue(out var ev).Should().BeTrue(); + ev!.Set(); + ev.Dispose(); + disposeTask.Wait(1).Should().BeFalse(); + inner.Disposed.Should().BeFalse(); + } + + // last one + tasks.TryDequeue(out var last).Should().BeTrue(); + last!.Set(); + last.Dispose(); + await disposeTask; + inner.Disposed.Should().BeTrue(); + } + + private class Inner : PipelineComponent + { + public bool Disposed { get; private set; } + + public override ValueTask DisposeAsync() + { + Disposed = true; + return default; + } + + public Action OnExecute { get; set; } = () => { }; + + internal override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state) + { + OnExecute(); + + return await callback(context, state); + } + } +}
ObjectDisposedException thrown if a request is inflight when configuration is reloaded Testing out Polly `8.0.0-beta.1` in an internal production application, we have observed the following exception thrown when using a resilience strategy occur if the application's configuration is reloaded while the policy is in use. ``` System.ObjectDisposedException: Cannot access a disposed object. Object name: 'CircuitStateController'. at Polly.CircuitBreaker.CircuitStateController`1.EnsureNotDisposed() at Polly.CircuitBreaker.CircuitStateController`1.OnActionSuccessAsync(Outcome`1 outcome, ResilienceContext context) at Polly.CircuitBreaker.CircuitBreakerResilienceStrategy`1.ExecuteCore[TState](Func`3 callback, ResilienceContext context, TState state) at Polly.Utils.Pipeline.BridgeComponent`1.<ConvertValueTask>g__ConvertValueTaskAsync|5_0[TTo](ValueTask`1 valueTask, ResilienceContext resilienceContext) at Polly.Utils.Pipeline.CompositeComponent.ExecuteCoreWithTelemetry[TResult,TState](Func`3 callback, ResilienceContext context, TState state) at Polly.Utils.StrategyHelper.<ExecuteCallbackSafeAsync>g__AwaitTask|0_0[TResult,TState,T](ValueTask`1 task, Boolean continueOnCapturedContext) at Polly.Outcome`1.GetResultOrRethrow() at Polly.ResiliencePipeline.ExecuteAsync[TResult](Func`2 callback, ResilienceContext context) at MyApplication.Providers.ApiClient.ExecuteAsync[TResult](String rateLimitToken, String operationKey, ClientExecuteOptions`1 clientExecuteOptions, Func`3 action, CancellationToken cancellationToken) in /_/src/MyApplication/Providers/ApiClient.cs:line 186 at MyApplication.Providers.ApiClient.ExecuteAsync[T](String rateLimitToken, String operationKey, Func`2 func, ClientExecuteOptions`1 clientExecuteOptions, CancellationToken cancellationToken) in /_/src/MyApplication/Providers/ApiClient.cs:line 125 at MyApplication.Providers.InflightClient.GetByOrderIdAsync(String tenant, String orderId, CancellationToken cancellationToken, Boolean handleExecutionFaults) in /_/src/MyApplication/Providers/InflightClient.cs:line 74 at MyApplication.Services.StatusService.GetOrderStatusAsync(String tenant, String id, CancellationToken cancellationToken) in /_/src/MyApplication/Services/StatusService.cs:line 109 at MyApplication.Controllers.StatusController.GetStatusAsync(String tenant, String id, CancellationToken cancellationToken) in /_/src/MyApplication/Controllers/StatusController.cs:line 143 at MyApplication.Controllers.StatusController.GetStatusByOrderIdAuthorized(String tenant, String id, CancellationToken cancellationToken) in /_/src/MyApplication/Controllers/StatusController.cs:line 96 at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|26_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) ``` I can't share the application code, but the overall structure is very similar to https://github.com/martincostello/polly-sandbox/pull/1. Over a pool of 6 EC2 instances handling ~8,500 requests per minute between them at the time, we had 2 occurrences, so imagine there's an element of chance to whether or not it happens when the application is under load when the configuration is reloaded.
Just found a second cluster of 3 of the same exception in another environment with a similar load and number of instances in service. I was worried this might happen. The solution is to keep track of active executions in circuit breaker and delay the disposal until the pipeline serves no more executions.
2023-09-08T12:41:06Z
0.2
['Polly.Core.Tests.Utils.Pipeline.ExecutionTrackingComponentTests.DisposeAsync_Timeout_Ok', 'Polly.Core.Tests.Utils.Pipeline.ExecutionTrackingComponentTests.HasPendingExecutions_Ok', 'Polly.Core.Tests.Utils.Pipeline.ExecutionTrackingComponentTests.DisposeAsync_PendingOperations_Delayed', 'Polly.Core.Tests.Utils.Pipeline.ExecutionTrackingComponentTests.DisposeAsync_WhenRunningMultipleTasks_Ok']
['Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.Dispose_WhenScheduledTaskExecuting', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.ScheduleTask_OperationCanceledException_EnsureExecuted', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.ScheduleTask_Success_EnsureExecuted', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.Dispose_ScheduledTaskCancelled', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.Dispose_EnsureNoBackgroundProcessing', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.ScheduleTask_Exception_EnsureExecuted', 'Polly.Core.Tests.CircuitBreaker.Controller.ScheduledTaskExecutorTests.ScheduleTask_Multiple_EnsureExecutionSerialized']
App-vNext/Polly
polly-1555
3f1b4355bb76724e26644df09dd11729162756cd
diff --git a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs index a40552b7b8c..e29c89560da 100644 --- a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs +++ b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs @@ -33,10 +33,6 @@ public RegistryPipelineComponentBuilder( internal PipelineComponent CreateComponent() { var builder = CreateBuilder(); - var telemetry = new ResilienceStrategyTelemetry( - new ResilienceTelemetrySource(_builderName, _instanceName, null), - builder.Listener); - var component = builder.ComponentFactory(); if (builder.ReloadTokens.Count == 0) @@ -45,13 +41,12 @@ internal PipelineComponent CreateComponent() } return PipelineComponentFactory.CreateReloadable( - new ReloadableComponent.Entry(component, builder.ReloadTokens), + new ReloadableComponent.Entry(component, builder.ReloadTokens, builder.Telemetry), () => { var builder = CreateBuilder(); - return new ReloadableComponent.Entry(builder.ComponentFactory(), builder.ReloadTokens); - }, - telemetry); + return new ReloadableComponent.Entry(builder.ComponentFactory(), builder.ReloadTokens, builder.Telemetry); + }); } private Builder CreateBuilder() @@ -62,13 +57,20 @@ private Builder CreateBuilder() builder.InstanceName = _instanceName; _configure(builder, context); + var telemetry = new ResilienceStrategyTelemetry( + new ResilienceTelemetrySource(builder.Name, builder.InstanceName, null), + builder.TelemetryListener); + return new( () => PipelineComponentFactory.WithDisposableCallbacks( builder.BuildPipelineComponent(), context.DisposeCallbacks), context.ReloadTokens, - builder.TelemetryListener); + telemetry); } - private record Builder(Func<PipelineComponent> ComponentFactory, List<CancellationToken> ReloadTokens, TelemetryListener? Listener); + private record Builder( + Func<PipelineComponent> ComponentFactory, + List<CancellationToken> ReloadTokens, + ResilienceStrategyTelemetry Telemetry); } diff --git a/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs b/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs index 121b88586a0..125f742a103 100644 --- a/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs +++ b/src/Polly.Core/Utils/Pipeline/PipelineComponentFactory.cs @@ -31,6 +31,5 @@ public static PipelineComponent CreateComposite( public static PipelineComponent CreateReloadable( ReloadableComponent.Entry initial, - Func<ReloadableComponent.Entry> factory, - ResilienceStrategyTelemetry telemetry) => new ReloadableComponent(initial, factory, telemetry); + Func<ReloadableComponent.Entry> factory) => new ReloadableComponent(initial, factory); } diff --git a/src/Polly.Core/Utils/Pipeline/ReloadableComponent.cs b/src/Polly.Core/Utils/Pipeline/ReloadableComponent.cs index ca88256e9e7..4e5be1554a2 100644 --- a/src/Polly.Core/Utils/Pipeline/ReloadableComponent.cs +++ b/src/Polly.Core/Utils/Pipeline/ReloadableComponent.cs @@ -13,18 +13,18 @@ internal sealed class ReloadableComponent : PipelineComponent public const string OnReloadEvent = "OnReload"; private readonly Func<Entry> _factory; - private readonly ResilienceStrategyTelemetry _telemetry; + private ResilienceStrategyTelemetry _telemetry; private CancellationTokenSource _tokenSource = null!; private CancellationTokenRegistration _registration; private List<CancellationToken> _reloadTokens; - public ReloadableComponent(Entry entry, Func<Entry> factory, ResilienceStrategyTelemetry telemetry) + public ReloadableComponent(Entry entry, Func<Entry> factory) { Component = entry.Component; _reloadTokens = entry.ReloadTokens; _factory = factory; - _telemetry = telemetry; + _telemetry = entry.Telemetry; TryRegisterOnReload(); } @@ -61,7 +61,7 @@ private void TryRegisterOnReload() try { _telemetry.Report(new(ResilienceEventSeverity.Information, OnReloadEvent), context, new OnReloadArguments()); - (Component, _reloadTokens) = _factory(); + (Component, _reloadTokens, _telemetry) = _factory(); } catch (Exception e) { @@ -107,5 +107,5 @@ internal record DisposedFailedArguments(Exception Exception); internal record OnReloadArguments(); - internal record Entry(PipelineComponent Component, List<CancellationToken> ReloadTokens); + internal record Entry(PipelineComponent Component, List<CancellationToken> ReloadTokens, ResilienceStrategyTelemetry Telemetry); }
diff --git a/test/Polly.Core.Tests/Utils/Pipeline/ReloadablePipelineComponentTests.cs b/test/Polly.Core.Tests/Utils/Pipeline/ReloadablePipelineComponentTests.cs index 6eeca2a04df..371e4d88219 100644 --- a/test/Polly.Core.Tests/Utils/Pipeline/ReloadablePipelineComponentTests.cs +++ b/test/Polly.Core.Tests/Utils/Pipeline/ReloadablePipelineComponentTests.cs @@ -54,8 +54,9 @@ public async Task ChangeTriggered_StrategyReloaded() [Fact] public async Task ChangeTriggered_EnsureOldStrategyDisposed() { + var telemetry = TestUtilities.CreateResilienceTelemetry(_listener); var component = Substitute.For<PipelineComponent>(); - await using var sut = CreateSut(component, () => new(Substitute.For<PipelineComponent>(), new List<CancellationToken>())); + await using var sut = CreateSut(component, () => new(Substitute.For<PipelineComponent>(), new List<CancellationToken>(), telemetry)); for (var i = 0; i < 10; i++) { @@ -130,12 +131,11 @@ public async Task DisposeError_EnsureReported() private ReloadableComponent CreateSut(PipelineComponent? initial = null, Func<ReloadableComponent.Entry>? factory = null) { - factory ??= () => new ReloadableComponent.Entry(PipelineComponent.Empty, new List<CancellationToken>()); + factory ??= () => new ReloadableComponent.Entry(PipelineComponent.Empty, new List<CancellationToken>(), _telemetry); return (ReloadableComponent)PipelineComponentFactory.CreateReloadable( - new ReloadableComponent.Entry(initial ?? PipelineComponent.Empty, new List<CancellationToken> { _cancellationTokenSource.Token }), - factory, - _telemetry); + new ReloadableComponent.Entry(initial ?? PipelineComponent.Empty, new List<CancellationToken> { _cancellationTokenSource.Token }, _telemetry), + factory); } public void Dispose() => _cancellationTokenSource.Dispose(); diff --git a/test/Polly.Extensions.Tests/DependencyInjection/PollyServiceCollectionExtensionTests.cs b/test/Polly.Extensions.Tests/DependencyInjection/PollyServiceCollectionExtensionTests.cs index 8d6e160d52d..d2895657e18 100644 --- a/test/Polly.Extensions.Tests/DependencyInjection/PollyServiceCollectionExtensionTests.cs +++ b/test/Polly.Extensions.Tests/DependencyInjection/PollyServiceCollectionExtensionTests.cs @@ -1,5 +1,6 @@ using System.Globalization; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Polly.DependencyInjection; @@ -271,6 +272,55 @@ public void AddResiliencePipelineRegistry_ConfigureCallback_Ok() provider.GetRequiredService<IOptions<ResiliencePipelineRegistryOptions<string>>>().Value.InstanceNameFormatter.Should().Be(formatter); } + [InlineData(true)] + [InlineData(false)] + [Theory] + public void AddResiliencePipeline_CustomInstanceName_EnsureReported(bool usingBuilder) + { + // arrange + using var loggerFactory = new FakeLoggerFactory(); + + var context = ResilienceContextPool.Shared.Get("my-operation-key"); + var services = new ServiceCollection(); + var listener = new FakeTelemetryListener(); + var registry = services + .AddResiliencePipeline("my-pipeline", ConfigureBuilder) + .Configure<TelemetryOptions>(options => options.TelemetryListeners.Add(listener)) + .AddSingleton((ILoggerFactory)loggerFactory) + .BuildServiceProvider() + .GetRequiredService<ResiliencePipelineRegistry<string>>(); + + var pipeline = usingBuilder ? + registry.GetPipeline("my-pipeline") : + registry.GetOrAddPipeline("my-pipeline", ConfigureBuilder); + + // act + pipeline.Execute(_ => { }, context); + + // assert + foreach (var ev in listener.Events) + { + ev.Source.PipelineInstanceName.Should().Be("my-instance"); + ev.Source.PipelineName.Should().Be("my-pipeline"); + } + + var record = loggerFactory.FakeLogger.GetRecords(new EventId(0, "ResilienceEvent")).First(); + + record.Message.Should().Contain("my-pipeline/my-instance"); + + static void ConfigureBuilder(ResiliencePipelineBuilder builder) + { + builder.Name.Should().Be("my-pipeline"); + builder.InstanceName = "my-instance"; + builder.AddRetry(new() + { + ShouldHandle = _ => PredicateResult.True(), + MaxRetryAttempts = 3, + Delay = TimeSpan.Zero + }); + } + } + private void AddResiliencePipeline(string key, Action<StrategyBuilderContext>? onBuilding = null) { _services.AddResiliencePipeline(key, builder => diff --git a/test/Polly.Extensions.Tests/ReloadableResiliencePipelineTests.cs b/test/Polly.Extensions.Tests/ReloadableResiliencePipelineTests.cs index d3b71721fdc..6546ee3a2e6 100644 --- a/test/Polly.Extensions.Tests/ReloadableResiliencePipelineTests.cs +++ b/test/Polly.Extensions.Tests/ReloadableResiliencePipelineTests.cs @@ -3,6 +3,7 @@ using NSubstitute; using Polly.DependencyInjection; using Polly.Registry; +using Polly.Telemetry; namespace Polly.Extensions.Tests; @@ -20,6 +21,7 @@ public void AddResiliencePipeline_EnsureReloadable(string? name) var reloadableConfig = new ReloadableConfiguration(); reloadableConfig.Reload(new() { { "tag", "initial-tag" } }); var builder = new ConfigurationBuilder().Add(reloadableConfig); + var fakeListener = new FakeTelemetryListener(); var services = new ServiceCollection(); @@ -32,8 +34,11 @@ public void AddResiliencePipeline_EnsureReloadable(string? name) services.Configure<ReloadableStrategyOptions>(name, builder.Build()); } + services.Configure<TelemetryOptions>(options => options.TelemetryListeners.Add(fakeListener)); services.AddResiliencePipeline("my-pipeline", (builder, context) => { + builder.InstanceName = "my-instance"; + var options = context.GetOptions<ReloadableStrategyOptions>(name); context.EnableReloads<ReloadableStrategyOptions>(name); @@ -76,6 +81,11 @@ public void AddResiliencePipeline_EnsureReloadable(string? name) resList.Last().Received(1).Dispose(); pipeline.Invoking(p => p.Execute(() => { })).Should().Throw<ObjectDisposedException>(); + foreach (var ev in fakeListener.Events) + { + ev.Source.PipelineName.Should().Be("my-pipeline"); + ev.Source.PipelineInstanceName.Should().Be("my-instance"); + } } public class ReloadableStrategy : ResilienceStrategy, IDisposable diff --git a/test/Polly.TestUtils/FakeLoggerFactory.cs b/test/Polly.TestUtils/FakeLoggerFactory.cs new file mode 100644 index 00000000000..4b18bdad25a --- /dev/null +++ b/test/Polly.TestUtils/FakeLoggerFactory.cs @@ -0,0 +1,18 @@ +using Microsoft.Extensions.Logging; + +namespace Polly.TestUtils; + +public sealed class FakeLoggerFactory : ILoggerFactory +{ + public FakeLogger FakeLogger { get; } = new FakeLogger(); + + public void AddProvider(ILoggerProvider provider) + { + } + + public ILogger CreateLogger(string categoryName) => FakeLogger; + + public void Dispose() + { + } +}
Default logging behaviour when using InstanceName is unintuitive If a user chooses to set a `InstanceName` on a strategy/pipeline, its value is never passed through to telemetry and is always null. This is because by default the `InstanceNameFormatter` is null, so any value is always formatted to be `null`: https://github.com/App-vNext/Polly/blob/445c582a997fa24381ddd7dca1c347870852bcf8/src/Polly.Core/Registry/ResiliencePipelineRegistryOptions.cs#L38-L49 To get the desired behaviour, instead the user has to explicitly configure the internally-registered-by-default `ResiliencePipelineRegistryOptions<TKey>` type to provide a formatter for each type they generate a registry for: ```csharp services.AddOptions<ResiliencePipelineRegistryOptions<string>>() .Configure((p) => p.InstanceNameFormatter = (key) => key?.ToString() ?? string.Empty); ``` This behaviour is not intuitive (I had to work it out by debugging through the Polly sources from my app). It would be much easier for users to instead just apply a default formatter to the instance the same as we do for `BuilderNameFormatter`: https://github.com/App-vNext/Polly/blob/445c582a997fa24381ddd7dca1c347870852bcf8/src/Polly.Core/Registry/ResiliencePipelineRegistryOptions.cs#L51-L63 We could always pre-allocate the default formatter delegates as a private static field if allocations are a concern.
I am not sure whether this is a bur or feature. Let me explain the behavior/thinking about the instance name. Instance name is meant as an additional dimension in case there are multiple pipeline instances with the same name. It's advanced feature in case composite pipeline keys are used. For example: https://github.com/App-vNext/Polly/blob/305ac235c87ccf1ec33457213938ac7f138340e9/test/Polly.Extensions.Tests/Issues/IssuesTests.StrategiesPerEndpoint_1365.cs#L79 The reason `InstanceNameFormatter ` does not have a value assigned is that it would produce the same value as `BuilderNameFormatter`, so there would be no additional information added to the telemetry. ``` pipeline-name: my-key pipeline-instance: my-key ``` These two would always be the same as opposed to: ``` pipeline-name: my-key pipeline-instance: null ``` In the latter example we at least know that no instance was specified automatically. Besides nothing prevents anyone from doing: ``` csharp new ServiceCollection().AddResiliencePipeline("my-key", builder => { builder.InstanceName = "my-instance-name"; builder.AddConcurrencyLimiter(100); }); ``` In the case above the telemetry is: ``` pipeline-name: my-key pipeline-instance: my-instance-name ``` I'll re-check what I was doing, but this came up because (if I remember correctly) I saw that despite setting the instance name in the configuration method, the instance name was missing in the logs. Yep, the values are missing from the logged values unless the formatter is set. Not set: ```  PollySandbox.IntegrationTests.Can_Get_Movie  Source: IntegrationTests.cs line 33  Duration: 516 ms Standard Output:  [2023-09-06 12:42:37Z] info: System.Net.Http.HttpClient.Movies.LogicalHandler[100] Start processing HTTP request GET https://dummyapi.online/api/movies/5 [2023-09-06 12:42:37Z] info: System.Net.Http.HttpClient.Movies.LogicalHandler[101] End processing HTTP request after 8.9891ms - 200 [2023-09-06 12:42:37Z] info: Polly[3] Execution attempt. Source: 'Movies/Retry/Movies/Movies/Retry', Operation Key: 'Movies.GetMovieAsync', Result: 'PollySandbox.Movie', Handled: 'False', Attempt: '0', Execution Time: '53.5176' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/(null)/(null)', Operation Key: '', Result: '' [2023-09-06 12:42:37Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/(null)/(null)', Operation Key: '', Result: '' ``` Set: ```  PollySandbox.IntegrationTests.Can_Get_Movie  Source: IntegrationTests.cs line 33  Duration: 451 ms Standard Output:  [2023-09-06 12:41:44Z] info: System.Net.Http.HttpClient.Movies.LogicalHandler[100] Start processing HTTP request GET https://dummyapi.online/api/movies/5 [2023-09-06 12:41:44Z] info: System.Net.Http.HttpClient.Movies.LogicalHandler[101] End processing HTTP request after 8.7178ms - 200 [2023-09-06 12:41:44Z] info: Polly[3] Execution attempt. Source: 'Movies/Retry/Movies/Movies/Retry', Operation Key: 'Movies.GetMovieAsync', Result: 'PollySandbox.Movie', Handled: 'False', Attempt: '0', Execution Time: '48.4437' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/GetMovieAsync/Movies/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/RateLimit/Movies/RateLimit/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Timeout/Movies/Timeout/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/CircuitBreaker/GetMovieAsync/Movies/CircuitBreaker/GetMovieAsync/(null)', Operation Key: '', Result: '' [2023-09-06 12:41:44Z] info: Polly[0] Resilience event occurred. EventName: 'OnReload', Source: 'Movies/Retry/Movies/Retry/(null)', Operation Key: '', Result: '' ``` > I'll re-check what I was doing, but this came up because (if I remember correctly) I saw that despite setting the instance name in the configuration method, the instance name was missing in the logs. Can you point me to piece that sets the `InstanceName` ? It doesn't in the PR, I just changed it locally to add `builder.InstanceName = builder.Name` in a few places.
2023-09-06T13:24:15Z
0.2
[]
['Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.ChangeTriggered_FactoryError_LastStrategyUsedAndErrorReported', 'Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.DisposeError_EnsureReported', 'Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.DisposeAsync_ComponentDisposed', 'Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.ChangeTriggered_EnsureOldStrategyDisposed', 'Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.Ctor_Ok', 'Polly.Core.Tests.Utils.Pipeline.ReloadablePipelineComponentTests.ChangeTriggered_StrategyReloaded']
App-vNext/Polly
polly-1528
a0be5612f1144ed13278b14b7e7e0b72071ab617
diff --git a/bench/Polly.Core.Benchmarks/CreationBenchmark.cs b/bench/Polly.Core.Benchmarks/CreationBenchmark.cs index ac3e507b2bf..52c44f037e2 100644 --- a/bench/Polly.Core.Benchmarks/CreationBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/CreationBenchmark.cs @@ -18,7 +18,7 @@ public static void Fallback_V8() new ResiliencePipelineBuilder<string>() .AddFallback(new() { - FallbackAction = _ => Outcome.FromResultAsTask("fallback") + FallbackAction = _ => Outcome.FromResultAsValueTask("fallback") }) .Build(); } diff --git a/bench/Polly.Core.Benchmarks/PredicateBenchmark.cs b/bench/Polly.Core.Benchmarks/PredicateBenchmark.cs index 77948b2ab05..7fa8cf0ccd5 100644 --- a/bench/Polly.Core.Benchmarks/PredicateBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/PredicateBenchmark.cs @@ -14,11 +14,11 @@ public class PredicateBenchmark { ShouldHandle = args => args.Outcome switch { - { Result: { StatusCode: HttpStatusCode.InternalServerError } } => PredicateResult.True, - { Exception: HttpRequestException } => PredicateResult.True, - { Exception: IOException } => PredicateResult.True, - { Exception: InvalidOperationException } => PredicateResult.False, - _ => PredicateResult.False, + { Result: { StatusCode: HttpStatusCode.InternalServerError } } => PredicateResult.True(), + { Exception: HttpRequestException } => PredicateResult.True(), + { Exception: IOException } => PredicateResult.True(), + { Exception: InvalidOperationException } => PredicateResult.False(), + _ => PredicateResult.False(), } }; diff --git a/bench/Polly.Core.Benchmarks/ResiliencePipelineBenchmark.cs b/bench/Polly.Core.Benchmarks/ResiliencePipelineBenchmark.cs index 55bea8960cb..54ef684a26a 100644 --- a/bench/Polly.Core.Benchmarks/ResiliencePipelineBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/ResiliencePipelineBenchmark.cs @@ -10,7 +10,7 @@ public class ResiliencePipelineBenchmark public async ValueTask ExecuteOutcomeAsync() { var context = ResilienceContextPool.Shared.Get(); - await ResiliencePipeline.Empty.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsTask("dummy"), context, "state").ConfigureAwait(false); + await ResiliencePipeline.Empty.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("dummy"), context, "state").ConfigureAwait(false); ResilienceContextPool.Shared.Return(context); } diff --git a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs index e4ca157469f..667e8d30b1a 100644 --- a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs @@ -33,7 +33,7 @@ public void Prepare() public async ValueTask Execute() { var context = ResilienceContextPool.Shared.Get(); - await _pipeline!.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsTask("dummy"), context, "state").ConfigureAwait(false); + await _pipeline!.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("dummy"), context, "state").ConfigureAwait(false); ResilienceContextPool.Shared.Return(context); } diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.CircuitBreaker.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.CircuitBreaker.cs index c4d2c358d41..c7cd8f451bb 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.CircuitBreaker.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.CircuitBreaker.cs @@ -7,7 +7,7 @@ public static object CreateOpenedCircuitBreaker(PollyVersion version, bool handl var manualControl = new CircuitBreakerManualControl(); var options = new CircuitBreakerStrategyOptions { - ShouldHandle = _ => PredicateResult.True, + ShouldHandle = _ => PredicateResult.True(), ManualControl = manualControl, }; @@ -54,9 +54,9 @@ public static object CreateCircuitBreaker(PollyVersion technology) BreakDuration = TimeSpan.FromSeconds(5), ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() } }); }), diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.Hedging.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.Hedging.cs index 7b5b62aa7c7..856e5a8a7af 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.Hedging.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.Hedging.cs @@ -13,7 +13,7 @@ public static ResiliencePipeline<string> CreateHedging() builder.AddHedging(new HedgingStrategyOptions<string> { ShouldHandle = args => new ValueTask<bool>(args.Outcome.Result == Failure), - ActionGenerator = args => () => Outcome.FromResultAsTask("hedged response"), + ActionGenerator = args => () => Outcome.FromResultAsValueTask("hedged response"), }); }); } diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs index 5b15fa917c1..1ff82eaaf8e 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs @@ -29,9 +29,9 @@ internal static partial class Helper Delay = TimeSpan.FromSeconds(1), ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() } }) .AddTimeout(TimeSpan.FromSeconds(1)) @@ -43,9 +43,9 @@ internal static partial class Helper BreakDuration = TimeSpan.FromSeconds(5), ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() } }); @@ -73,9 +73,9 @@ public static ResiliencePipeline CreateNonGenericStrategyPipeline(bool telemetry Delay = TimeSpan.FromSeconds(1), ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() } }) .AddTimeout(TimeSpan.FromSeconds(1)) @@ -87,9 +87,9 @@ public static ResiliencePipeline CreateNonGenericStrategyPipeline(bool telemetry BreakDuration = TimeSpan.FromSeconds(5), ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() } }); diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.Retry.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.Retry.cs index 4d49ef66825..ae3297d0a31 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.Retry.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.Retry.cs @@ -23,9 +23,9 @@ public static object CreateRetry(PollyVersion technology) Delay = delay, ShouldHandle = args => args.Outcome switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() }, OnRetry = _ => default }); diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.cs index f0acdc8f243..9fefb506a69 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.cs @@ -15,7 +15,7 @@ public static async ValueTask ExecuteAsync(this object obj, PollyVersion version var context = ResilienceContextPool.Shared.Get(); await ((ResiliencePipeline<string>)obj).ExecuteOutcomeAsync( - static (_, _) => Outcome.FromResultAsTask("dummy"), + static (_, _) => Outcome.FromResultAsValueTask("dummy"), context, string.Empty).ConfigureAwait(false); diff --git a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs index cc56c1b87aa..fcd35117e06 100644 --- a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs +++ b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs @@ -298,9 +298,9 @@ private void SetLastHandledOutcome_NeedsLock(Outcome<T> outcome) { _breakingException = new BrokenCircuitException(BrokenCircuitException.DefaultMessage, exception); } - else if (outcome.TryGetResult(out var result)) + else { - _breakingException = new BrokenCircuitException<T>(BrokenCircuitException.DefaultMessage, result!); + _breakingException = new BrokenCircuitException(BrokenCircuitException.DefaultMessage); } } diff --git a/src/Polly.Core/Outcome.TResult.cs b/src/Polly.Core/Outcome.TResult.cs index 2bb88010b36..ad5a077fce9 100644 --- a/src/Polly.Core/Outcome.TResult.cs +++ b/src/Polly.Core/Outcome.TResult.cs @@ -56,7 +56,7 @@ internal Outcome(ExceptionDispatchInfo exceptionDispatchInfo) /// <remarks> /// If the operation produced a result, this method does nothing. The thrown exception maintains its original stack trace. /// </remarks> - public void EnsureSuccess() => ExceptionDispatchInfo?.Throw(); + public void ThrowIfException() => ExceptionDispatchInfo?.Throw(); /// <summary> /// Tries to get the result, if available. diff --git a/src/Polly.Core/Outcome.cs b/src/Polly.Core/Outcome.cs index adf0a210fe5..ec6b79e2950 100644 --- a/src/Polly.Core/Outcome.cs +++ b/src/Polly.Core/Outcome.cs @@ -19,7 +19,7 @@ public static class Outcome /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="value">The result value.</param> /// <returns>A completed <see cref="ValueTask{TResult}"/> that produces <see cref="Outcome{TResult}"/>.</returns> - public static ValueTask<Outcome<TResult>> FromResultAsTask<TResult>(TResult value) => new(FromResult(value)); + public static ValueTask<Outcome<TResult>> FromResultAsValueTask<TResult>(TResult value) => new(FromResult(value)); /// <summary> /// Returns a <see cref="Outcome{TResult}"/> with the given <paramref name="exception"/>. @@ -42,7 +42,7 @@ public static Outcome<TResult> FromException<TResult>(Exception exception) /// <param name="exception">The exception.</param> /// <returns>A completed <see cref="ValueTask{TResult}"/> that produces <see cref="Outcome{TResult}"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="exception"/> is <see langword="null"/>.</exception> - public static ValueTask<Outcome<TResult>> FromExceptionAsTask<TResult>(Exception exception) + public static ValueTask<Outcome<TResult>> FromExceptionAsValueTask<TResult>(Exception exception) { Guard.NotNull(exception); diff --git a/src/Polly.Core/PredicateResult.cs b/src/Polly.Core/PredicateResult.cs index 89daced9217..49356ac67cb 100644 --- a/src/Polly.Core/PredicateResult.cs +++ b/src/Polly.Core/PredicateResult.cs @@ -6,12 +6,14 @@ namespace Polly; public static class PredicateResult { /// <summary> - /// Gets a finished <see cref="ValueTask{TResult}"/> that returns <see langword="true"/> value. + /// Returns a finished <see cref="ValueTask{TResult}"/> that returns <see langword="true"/> value. /// </summary> - public static ValueTask<bool> True => new(true); + /// <returns>A new instance of finished <see cref="ValueTask{TResult}"/>.</returns> + public static ValueTask<bool> True() => new(true); /// <summary> - /// Gets a finished <see cref="ValueTask{TResult}"/> that returns <see langword="false"/> value. + /// Returns a finished <see cref="ValueTask{TResult}"/> that returns <see langword="false"/> value. /// </summary> - public static ValueTask<bool> False => new(false); + /// <returns>A new instance of finished <see cref="ValueTask{TResult}"/>.</returns> + public static ValueTask<bool> False() => new(false); } diff --git a/src/Polly.Core/PublicAPI.Unshipped.txt b/src/Polly.Core/PublicAPI.Unshipped.txt index d690461ed16..74c19f8c4ed 100644 --- a/src/Polly.Core/PublicAPI.Unshipped.txt +++ b/src/Polly.Core/PublicAPI.Unshipped.txt @@ -15,11 +15,6 @@ Polly.CircuitBreaker.BrokenCircuitException Polly.CircuitBreaker.BrokenCircuitException.BrokenCircuitException() -> void Polly.CircuitBreaker.BrokenCircuitException.BrokenCircuitException(string! message) -> void Polly.CircuitBreaker.BrokenCircuitException.BrokenCircuitException(string! message, System.Exception! inner) -> void -Polly.CircuitBreaker.BrokenCircuitException<TResult> -Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(string! message, System.Exception! inner, TResult result) -> void -Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(string! message, TResult result) -> void -Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(TResult result) -> void -Polly.CircuitBreaker.BrokenCircuitException<TResult>.Result.get -> TResult Polly.CircuitBreaker.CircuitBreakerManualControl Polly.CircuitBreaker.CircuitBreakerManualControl.CircuitBreakerManualControl() -> void Polly.CircuitBreaker.CircuitBreakerManualControl.CircuitBreakerManualControl(bool isIsolated) -> void @@ -158,10 +153,10 @@ Polly.HedgingResiliencePipelineBuilderExtensions Polly.LegacySupport Polly.Outcome Polly.Outcome<TResult> -Polly.Outcome<TResult>.EnsureSuccess() -> void Polly.Outcome<TResult>.Exception.get -> System.Exception? Polly.Outcome<TResult>.Outcome() -> void Polly.Outcome<TResult>.Result.get -> TResult? +Polly.Outcome<TResult>.ThrowIfException() -> void Polly.PredicateBuilder Polly.PredicateBuilder.PredicateBuilder() -> void Polly.PredicateBuilder<TResult> @@ -296,10 +291,9 @@ Polly.Retry.OnRetryArguments<TResult>.RetryDelay.get -> System.TimeSpan Polly.Retry.RetryDelayGeneratorArguments<TResult> Polly.Retry.RetryDelayGeneratorArguments<TResult>.AttemptNumber.get -> int Polly.Retry.RetryDelayGeneratorArguments<TResult>.Context.get -> Polly.ResilienceContext! -Polly.Retry.RetryDelayGeneratorArguments<TResult>.DelayHint.get -> System.TimeSpan Polly.Retry.RetryDelayGeneratorArguments<TResult>.Outcome.get -> Polly.Outcome<TResult> Polly.Retry.RetryDelayGeneratorArguments<TResult>.RetryDelayGeneratorArguments() -> void -Polly.Retry.RetryDelayGeneratorArguments<TResult>.RetryDelayGeneratorArguments(Polly.ResilienceContext! context, Polly.Outcome<TResult> outcome, int attemptNumber, System.TimeSpan delayHint) -> void +Polly.Retry.RetryDelayGeneratorArguments<TResult>.RetryDelayGeneratorArguments(Polly.ResilienceContext! context, Polly.Outcome<TResult> outcome, int attemptNumber) -> void Polly.Retry.RetryPredicateArguments<TResult> Polly.Retry.RetryPredicateArguments<TResult>.AttemptNumber.get -> int Polly.Retry.RetryPredicateArguments<TResult>.Context.get -> Polly.ResilienceContext! @@ -313,7 +307,7 @@ Polly.Retry.RetryStrategyOptions<TResult>.BackoffType.get -> Polly.DelayBackoffT Polly.Retry.RetryStrategyOptions<TResult>.BackoffType.set -> void Polly.Retry.RetryStrategyOptions<TResult>.Delay.get -> System.TimeSpan Polly.Retry.RetryStrategyOptions<TResult>.Delay.set -> void -Polly.Retry.RetryStrategyOptions<TResult>.DelayGenerator.get -> System.Func<Polly.Retry.RetryDelayGeneratorArguments<TResult>, System.Threading.Tasks.ValueTask<System.TimeSpan>>? +Polly.Retry.RetryStrategyOptions<TResult>.DelayGenerator.get -> System.Func<Polly.Retry.RetryDelayGeneratorArguments<TResult>, System.Threading.Tasks.ValueTask<System.TimeSpan?>>? Polly.Retry.RetryStrategyOptions<TResult>.DelayGenerator.set -> void Polly.Retry.RetryStrategyOptions<TResult>.MaxRetryAttempts.get -> int Polly.Retry.RetryStrategyOptions<TResult>.MaxRetryAttempts.set -> void @@ -403,15 +397,15 @@ static Polly.FallbackResiliencePipelineBuilderExtensions.AddFallback<TResult>(th static Polly.HedgingResiliencePipelineBuilderExtensions.AddHedging<TResult>(this Polly.ResiliencePipelineBuilder<TResult>! builder, Polly.Hedging.HedgingStrategyOptions<TResult>! options) -> Polly.ResiliencePipelineBuilder<TResult>! static Polly.LegacySupport.SetProperties(this Polly.ResilienceProperties! resilienceProperties, System.Collections.Generic.IDictionary<string!, object?>! properties, out System.Collections.Generic.IDictionary<string!, object?>! oldProperties) -> void static Polly.Outcome.FromException<TResult>(System.Exception! exception) -> Polly.Outcome<TResult> -static Polly.Outcome.FromExceptionAsTask<TResult>(System.Exception! exception) -> System.Threading.Tasks.ValueTask<Polly.Outcome<TResult>> +static Polly.Outcome.FromExceptionAsValueTask<TResult>(System.Exception! exception) -> System.Threading.Tasks.ValueTask<Polly.Outcome<TResult>> static Polly.Outcome.FromResult<TResult>(TResult? value) -> Polly.Outcome<TResult> -static Polly.Outcome.FromResultAsTask<TResult>(TResult value) -> System.Threading.Tasks.ValueTask<Polly.Outcome<TResult>> +static Polly.Outcome.FromResultAsValueTask<TResult>(TResult value) -> System.Threading.Tasks.ValueTask<Polly.Outcome<TResult>> static Polly.PredicateBuilder<TResult>.implicit operator System.Func<Polly.CircuitBreaker.CircuitBreakerPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>!(Polly.PredicateBuilder<TResult>! builder) -> System.Func<Polly.CircuitBreaker.CircuitBreakerPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>! static Polly.PredicateBuilder<TResult>.implicit operator System.Func<Polly.Fallback.FallbackPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>!(Polly.PredicateBuilder<TResult>! builder) -> System.Func<Polly.Fallback.FallbackPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>! static Polly.PredicateBuilder<TResult>.implicit operator System.Func<Polly.Hedging.HedgingPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>!(Polly.PredicateBuilder<TResult>! builder) -> System.Func<Polly.Hedging.HedgingPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>! static Polly.PredicateBuilder<TResult>.implicit operator System.Func<Polly.Retry.RetryPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>!(Polly.PredicateBuilder<TResult>! builder) -> System.Func<Polly.Retry.RetryPredicateArguments<TResult>, System.Threading.Tasks.ValueTask<bool>>! -static Polly.PredicateResult.False.get -> System.Threading.Tasks.ValueTask<bool> -static Polly.PredicateResult.True.get -> System.Threading.Tasks.ValueTask<bool> +static Polly.PredicateResult.False() -> System.Threading.Tasks.ValueTask<bool> +static Polly.PredicateResult.True() -> System.Threading.Tasks.ValueTask<bool> static Polly.ResilienceContextPool.Shared.get -> Polly.ResilienceContextPool! static Polly.ResiliencePipelineBuilderExtensions.AddPipeline<TBuilder>(this TBuilder! builder, Polly.ResiliencePipeline! pipeline) -> TBuilder! static Polly.ResiliencePipelineBuilderExtensions.AddPipeline<TResult>(this Polly.ResiliencePipelineBuilder<TResult>! builder, Polly.ResiliencePipeline<TResult>! pipeline) -> Polly.ResiliencePipelineBuilder<TResult>! diff --git a/src/Polly.Core/README.md b/src/Polly.Core/README.md index 867d5e2f828..6140cdc6364 100644 --- a/src/Polly.Core/README.md +++ b/src/Polly.Core/README.md @@ -226,10 +226,10 @@ new ResiliencePipelineBuilder() { ShouldRetry = args => args switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: string result } when result == Failure => PredicateResult.True, - { Result: int result } when result == -1 => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: string result } when result == Failure => PredicateResult.True(), + { Result: int result } when result == -1 => PredicateResult.True(), + _ => PredicateResult.False() }, }) .Build(); @@ -243,9 +243,9 @@ new ResiliencePipelineBuilder() { ShouldRetry = args => args switch { - { Exception: InvalidOperationException } => PredicateResult.True, - { Result: result } when result == Failure => PredicateResult.True, - _ => PredicateResult.False + { Exception: InvalidOperationException } => PredicateResult.True(), + { Result: result } when result == Failure => PredicateResult.True(), + _ => PredicateResult.False() }, }) .Build(); diff --git a/src/Polly.Core/Retry/RetryDelayGeneratorArguments.cs b/src/Polly.Core/Retry/RetryDelayGeneratorArguments.cs index 161c99ad6d9..a327ae6e88d 100644 --- a/src/Polly.Core/Retry/RetryDelayGeneratorArguments.cs +++ b/src/Polly.Core/Retry/RetryDelayGeneratorArguments.cs @@ -17,13 +17,11 @@ public readonly struct RetryDelayGeneratorArguments<TResult> /// <param name="outcome">The context in which the resilience operation or event occurred.</param> /// <param name="context">The outcome of the resilience operation or event.</param> /// <param name="attemptNumber">The zero-based attempt number.</param> - /// <param name="delayHint">The delay suggested by the retry strategy.</param> - public RetryDelayGeneratorArguments(ResilienceContext context, Outcome<TResult> outcome, int attemptNumber, TimeSpan delayHint) + public RetryDelayGeneratorArguments(ResilienceContext context, Outcome<TResult> outcome, int attemptNumber) { Context = context; Outcome = outcome; AttemptNumber = attemptNumber; - DelayHint = delayHint; } /// <summary> @@ -40,9 +38,4 @@ public RetryDelayGeneratorArguments(ResilienceContext context, Outcome<TResult> /// Gets The zero-based attempt number. /// </summary> public int AttemptNumber { get; } - - /// <summary> - /// Gets the delay suggested by the retry strategy. - /// </summary> - public TimeSpan DelayHint { get; } } diff --git a/src/Polly.Core/Retry/RetryResilienceStrategy.cs b/src/Polly.Core/Retry/RetryResilienceStrategy.cs index 62eccd7e4fa..6d61e7bdaf7 100644 --- a/src/Polly.Core/Retry/RetryResilienceStrategy.cs +++ b/src/Polly.Core/Retry/RetryResilienceStrategy.cs @@ -34,7 +34,7 @@ public RetryResilienceStrategy( public Func<RetryPredicateArguments<T>, ValueTask<bool>> ShouldHandle { get; } - public Func<RetryDelayGeneratorArguments<T>, ValueTask<TimeSpan>>? DelayGenerator { get; } + public Func<RetryDelayGeneratorArguments<T>, ValueTask<TimeSpan?>>? DelayGenerator { get; } public bool UseJitter { get; } @@ -64,9 +64,9 @@ protected internal override async ValueTask<Outcome<T>> ExecuteCore<TState>(Func var delay = RetryHelper.GetRetryDelay(BackoffType, UseJitter, attempt, BaseDelay, ref retryState, _randomizer); if (DelayGenerator is not null) { - var delayArgs = new RetryDelayGeneratorArguments<T>(context, outcome, attempt, delay); - var newDelay = await DelayGenerator(delayArgs).ConfigureAwait(false); - if (RetryHelper.IsValidDelay(newDelay)) + var delayArgs = new RetryDelayGeneratorArguments<T>(context, outcome, attempt); + + if (await DelayGenerator(delayArgs).ConfigureAwait(false) is TimeSpan newDelay && RetryHelper.IsValidDelay(newDelay)) { delay = newDelay; } diff --git a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs index aa4015af4f7..797d65c981b 100644 --- a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs +++ b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs @@ -85,12 +85,13 @@ public class RetryStrategyOptions<TResult> : ResilienceStrategyOptions /// Gets or sets a generator that calculates the delay between retries. /// </summary> /// <remarks> - /// The generator has precedence over <see cref="Delay"/> and <see cref="BackoffType"/>. + /// The generator can override the delay generated by the retry strategy. If the generator returns <see langword="null"/>, the delay generated + /// by the retry strategy for that attempt will be used. /// </remarks> /// <value> /// The default value is <see langword="null"/>. /// </value> - public Func<RetryDelayGeneratorArguments<TResult>, ValueTask<TimeSpan>>? DelayGenerator { get; set; } + public Func<RetryDelayGeneratorArguments<TResult>, ValueTask<TimeSpan?>>? DelayGenerator { get; set; } /// <summary> /// Gets or sets an event delegate that is raised when the retry happens. diff --git a/src/Polly.Core/Utils/DefaultPredicates.cs b/src/Polly.Core/Utils/DefaultPredicates.cs index ae74ed8cbfd..fdbcb3efa55 100644 --- a/src/Polly.Core/Utils/DefaultPredicates.cs +++ b/src/Polly.Core/Utils/DefaultPredicates.cs @@ -4,8 +4,8 @@ internal static class DefaultPredicates<TArgs, TResult> { public static readonly Func<TArgs, ValueTask<bool>> HandleOutcome = args => args.Outcome.Exception switch { - OperationCanceledException => PredicateResult.False, - Exception => PredicateResult.True, - _ => PredicateResult.False + OperationCanceledException => PredicateResult.False(), + Exception => PredicateResult.True(), + _ => PredicateResult.False() }; } diff --git a/src/Polly.Core/Utils/Pipeline/CompositeComponent.cs b/src/Polly.Core/Utils/Pipeline/CompositeComponent.cs index ef2daa09d1d..8ec9515df29 100644 --- a/src/Polly.Core/Utils/Pipeline/CompositeComponent.cs +++ b/src/Polly.Core/Utils/Pipeline/CompositeComponent.cs @@ -97,7 +97,7 @@ private ValueTask<Outcome<TResult>> ExecuteCoreWithoutTelemetry<TResult, TState> { if (context.CancellationToken.IsCancellationRequested) { - return Outcome.FromExceptionAsTask<TResult>(new OperationCanceledException(context.CancellationToken).TrySetStackTrace()); + return Outcome.FromExceptionAsValueTask<TResult>(new OperationCanceledException(context.CancellationToken).TrySetStackTrace()); } else { @@ -146,7 +146,7 @@ internal override ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>( { if (context.CancellationToken.IsCancellationRequested) { - return Outcome.FromExceptionAsTask<TResult>(new OperationCanceledException(context.CancellationToken).TrySetStackTrace()); + return Outcome.FromExceptionAsValueTask<TResult>(new OperationCanceledException(context.CancellationToken).TrySetStackTrace()); } return state.Next!.ExecuteCore(state.callback, context, state.state); diff --git a/src/Polly.Core/CircuitBreaker/BrokenCircuitException.TResult.cs b/src/Polly/CircuitBreaker/BrokenCircuitException.TResult.cs similarity index 100% rename from src/Polly.Core/CircuitBreaker/BrokenCircuitException.TResult.cs rename to src/Polly/CircuitBreaker/BrokenCircuitException.TResult.cs diff --git a/src/Polly/Properties/AssemblyInfo.cs b/src/Polly/Properties/AssemblyInfo.cs index a96745bc506..b949813529e 100644 --- a/src/Polly/Properties/AssemblyInfo.cs +++ b/src/Polly/Properties/AssemblyInfo.cs @@ -6,6 +6,5 @@ [assembly: TypeForwardedTo(typeof(ExecutionRejectedException))] [assembly: TypeForwardedTo(typeof(TimeoutRejectedException))] [assembly: TypeForwardedTo(typeof(BrokenCircuitException))] -[assembly: TypeForwardedTo(typeof(BrokenCircuitException<>))] [assembly: TypeForwardedTo(typeof(IsolatedCircuitException))] [assembly: TypeForwardedTo(typeof(CircuitState))] diff --git a/src/Polly/PublicAPI.Shipped.txt b/src/Polly/PublicAPI.Shipped.txt index 4c456056fe9..22ba236f1fa 100644 --- a/src/Polly/PublicAPI.Shipped.txt +++ b/src/Polly/PublicAPI.Shipped.txt @@ -1052,3 +1052,9 @@ static readonly Polly.ExceptionPredicates.None -> Polly.ExceptionPredicates static readonly Polly.ResultPredicates<TResult>.None -> Polly.ResultPredicates<TResult> virtual Polly.AsyncPolicy.ImplementationAsync(System.Func<Polly.Context, System.Threading.CancellationToken, System.Threading.Tasks.Task> action, Polly.Context context, System.Threading.CancellationToken cancellationToken, bool continueOnCapturedContext) -> System.Threading.Tasks.Task virtual Polly.Policy.Implementation(System.Action<Polly.Context, System.Threading.CancellationToken> action, Polly.Context context, System.Threading.CancellationToken cancellationToken) -> void +Polly.CircuitBreaker.BrokenCircuitException<TResult> +Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(string message, System.Exception inner, TResult result) -> void +Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(string message, TResult result) -> void +Polly.CircuitBreaker.BrokenCircuitException<TResult>.BrokenCircuitException(TResult result) -> void +Polly.CircuitBreaker.BrokenCircuitException<TResult>.Result.get -> TResult +
diff --git a/test/Polly.Core.Tests/CircuitBreaker/BrokenCircuitExceptionTests.cs b/test/Polly.Core.Tests/CircuitBreaker/BrokenCircuitExceptionTests.cs index 075e04b55f1..3fb989e7a59 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/BrokenCircuitExceptionTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/BrokenCircuitExceptionTests.cs @@ -12,39 +12,11 @@ public void Ctor_Ok() new BrokenCircuitException("Dummy.", new InvalidOperationException()).InnerException.Should().BeOfType<InvalidOperationException>(); } - [Fact] - public void Ctor_Generic_Ok() - { - var exception = new BrokenCircuitException<int>(10); - exception.Result.Should().Be(10); - - exception = new BrokenCircuitException<int>("Dummy.", 10); - exception.Message.Should().Be("Dummy."); - exception.Result.Should().Be(10); - - exception = new BrokenCircuitException<int>("Dummy.", new InvalidOperationException(), 10); - exception.Message.Should().Be("Dummy."); - exception.Result.Should().Be(10); - exception.InnerException.Should().BeOfType<InvalidOperationException>(); - } - #if !NETCOREAPP [Fact] public void BinarySerialization_Ok() { BinarySerializationUtil.SerializeAndDeserializeException(new BrokenCircuitException()).Should().NotBeNull(); } - - [Fact] - public void BinarySerialization_Generic_Ok() - { - var result = BinarySerializationUtil - .SerializeAndDeserializeException(new BrokenCircuitException<int>(123)); - - result.Should().NotBeNull(); - - // default - result.Result.Should().Be(0); - } #endif } diff --git a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs index d05ebf5914a..c9bb40cb017 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResiliencePipelineBuilderTests.cs @@ -11,7 +11,7 @@ public class CircuitBreakerResiliencePipelineBuilderTests { builder => builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions { - ShouldHandle = _ => PredicateResult.True + ShouldHandle = _ => PredicateResult.True() }), }; @@ -19,7 +19,7 @@ public class CircuitBreakerResiliencePipelineBuilderTests { builder => builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<int> { - ShouldHandle = _ => PredicateResult.True + ShouldHandle = _ => PredicateResult.True() }), }; @@ -90,12 +90,12 @@ public void AddCircuitBreaker_IntegrationTest() opened.Should().Be(1); halfOpened.Should().Be(0); closed.Should().Be(0); - Assert.Throws<BrokenCircuitException<object>>(() => strategy.Execute(_ => 0)); + Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); // Circuit Half Opened timeProvider.Advance(options.BreakDuration); strategy.Execute(_ => -1); - Assert.Throws<BrokenCircuitException<object>>(() => strategy.Execute(_ => 0)); + Assert.Throws<BrokenCircuitException>(() => strategy.Execute(_ => 0)); opened.Should().Be(2); halfOpened.Should().Be(1); closed.Should().Be(0); diff --git a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs index fe0d54ee9e9..03c7d7c7658 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/CircuitBreakerResilienceStrategyTests.cs @@ -123,7 +123,7 @@ public void Execute_UnhandledException_NoCalls() [Fact] public void Execute_Ok() { - _options.ShouldHandle = _ => PredicateResult.False; + _options.ShouldHandle = _ => PredicateResult.False(); Create().Invoking(s => s.Execute(_ => 0)).Should().NotThrow(); diff --git a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs index 4e846e71385..75bcfc367d5 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs @@ -118,9 +118,8 @@ public async Task OnActionPreExecute_CircuitOpenedByValue() using var controller = CreateController(); await OpenCircuit(controller, Outcome.FromResult(99)); - var error = (BrokenCircuitException<int>)(await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get())).Value.Exception!; - error.Should().BeOfType<BrokenCircuitException<int>>(); - error.Result.Should().Be(99); + var error = (BrokenCircuitException)(await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get())).Value.Exception!; + error.Should().BeOfType<BrokenCircuitException>(); GetBlockedTill(controller).Should().Be(_timeProvider.GetUtcNow() + _options.BreakDuration); } @@ -219,7 +218,7 @@ public async Task OnActionPreExecute_HalfOpen() // act await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get()); var error = (await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get())).Value.Exception; - error.Should().BeOfType<BrokenCircuitException<int>>(); + error.Should().BeOfType<BrokenCircuitException>(); // assert controller.CircuitState.Should().Be(CircuitState.HalfOpen); @@ -357,7 +356,7 @@ public async Task OnActionFailureAsync_VoidResult_EnsureBreakingExceptionNotSet( // assert controller.LastException.Should().BeNull(); var outcome = await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get()); - outcome.Value.Exception.Should().BeOfType<BrokenCircuitException<int>>(); + outcome.Value.Exception.Should().BeOfType<BrokenCircuitException>(); } [Fact] @@ -392,7 +391,7 @@ public async Task Flow_Closed_HalfOpen_Open_HalfOpen_Closed() // execution rejected AdvanceTime(TimeSpan.FromMilliseconds(1)); var outcome = await controller.OnActionPreExecuteAsync(ResilienceContextPool.Shared.Get()); - outcome.Value.Exception.Should().BeOfType<BrokenCircuitException<int>>(); + outcome.Value.Exception.Should().BeOfType<BrokenCircuitException>(); // wait and try, transition to half open AdvanceTime(_options.BreakDuration + _options.BreakDuration); diff --git a/test/Polly.Core.Tests/Fallback/FallbackResiliencePipelineBuilderExtensionsTests.cs b/test/Polly.Core.Tests/Fallback/FallbackResiliencePipelineBuilderExtensionsTests.cs index 5c601b34b91..6dbe198712d 100644 --- a/test/Polly.Core.Tests/Fallback/FallbackResiliencePipelineBuilderExtensionsTests.cs +++ b/test/Polly.Core.Tests/Fallback/FallbackResiliencePipelineBuilderExtensionsTests.cs @@ -12,8 +12,8 @@ public class FallbackResiliencePipelineBuilderExtensionsTests { builder.AddFallback(new FallbackStrategyOptions<int> { - FallbackAction = _ => Outcome.FromResultAsTask(0), - ShouldHandle = _ => PredicateResult.False, + FallbackAction = _ => Outcome.FromResultAsValueTask(0), + ShouldHandle = _ => PredicateResult.False(), }); } }; diff --git a/test/Polly.Core.Tests/Fallback/FallbackResilienceStrategyTests.cs b/test/Polly.Core.Tests/Fallback/FallbackResilienceStrategyTests.cs index 0e0cbad4ab9..8415d82e19d 100644 --- a/test/Polly.Core.Tests/Fallback/FallbackResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Fallback/FallbackResilienceStrategyTests.cs @@ -52,7 +52,7 @@ public void ShouldHandle_ArgumentsSetCorrectly(bool handle) args.Outcome.Result.Should().Be("ok"); args.Context.Should().NotBeNull(); called++; - return Outcome.FromResultAsTask("fallback"); + return Outcome.FromResultAsValueTask("fallback"); }); var result = Create().Execute(_ => "ok"); diff --git a/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs b/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs index 33927630462..e31fffc15b1 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs @@ -28,7 +28,7 @@ public async Task Pooling_Ok() private static async Task PrepareAsync(HedgingExecutionContext<int> context) { - await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsTask(10), "state"); + await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsValueTask(10), "state"); await context.TryWaitForCompletedExecutionAsync(System.Threading.Timeout.InfiniteTimeSpan); context.Tasks[0].AcceptOutcome(); } diff --git a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs index bbd20da0eb9..8c0a2700e2d 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs @@ -97,7 +97,7 @@ public async Task TryWaitForCompletedExecutionAsync_FinishedTask_Ok() { var context = Create(); context.Initialize(_resilienceContext); - await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsTask(new DisposableResult("dummy")), "state"); + await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsValueTask(new DisposableResult("dummy")), "state"); var task = await context.TryWaitForCompletedExecutionAsync(TimeSpan.Zero); @@ -182,8 +182,8 @@ public async Task TryWaitForCompletedExecutionAsync_TwiceWhenSecondaryGeneratorN var context = Create(); context.Initialize(_resilienceContext); - await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsTask(new DisposableResult("dummy")), "state"); - await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsTask(new DisposableResult("dummy")), "state"); + await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsValueTask(new DisposableResult("dummy")), "state"); + await context.LoadExecutionAsync((_, _) => Outcome.FromResultAsValueTask(new DisposableResult("dummy")), "state"); var task = await context.TryWaitForCompletedExecutionAsync(TimeSpan.Zero); @@ -199,7 +199,7 @@ public async Task TryWaitForCompletedExecutionAsync_TwiceWhenSecondaryGeneratorR await LoadExecutionAsync(context); await LoadExecutionAsync(context); - Generator = args => () => Outcome.FromResultAsTask(new DisposableResult { Name = "secondary" }); + Generator = args => () => Outcome.FromResultAsValueTask(new DisposableResult { Name = "secondary" }); var task = await context.TryWaitForCompletedExecutionAsync(TimeSpan.Zero); task!.Type.Should().Be(HedgedTaskType.Primary); @@ -470,7 +470,7 @@ private void ConfigureSecondaryTasks(params TimeSpan[] delays) private Func<HedgingActionGeneratorArguments<DisposableResult>, Func<ValueTask<Outcome<DisposableResult>>>?> Generator { get; set; } = args => { - return () => Outcome.FromResultAsTask(new DisposableResult { Name = Handled }); + return () => Outcome.FromResultAsValueTask(new DisposableResult { Name = Handled }); }; private HedgingExecutionContext<DisposableResult> Create() diff --git a/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs b/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs index 760831a6b66..fa7ec8280c8 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs @@ -52,7 +52,7 @@ await execution.InitializeAsync(HedgedTaskType.Primary, _snapshot, { AssertPrimaryContext(context, execution); state.Should().Be("dummy-state"); - return Outcome.FromResultAsTask(new DisposableResult { Name = value }); + return Outcome.FromResultAsValueTask(new DisposableResult { Name = value }); }, "dummy-state", 99); @@ -91,7 +91,7 @@ public async Task Initialize_Secondary_Ok(string value, bool handled) { AssertSecondaryContext(args.ActionContext, execution); args.AttemptNumber.Should().Be(4); - return () => Outcome.FromResultAsTask(new DisposableResult { Name = value }); + return () => Outcome.FromResultAsValueTask(new DisposableResult { Name = value }); }; (await execution.InitializeAsync<string>(HedgedTaskType.Secondary, _snapshot, null!, "dummy-state", 4)).Should().BeTrue(); @@ -255,7 +255,7 @@ private async Task InitializePrimaryAsync(TaskExecution<DisposableResult> execut await execution.InitializeAsync(HedgedTaskType.Primary, _snapshot, (context, _) => { onContext?.Invoke(context); - return Outcome.FromResultAsTask(result ?? new DisposableResult { Name = Handled }); + return Outcome.FromResultAsValueTask(result ?? new DisposableResult { Name = Handled }); }, "dummy-state", 1); } @@ -296,7 +296,7 @@ private void CreateSnapshot(CancellationToken? token = null) private Func<HedgingActionGeneratorArguments<DisposableResult>, Func<ValueTask<Outcome<DisposableResult>>>?> Generator { get; set; } = args => { - return () => Outcome.FromResultAsTask(new DisposableResult { Name = Handled }); + return () => Outcome.FromResultAsValueTask(new DisposableResult { Name = Handled }); }; private TaskExecution<DisposableResult> Create() => new(_hedgingHandler, CancellationTokenSourcePool.Create(TimeProvider.System), _timeProvider, _telemetry); diff --git a/test/Polly.Core.Tests/Hedging/HedgingActionGeneratorArgumentsTests.cs b/test/Polly.Core.Tests/Hedging/HedgingActionGeneratorArgumentsTests.cs index 0c871989a16..8de0f80fd97 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingActionGeneratorArgumentsTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingActionGeneratorArgumentsTests.cs @@ -7,7 +7,7 @@ public class HedgingActionGeneratorArgumentsTests [Fact] public void Ctor_Ok() { - var args = new HedgingActionGeneratorArguments<string>(ResilienceContextPool.Shared.Get(), ResilienceContextPool.Shared.Get(), 5, _ => Outcome.FromResultAsTask("dummy")); + var args = new HedgingActionGeneratorArguments<string>(ResilienceContextPool.Shared.Get(), ResilienceContextPool.Shared.Get(), 5, _ => Outcome.FromResultAsValueTask("dummy")); args.PrimaryContext.Should().NotBeNull(); args.ActionContext.Should().NotBeNull(); diff --git a/test/Polly.Core.Tests/Hedging/HedgingHandlerTests.cs b/test/Polly.Core.Tests/Hedging/HedgingHandlerTests.cs index 45baab8fdc4..2f988c279b1 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingHandlerTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingHandlerTests.cs @@ -9,14 +9,14 @@ public class HedgingHandlerTests public async Task GenerateAction_Generic_Ok() { var handler = new HedgingHandler<string>( - args => PredicateResult.True, - args => () => Outcome.FromResultAsTask("ok")); + args => PredicateResult.True(), + args => () => Outcome.FromResultAsValueTask("ok")); var action = handler.GenerateAction(new HedgingActionGeneratorArguments<string>( ResilienceContextPool.Shared.Get(), ResilienceContextPool.Shared.Get(), 0, - _ => Outcome.FromResultAsTask("primary")))!; + _ => Outcome.FromResultAsValueTask("primary")))!; var res = await action(); res.Result.Should().Be("ok"); diff --git a/test/Polly.Core.Tests/Hedging/HedgingResiliencePipelineBuilderExtensionsTests.cs b/test/Polly.Core.Tests/Hedging/HedgingResiliencePipelineBuilderExtensionsTests.cs index bfa2f2b02e5..13e877146f2 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingResiliencePipelineBuilderExtensionsTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingResiliencePipelineBuilderExtensionsTests.cs @@ -14,8 +14,8 @@ public void AddHedging_Generic_Ok() { _builder.AddHedging(new HedgingStrategyOptions<string> { - ActionGenerator = args => () => Outcome.FromResultAsTask("dummy"), - ShouldHandle = _ => PredicateResult.True + ActionGenerator = args => () => Outcome.FromResultAsValueTask("dummy"), + ShouldHandle = _ => PredicateResult.True() }); _builder.Build().GetPipelineDescriptor().FirstStrategy.StrategyInstance @@ -45,8 +45,8 @@ public async Task AddHedging_IntegrationTest() Delay = TimeSpan.FromMilliseconds(20), ShouldHandle = args => args.Outcome.Result switch { - "error" => PredicateResult.True, - _ => PredicateResult.False + "error" => PredicateResult.True(), + _ => PredicateResult.False() }, ActionGenerator = args => { diff --git a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs index efc80efd2c9..82e757c0738 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs @@ -65,7 +65,7 @@ public async Task Execute_CancellationRequested_Throws() var context = ResilienceContextPool.Shared.Get(); context.CancellationToken = _cts.Token; - var outcome = await strategy.ExecuteCore((_, _) => Outcome.FromResultAsTask("dummy"), context, "state"); + var outcome = await strategy.ExecuteCore((_, _) => Outcome.FromResultAsValueTask("dummy"), context, "state"); outcome.Exception.Should().BeOfType<OperationCanceledException>(); outcome.Exception!.StackTrace.Should().Contain("Execute_CancellationRequested_Throws"); } @@ -80,7 +80,7 @@ public void ExecutePrimaryAndSecondary_EnsureAttemptReported() return timeStamp; }; _options.MaxHedgedAttempts = 2; - ConfigureHedging(_ => true, args => () => Outcome.FromResultAsTask("any")); + ConfigureHedging(_ => true, args => () => Outcome.FromResultAsValueTask("any")); var strategy = Create(); strategy.Execute(_ => "dummy"); @@ -101,7 +101,7 @@ public async Task ExecutePrimary_Cancelled_SecondaryShouldBeExecuted() { _options.MaxHedgedAttempts = 2; - ConfigureHedging(o => o.Result == "primary", args => () => Outcome.FromResultAsTask("secondary")); + ConfigureHedging(o => o.Result == "primary", args => () => Outcome.FromResultAsValueTask("secondary")); var strategy = Create(); var result = await strategy.ExecuteAsync( @@ -186,7 +186,7 @@ public async Task ExecuteAsync_EnsurePrimaryContextFlows() { args.PrimaryContext.Properties.GetValue(key, string.Empty).Should().Be("dummy"); args.PrimaryContext.Should().Be(primaryContext); - return () => Outcome.FromResultAsTask(Failure); + return () => Outcome.FromResultAsValueTask(Failure); }); var strategy = Create(); @@ -298,7 +298,7 @@ public async Task ExecuteAsync_EnsureSecondaryHedgedTaskReportedWithNoOutcome() return default; }; - ConfigureHedging(context => Outcome.FromResultAsTask(Success)); + ConfigureHedging(context => Outcome.FromResultAsValueTask(Success)); var strategy = Create(); @@ -326,7 +326,7 @@ public async Task ExecuteAsync_EnsureDiscardedResultDisposed() { return () => { - return Outcome.FromResultAsTask(secondaryResult); + return Outcome.FromResultAsValueTask(secondaryResult); }; }); @@ -530,7 +530,7 @@ public async Task ExecuteAsync_Secondary_CustomPropertiesAvailable() args.ActionContext.Properties.TryGetValue(key2, out var val).Should().BeTrue(); val.Should().Be("my-value-2"); args.ActionContext.Properties.Set(key, "my-value"); - return Outcome.FromResultAsTask(Success); + return Outcome.FromResultAsValueTask(Success); }; }); var strategy = Create(); @@ -549,7 +549,7 @@ public async Task ExecuteAsync_Secondary_CustomPropertiesAvailable() public async Task ExecuteAsync_OnHedgingEventThrows_EnsureExceptionRethrown() { // arrange - ConfigureHedging(args => () => Outcome.FromResultAsTask(Success)); + ConfigureHedging(args => () => Outcome.FromResultAsValueTask(Success)); _options.OnHedging = _ => throw new InvalidOperationException("my-exception"); var strategy = Create(); @@ -651,7 +651,7 @@ ValueTask<Outcome<string>> BackgroundWork(ResilienceContext resilienceContext) { var delay = Task.Delay(TimeSpan.FromDays(24), resilienceContext.CancellationToken); backgroundTasks.Add(delay); - return Outcome.FromResultAsTask(Success); + return Outcome.FromResultAsValueTask(Success); } } @@ -833,10 +833,10 @@ public async Task ExecuteAsync_ExceptionsHandled_ShouldReturnLastResult() { if (exception != null) { - return Outcome.FromExceptionAsTask<string>(exception); + return Outcome.FromExceptionAsValueTask<string>(exception); } - return Outcome.FromResultAsTask(Success); + return Outcome.FromResultAsValueTask(Success); }; }); @@ -851,7 +851,7 @@ public async Task ExecuteAsync_EnsureHedgingDelayGeneratorRespected() var delay = TimeSpan.FromMilliseconds(12345); _options.DelayGenerator = _ => new ValueTask<TimeSpan>(TimeSpan.FromMilliseconds(12345)); - ConfigureHedging(res => false, args => () => Outcome.FromResultAsTask(Success)); + ConfigureHedging(res => false, args => () => Outcome.FromResultAsValueTask(Success)); var strategy = Create(); var task = strategy.ExecuteAsync<string>(async token => @@ -892,7 +892,7 @@ public async Task ExecuteAsync_EnsureOnHedgingCalled() return default; }; - ConfigureHedging(res => res.Result == Failure, args => () => Outcome.FromResultAsTask(Failure)); + ConfigureHedging(res => res.Result == Failure, args => () => Outcome.FromResultAsValueTask(Failure)); var strategy = Create(); await strategy.ExecuteAsync(_ => new ValueTask<string>(Failure)); @@ -907,7 +907,7 @@ public async Task ExecuteAsync_EnsureOnHedgingTelemetry() { var context = ResilienceContextPool.Shared.Get(); - ConfigureHedging(res => res.Result == Failure, args => () => Outcome.FromResultAsTask(Failure)); + ConfigureHedging(res => res.Result == Failure, args => () => Outcome.FromResultAsValueTask(Failure)); var strategy = Create(); await strategy.ExecuteAsync((_, _) => new ValueTask<string>(Failure), context, "state"); diff --git a/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs b/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs index 2208428f689..51d02dcd240 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs @@ -39,7 +39,7 @@ public async Task HedgingActionGenerator_EnsureDefaults(bool synchronous) Thread.CurrentThread.ManagedThreadId.Should().Be(threadId); } - return Outcome.FromResultAsTask(99); + return Outcome.FromResultAsValueTask(99); }))!; action.Should().NotBeNull(); diff --git a/test/Polly.Core.Tests/Issues/IssuesTests.FlowingContext_849.cs b/test/Polly.Core.Tests/Issues/IssuesTests.FlowingContext_849.cs index 7b1a829e4db..55e39f54acd 100644 --- a/test/Polly.Core.Tests/Issues/IssuesTests.FlowingContext_849.cs +++ b/test/Polly.Core.Tests/Issues/IssuesTests.FlowingContext_849.cs @@ -18,7 +18,7 @@ public void FlowingContext_849() ResilienceContext context = args.Context; context.Should().NotBeNull(); contextChecked = true; - return PredicateResult.False; + return PredicateResult.False(); } }) .Build(); diff --git a/test/Polly.Core.Tests/Issues/IssuesTests.HandleMultipleResults_898.cs b/test/Polly.Core.Tests/Issues/IssuesTests.HandleMultipleResults_898.cs index 3065826d2e1..9dfc01af8b2 100644 --- a/test/Polly.Core.Tests/Issues/IssuesTests.HandleMultipleResults_898.cs +++ b/test/Polly.Core.Tests/Issues/IssuesTests.HandleMultipleResults_898.cs @@ -16,11 +16,11 @@ public void HandleMultipleResults_898() ShouldHandle = args => args.Outcome switch { // handle string results - { Result: string res } when res == "error" => PredicateResult.True, + { Result: string res } when res == "error" => PredicateResult.True(), // handle int results - { Result: int res } when res == -1 => PredicateResult.True, - _ => PredicateResult.False + { Result: int res } when res == -1 => PredicateResult.True(), + _ => PredicateResult.False() }, OnRetry = args => { diff --git a/test/Polly.Core.Tests/OutcomeTests.cs b/test/Polly.Core.Tests/OutcomeTests.cs index 4474a652b0a..42e2c1dfc02 100644 --- a/test/Polly.Core.Tests/OutcomeTests.cs +++ b/test/Polly.Core.Tests/OutcomeTests.cs @@ -50,7 +50,7 @@ public void EnsureSuccess_Result() { var outcome = Outcome.FromResult("dummy"); - outcome.Invoking(o => o.EnsureSuccess()).Should().NotThrow(); + outcome.Invoking(o => o.ThrowIfException()).Should().NotThrow(); } [Fact] @@ -58,6 +58,6 @@ public void EnsureSuccess_Exception() { var outcome = Outcome.FromException<string>(new InvalidOperationException()); - outcome.Invoking(o => o.EnsureSuccess()).Should().Throw<InvalidOperationException>(); + outcome.Invoking(o => o.ThrowIfException()).Should().Throw<InvalidOperationException>(); } } diff --git a/test/Polly.Core.Tests/PredicateResultTests.cs b/test/Polly.Core.Tests/PredicateResultTests.cs index f1a48c0cdca..a3a655fcc8d 100644 --- a/test/Polly.Core.Tests/PredicateResultTests.cs +++ b/test/Polly.Core.Tests/PredicateResultTests.cs @@ -5,12 +5,12 @@ public class PredicateResultTests [Fact] public async Task True_Ok() { - (await PredicateResult.True).Should().BeTrue(); + (await PredicateResult.True()).Should().BeTrue(); } [Fact] public async Task False_Ok() { - (await PredicateResult.False).Should().BeFalse(); + (await PredicateResult.False()).Should().BeFalse(); } } diff --git a/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs b/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs index 4968d635155..ea89af60a89 100644 --- a/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs +++ b/test/Polly.Core.Tests/Registry/ResiliencePipelineRegistryTests.cs @@ -268,7 +268,7 @@ public void EnableReloads_Ok(bool firstOne) builder.AddRetry(new RetryStrategyOptions { - ShouldHandle = _ => PredicateResult.True, + ShouldHandle = _ => PredicateResult.True(), MaxRetryAttempts = retryCount, Delay = TimeSpan.FromMilliseconds(2), }); @@ -344,7 +344,7 @@ public void EnableReloads_Generic_Ok() builder.AddRetry(new RetryStrategyOptions<string> { - ShouldHandle = _ => PredicateResult.True, + ShouldHandle = _ => PredicateResult.True(), MaxRetryAttempts = retryCount, Delay = TimeSpan.FromMilliseconds(2), }); diff --git a/test/Polly.Core.Tests/ResiliencePipelineTTests.Async.cs b/test/Polly.Core.Tests/ResiliencePipelineTTests.Async.cs index 27dcd6a46b9..333a4d22034 100644 --- a/test/Polly.Core.Tests/ResiliencePipelineTTests.Async.cs +++ b/test/Polly.Core.Tests/ResiliencePipelineTTests.Async.cs @@ -87,7 +87,7 @@ public async Task ExecuteOutcomeAsync_GenericStrategy_Ok() state.Should().Be("state"); context.IsSynchronous.Should().BeFalse(); context.ResultType.Should().Be(typeof(int)); - return Outcome.FromResultAsTask(12345); + return Outcome.FromResultAsValueTask(12345); }, ResilienceContextPool.Shared.Get(), "state"); diff --git a/test/Polly.Core.Tests/ResiliencePipelineTests.AsyncT.cs b/test/Polly.Core.Tests/ResiliencePipelineTests.AsyncT.cs index 1ae26be6741..99bf972b03c 100644 --- a/test/Polly.Core.Tests/ResiliencePipelineTests.AsyncT.cs +++ b/test/Polly.Core.Tests/ResiliencePipelineTests.AsyncT.cs @@ -122,7 +122,7 @@ public async Task ExecuteOutcomeAsync_Ok() state.Should().Be("state"); context.IsSynchronous.Should().BeFalse(); context.ResultType.Should().Be(typeof(int)); - return Outcome.FromResultAsTask(12345); + return Outcome.FromResultAsValueTask(12345); }, ResilienceContextPool.Shared.Get(), "state"); diff --git a/test/Polly.Core.Tests/Retry/RetryDelayGeneratorArgumentsTests.cs b/test/Polly.Core.Tests/Retry/RetryDelayGeneratorArgumentsTests.cs index f02558e023e..5fb9dee6276 100644 --- a/test/Polly.Core.Tests/Retry/RetryDelayGeneratorArgumentsTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryDelayGeneratorArgumentsTests.cs @@ -7,11 +7,10 @@ public class RetryDelayGeneratorArgumentsTests [Fact] public void Ctor_Ok() { - var args = new RetryDelayGeneratorArguments<int>(ResilienceContextPool.Shared.Get(), Outcome.FromResult(1), 2, TimeSpan.FromSeconds(2)); + var args = new RetryDelayGeneratorArguments<int>(ResilienceContextPool.Shared.Get(), Outcome.FromResult(1), 2); args.Context.Should().NotBeNull(); args.Outcome.Result.Should().Be(1); args.AttemptNumber.Should().Be(2); - args.DelayHint.Should().Be(TimeSpan.FromSeconds(2)); } } diff --git a/test/Polly.Core.Tests/Retry/RetryResiliencePipelineBuilderExtensionsTests.cs b/test/Polly.Core.Tests/Retry/RetryResiliencePipelineBuilderExtensionsTests.cs index 57a0010e371..f73886985ba 100644 --- a/test/Polly.Core.Tests/Retry/RetryResiliencePipelineBuilderExtensionsTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryResiliencePipelineBuilderExtensionsTests.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using NSubstitute; using Polly.Retry; using Polly.Testing; @@ -17,7 +18,7 @@ public class RetryResiliencePipelineBuilderExtensionsTests BackoffType = DelayBackoffType.Exponential, MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(2), - ShouldHandle = _ => PredicateResult.True, + ShouldHandle = _ => PredicateResult.True(), }); AssertStrategy(builder, DelayBackoffType.Exponential, 3, TimeSpan.FromSeconds(2)); @@ -33,7 +34,7 @@ public class RetryResiliencePipelineBuilderExtensionsTests BackoffType = DelayBackoffType.Exponential, MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(2), - ShouldHandle = _ => PredicateResult.True + ShouldHandle = _ => PredicateResult.True() }); AssertStrategy(builder, DelayBackoffType.Exponential, 3, TimeSpan.FromSeconds(2)); @@ -62,7 +63,7 @@ public void AddRetry_GenericOverloads_Ok(Action<ResiliencePipelineBuilder<int>> public void AddRetry_DefaultOptions_Ok() { var builder = new ResiliencePipelineBuilder(); - var options = new RetryStrategyOptions { ShouldHandle = _ => PredicateResult.True }; + var options = new RetryStrategyOptions { ShouldHandle = _ => PredicateResult.True() }; builder.AddRetry(options); @@ -131,19 +132,18 @@ private static TimeSpan GetAggregatedDelay<T>(RetryStrategyOptions<T> options) { var aggregatedDelay = TimeSpan.Zero; - var strategy = new ResiliencePipelineBuilder().AddRetry(new() + var strategy = new ResiliencePipelineBuilder { TimeProvider = new NoWaitingTimeProvider() }.AddRetry(new() { MaxRetryAttempts = options.MaxRetryAttempts, Delay = options.Delay, BackoffType = options.BackoffType, - ShouldHandle = _ => PredicateResult.True, // always retry until all retries are exhausted - DelayGenerator = args => + ShouldHandle = _ => PredicateResult.True(), // always retry until all retries are exhausted + OnRetry = args => { // the delay hint is calculated for this attempt by the retry strategy - aggregatedDelay += args.DelayHint; + aggregatedDelay += args.RetryDelay; - // return zero delay, so no waiting - return new ValueTask<TimeSpan>(TimeSpan.Zero); + return default; }, Randomizer = () => 1.0, }) @@ -154,4 +154,13 @@ private static TimeSpan GetAggregatedDelay<T>(RetryStrategyOptions<T> options) return aggregatedDelay; } + + private class NoWaitingTimeProvider : TimeProvider + { + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + callback(state); + return Substitute.For<ITimer>(); + } + } } diff --git a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs index 4f05e5b3dc6..3e209ffa5cf 100644 --- a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs @@ -40,7 +40,7 @@ public async Task ExecuteAsync_CancellationRequested_EnsureNotRetried() context.CancellationToken = cancellationToken.Token; var executed = false; - var result = await sut.ExecuteOutcomeAsync((_, _) => { executed = true; return Outcome.FromResultAsTask("dummy"); }, context, "state"); + var result = await sut.ExecuteOutcomeAsync((_, _) => { executed = true; return Outcome.FromResultAsValueTask("dummy"); }, context, "state"); result.Exception.Should().BeOfType<OperationCanceledException>(); executed.Should().BeFalse(); } @@ -50,7 +50,7 @@ public async Task ExecuteAsync_CancellationRequestedAfterCallback_EnsureNotRetri { using var cancellationToken = new CancellationTokenSource(); - _options.ShouldHandle = _ => PredicateResult.True; + _options.ShouldHandle = _ => PredicateResult.True(); _options.OnRetry = _ => { cancellationToken.Cancel(); @@ -62,7 +62,7 @@ public async Task ExecuteAsync_CancellationRequestedAfterCallback_EnsureNotRetri context.CancellationToken = cancellationToken.Token; var executed = false; - var result = await sut.ExecuteOutcomeAsync((_, _) => { executed = true; return Outcome.FromResultAsTask("dummy"); }, context, "state"); + var result = await sut.ExecuteOutcomeAsync((_, _) => { executed = true; return Outcome.FromResultAsValueTask("dummy"); }, context, "state"); result.Exception.Should().BeOfType<OperationCanceledException>(); executed.Should().BeTrue(); } @@ -73,7 +73,7 @@ public void ExecuteAsync_MultipleRetries_EnsureDiscardedResultsDisposed() // arrange _options.MaxRetryAttempts = 5; SetupNoDelay(); - _options.ShouldHandle = _ => PredicateResult.True; + _options.ShouldHandle = _ => PredicateResult.True(); var results = new List<DisposableResult>(); var sut = CreateSut(); @@ -137,7 +137,7 @@ public void RetryDelayGenerator_Respected() var generatedValues = 0; var delay = TimeSpan.FromMilliseconds(120); - _options.ShouldHandle = _ => PredicateResult.True; + _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Constant; @@ -150,7 +150,7 @@ public void RetryDelayGenerator_Respected() _options.DelayGenerator = _ => { generatedValues++; - return new ValueTask<TimeSpan>(delay); + return new ValueTask<TimeSpan?>(delay); }; CreateSut(TimeProvider.System).Execute<string>(_ => "dummy"); @@ -168,7 +168,7 @@ public async Task RetryDelayGenerator_ZeroDelay_NoTimeProviderCalls() var delay = TimeSpan.Zero; var provider = new ThrowingFakeTimeProvider(); - _options.ShouldHandle = _ => PredicateResult.True; + _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Constant; @@ -180,7 +180,7 @@ public async Task RetryDelayGenerator_ZeroDelay_NoTimeProviderCalls() _options.DelayGenerator = _ => { generatedValues++; - return new ValueTask<TimeSpan>(delay); + return new ValueTask<TimeSpan?>(delay); }; var sut = CreateSut(provider); @@ -213,7 +213,7 @@ public async void OnRetry_EnsureCorrectArguments() return default; }; - _options.ShouldHandle = args => PredicateResult.True; + _options.ShouldHandle = args => PredicateResult.True(); _options.MaxRetryAttempts = 3; _options.BackoffType = DelayBackoffType.Linear; @@ -243,7 +243,7 @@ public async Task OnRetry_EnsureExecutionTime() return default; }; - _options.ShouldHandle = _ => PredicateResult.True; + _options.ShouldHandle = _ => PredicateResult.True(); _options.MaxRetryAttempts = 1; _options.BackoffType = DelayBackoffType.Constant; _options.Delay = TimeSpan.Zero; @@ -307,12 +307,11 @@ public void RetryDelayGenerator_EnsureCorrectArguments() _options.DelayGenerator = args => { attempts.Add(args.AttemptNumber); - hints.Add(args.DelayHint); args.Outcome.Exception.Should().BeNull(); args.Outcome.Result.Should().Be(0); - return new ValueTask<TimeSpan>(TimeSpan.Zero); + return new ValueTask<TimeSpan?>(TimeSpan.Zero); }; _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); @@ -327,13 +326,33 @@ public void RetryDelayGenerator_EnsureCorrectArguments() attempts[0].Should().Be(0); attempts[1].Should().Be(1); attempts[2].Should().Be(2); + } + + [Fact] + public void RetryDelayGenerator_ReturnsNull_EnsureDefaultRetry() + { + var delays = new List<TimeSpan>(); + _options.DelayGenerator = args => new ValueTask<TimeSpan?>((TimeSpan?)null); + _options.OnRetry = args => + { + delays.Add(args.RetryDelay); + return default; + }; + _options.ShouldHandle = args => args.Outcome.ResultPredicateAsync(0); + _options.MaxRetryAttempts = 2; + _options.BackoffType = DelayBackoffType.Constant; + _options.Delay = TimeSpan.FromMilliseconds(2); + + var sut = CreateSut(TimeProvider.System); + + sut.Execute(() => 0); - hints[0].Should().Be(TimeSpan.FromSeconds(2)); - hints[1].Should().Be(TimeSpan.FromSeconds(4)); - hints[2].Should().Be(TimeSpan.FromSeconds(6)); + delays.Should().HaveCount(2); + delays[0].Should().Be(TimeSpan.FromMilliseconds(2)); + delays[1].Should().Be(TimeSpan.FromMilliseconds(2)); } - private void SetupNoDelay() => _options.DelayGenerator = _ => new ValueTask<TimeSpan>(TimeSpan.Zero); + private void SetupNoDelay() => _options.DelayGenerator = _ => new ValueTask<TimeSpan?>(TimeSpan.Zero); private async ValueTask<int> ExecuteAndAdvance(ResiliencePipeline<object> sut) { diff --git a/test/Polly.Core.Tests/Utils/Pipeline/CompositePipelineComponentTests.cs b/test/Polly.Core.Tests/Utils/Pipeline/CompositePipelineComponentTests.cs index 324952e67bc..77529774d78 100644 --- a/test/Polly.Core.Tests/Utils/Pipeline/CompositePipelineComponentTests.cs +++ b/test/Polly.Core.Tests/Utils/Pipeline/CompositePipelineComponentTests.cs @@ -50,7 +50,7 @@ public async Task Create_EnsureExceptionsNotWrapped() var pipeline = CreateSut(components); await pipeline - .Invoking(p => p.ExecuteCore((_, _) => Outcome.FromResultAsTask(10), ResilienceContextPool.Shared.Get(), "state").AsTask()) + .Invoking(p => p.ExecuteCore((_, _) => Outcome.FromResultAsValueTask(10), ResilienceContextPool.Shared.Get(), "state").AsTask()) .Should() .ThrowAsync<NotSupportedException>(); } @@ -90,7 +90,7 @@ public async Task Create_Cancelled_EnsureNoExecution() var context = ResilienceContextPool.Shared.Get(); context.CancellationToken = cancellation.Token; - var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsTask("result"), context, "state"); + var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("result"), context, "state"); result.Exception.Should().BeOfType<OperationCanceledException>(); } @@ -108,7 +108,7 @@ public async Task Create_CancelledLater_EnsureNoExecution() var context = ResilienceContextPool.Shared.Get(); context.CancellationToken = cancellation.Token; - var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsTask("result"), context, "state"); + var result = await pipeline.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("result"), context, "state"); result.Exception.Should().BeOfType<OperationCanceledException>(); executed.Should().BeTrue(); } diff --git a/test/Polly.Extensions.Tests/Issues/IssuesTests.OnCircuitBreakWithServiceProvider_796.cs b/test/Polly.Extensions.Tests/Issues/IssuesTests.OnCircuitBreakWithServiceProvider_796.cs index cf35ede2586..13cae165f7d 100644 --- a/test/Polly.Extensions.Tests/Issues/IssuesTests.OnCircuitBreakWithServiceProvider_796.cs +++ b/test/Polly.Extensions.Tests/Issues/IssuesTests.OnCircuitBreakWithServiceProvider_796.cs @@ -33,8 +33,8 @@ public async Task OnCircuitBreakWithServiceProvider_796() }, ShouldHandle = args => args.Outcome.Result switch { - string result when result == "error" => PredicateResult.True, - _ => PredicateResult.False + string result when result == "error" => PredicateResult.True(), + _ => PredicateResult.False() } }); }); diff --git a/test/Polly.Extensions.Tests/Issues/IssuesTests.OverrideLibraryStrategies_1072.cs b/test/Polly.Extensions.Tests/Issues/IssuesTests.OverrideLibraryStrategies_1072.cs index ccf216f19cc..cce6d52d275 100644 --- a/test/Polly.Extensions.Tests/Issues/IssuesTests.OverrideLibraryStrategies_1072.cs +++ b/test/Polly.Extensions.Tests/Issues/IssuesTests.OverrideLibraryStrategies_1072.cs @@ -23,9 +23,9 @@ public void OverrideLibraryStrategies_898(bool overrideStrategy) { ShouldHandle = args => args.Outcome.Exception switch { - InvalidOperationException => PredicateResult.True, - SocketException => PredicateResult.True, - _ => PredicateResult.False + InvalidOperationException => PredicateResult.True(), + SocketException => PredicateResult.True(), + _ => PredicateResult.False() }, Delay = TimeSpan.Zero })); @@ -68,8 +68,8 @@ private static void AddLibraryServices(IServiceCollection services) { ShouldHandle = args => args.Outcome.Exception switch { - InvalidOperationException => PredicateResult.True, - _ => PredicateResult.False + InvalidOperationException => PredicateResult.True(), + _ => PredicateResult.False() } })); } diff --git a/test/Polly.RateLimiting.Tests/RateLimiterResilienceStrategyTests.cs b/test/Polly.RateLimiting.Tests/RateLimiterResilienceStrategyTests.cs index e8380d1569e..7972e490734 100644 --- a/test/Polly.RateLimiting.Tests/RateLimiterResilienceStrategyTests.cs +++ b/test/Polly.RateLimiting.Tests/RateLimiterResilienceStrategyTests.cs @@ -70,7 +70,7 @@ public async Task Execute_LeaseRejected(bool hasEvents, bool hasRetryAfter) var strategy = Create(); var context = ResilienceContextPool.Shared.Get(cts.Token); - var outcome = await strategy.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsTask("dummy"), context, "state"); + var outcome = await strategy.ExecuteOutcomeAsync((_, _) => Outcome.FromResultAsValueTask("dummy"), context, "state"); outcome.Exception .Should() diff --git a/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs b/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs index eb5fe71be9e..f213e1f614c 100644 --- a/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs +++ b/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs @@ -152,7 +152,7 @@ public void RetryStrategy_AsSyncPolicy_Ok() var policy = new ResiliencePipelineBuilder<string>() .AddRetry(new RetryStrategyOptions<string> { - ShouldHandle = _ => PredicateResult.True, + ShouldHandle = _ => PredicateResult.True(), BackoffType = DelayBackoffType.Constant, MaxRetryAttempts = 5, Delay = TimeSpan.FromMilliseconds(1) diff --git a/test/Polly.Testing.Tests/ResiliencePipelineExtensionsTests.cs b/test/Polly.Testing.Tests/ResiliencePipelineExtensionsTests.cs index 2018ba08824..291329679b4 100644 --- a/test/Polly.Testing.Tests/ResiliencePipelineExtensionsTests.cs +++ b/test/Polly.Testing.Tests/ResiliencePipelineExtensionsTests.cs @@ -18,7 +18,7 @@ public void GetPipelineDescriptor_Generic_Ok() var strategy = new ResiliencePipelineBuilder<string>() .AddFallback(new() { - FallbackAction = _ => Outcome.FromResultAsTask("dummy"), + FallbackAction = _ => Outcome.FromResultAsValueTask("dummy"), }) .AddRetry(new()) .AddCircuitBreaker(new())
Finalize the V8 API We should finalize the V8 API: - Based on the alpha release feedback. - Address or close any comments in #1233
null
2023-08-30T14:23:27Z
0.2
[]
['Polly.Core.Tests.CircuitBreaker.BrokenCircuitExceptionTests.Ctor_Ok']
App-vNext/Polly
polly-1472
9674b6b2fee25db24e770ad5d9056be68ddbda73
diff --git a/Directory.Packages.props b/Directory.Packages.props index 3a5e431dfd0..ce5b24e4b09 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -22,7 +22,7 @@ <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> <PackageVersion Include="Microsoft.SourceLink.GitHub" Version="1.1.1" /> <PackageVersion Include="MinVer" Version="4.3.0" /> - <PackageVersion Include="Moq" Version="4.18.4" /> + <PackageVersion Include="NSubstitute" Version="5.0.0" /> <PackageVersion Include="Polly" Version="$(PollyVersion)" /> <PackageVersion Include="Polly.Core" Version="$(PollyVersion)" /> <PackageVersion Include="Polly.Extensions" Version="$(PollyVersion)" /> diff --git a/eng/Test.targets b/eng/Test.targets index 2c270eac370..a8baacb3403 100644 --- a/eng/Test.targets +++ b/eng/Test.targets @@ -15,7 +15,7 @@ <PackageReference Include="FluentAssertions" /> <PackageReference Include="GitHubActionsTestLogger" /> <PackageReference Include="Microsoft.NET.Test.Sdk" /> - <PackageReference Include="Moq" /> + <PackageReference Include="NSubstitute" /> <PackageReference Include="ReportGenerator" PrivateAssets="all" /> <PackageReference Include="xunit" /> <PackageReference Include="xunit.runner.visualstudio" PrivateAssets="all" />
null
Replace Moq Given recent developments with Moq as of version 4.20.0, we should remove it and replace with another library. [NSubstitue](https://nsubstitute.github.io/) seems like a good _substitue_. I'm going to work on this today unless someone has any strong opinions about an alternative library to use in its place.
Are there any plans to fork the Moq? Maybe in the meantime, we can freeze the versions and wait for some "official forked package". I have not used NSubstitute personally, so I can't comment on that. It seems some folks find it cleaner compared to Moq. If the switch is straightforward, we can get away with that. There is already an issue for creating a migration tool: https://github.com/nsubstitute/NSubstitute/issues/720 I would probably wait and see in this case, how it develops. The latest version of Moq no longer has that dependency, so I would say it's not immediate concern. Thanks for the link, I'll bear that in mind for the future. I have however just finished locally converting the code over 😅
2023-08-09T11:54:12Z
0.2
[]
['Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Execute_HandledException_OnFailureCalled', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Ctor_StateProvider_EnsureAttached', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Execute_UnhandledException_NoCalls', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Ctor_ManualControl_EnsureAttached', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Execute_HandledResult_OnFailureCalled', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Ctor_Ok', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Execute_UnhandledResult_OnActionSuccess', 'Polly.Core.Tests.CircuitBreaker.CircuitBreakerResilienceStrategyTests.Execute_Ok']
App-vNext/Polly
polly-1436
b38e6c43bd4647a6e34b4e636f62c674139a22f5
diff --git a/src/Polly.Extensions/Telemetry/Log.cs b/src/Polly.Extensions/Telemetry/Log.cs index 3ca6726db82..0765a6081cd 100644 --- a/src/Polly.Extensions/Telemetry/Log.cs +++ b/src/Polly.Extensions/Telemetry/Log.cs @@ -12,7 +12,7 @@ internal static partial class Log EventId = 0, Message = "Resilience event occurred. " + "EventName: '{EventName}', " + - "Source: '{BuilderName}[{BuilderInstance}]/{StrategyName}', " + + "Source: '{BuilderName}/{BuilderInstance}/{StrategyName}', " + "Operation Key: '{OperationKey}', " + "Result: '{Result}'", EventName = "ResilienceEvent")] @@ -20,8 +20,8 @@ public static partial void ResilienceEvent( this ILogger logger, LogLevel logLevel, string eventName, - string? builderName, - string? builderInstance, + string builderName, + string builderInstance, string? strategyName, string? operationKey, object? result, @@ -31,21 +31,21 @@ public static partial void ResilienceEvent( 1, LogLevel.Debug, "Resilience strategy executing. " + - "Source: '{BuilderName}[{BuilderInstance}]', " + + "Source: '{BuilderName}/{BuilderInstance}', " + "Operation Key: '{OperationKey}', " + "Result Type: '{ResultType}'", EventName = "StrategyExecuting")] public static partial void ExecutingStrategy( this ILogger logger, - string? builderName, - string? builderInstance, + string builderName, + string builderInstance, string? operationKey, string resultType); [LoggerMessage( EventId = 2, Message = "Resilience strategy executed. " + - "Source: '{BuilderName}[{BuilderInstance}]', " + + "Source: '{BuilderName}/{BuilderInstance}', " + "Operation Key: '{OperationKey}', " + "Result Type: '{ResultType}', " + "Result: '{Result}', " + @@ -55,8 +55,8 @@ public static partial void ExecutingStrategy( public static partial void StrategyExecuted( this ILogger logger, LogLevel logLevel, - string? builderName, - string? builderInstance, + string builderName, + string builderInstance, string? operationKey, string resultType, object? result, @@ -67,7 +67,7 @@ public static partial void StrategyExecuted( [LoggerMessage( EventId = 3, Message = "Execution attempt. " + - "Source: '{BuilderName}[{BuilderInstance}]/{StrategyName}', " + + "Source: '{BuilderName}/{BuilderInstance}/{StrategyName}', " + "Operation Key: '{OperationKey}', " + "Result: '{Result}', " + "Handled: '{Handled}', " + @@ -78,9 +78,9 @@ public static partial void StrategyExecuted( public static partial void ExecutionAttempt( this ILogger logger, LogLevel level, - string? builderName, - string? builderInstance, - string? strategyName, + string builderName, + string builderInstance, + string strategyName, string? operationKey, object? result, bool handled, diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs index b33b45a1f01..5965a1b9ef1 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs @@ -115,9 +115,9 @@ private void LogEvent(TelemetryEventArguments args) Log.ExecutionAttempt( _logger, level, - args.Source.BuilderName, - args.Source.BuilderInstanceName, - args.Source.StrategyName, + args.Source.BuilderName.GetValueOrPlaceholder(), + args.Source.BuilderInstanceName.GetValueOrPlaceholder(), + args.Source.StrategyName.GetValueOrPlaceholder(), args.Context.OperationKey, result, executionAttempt.Handled, @@ -132,9 +132,9 @@ private void LogEvent(TelemetryEventArguments args) _logger, level, args.Event.EventName, - args.Source.BuilderName, - args.Source.BuilderInstanceName, - args.Source.StrategyName, + args.Source.BuilderName.GetValueOrPlaceholder(), + args.Source.BuilderInstanceName.GetValueOrPlaceholder(), + args.Source.StrategyName.GetValueOrPlaceholder(), args.Context.OperationKey, result, args.Outcome?.Exception); diff --git a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs index 3cac7fc2bb8..0fc6f8d3ca9 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs @@ -6,8 +6,8 @@ namespace Polly.Extensions.Telemetry; internal sealed class TelemetryResilienceStrategy : ResilienceStrategy { private readonly TimeProvider _timeProvider; - private readonly string? _builderName; - private readonly string? _builderInstance; + private readonly string _builderName; + private readonly string _builderInstance; private readonly List<Action<EnrichmentContext>> _enrichers; private readonly ILogger _logger; private readonly Func<ResilienceContext, object?, object?> _resultFormatter; @@ -32,8 +32,8 @@ public TelemetryResilienceStrategy( List<Action<EnrichmentContext>> enrichers) { _timeProvider = timeProvider; - _builderName = builderName; - _builderInstance = builderInstance; + _builderName = builderName.GetValueOrPlaceholder(); + _builderInstance = builderInstance.GetValueOrPlaceholder(); _resultFormatter = resultFormatter; _enrichers = enrichers; _logger = loggerFactory.CreateLogger(TelemetryUtil.PollyDiagnosticSource); diff --git a/src/Polly.Extensions/Telemetry/TelemetryUtil.cs b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs index 167a628a0a3..0c53049adf1 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryUtil.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs @@ -15,6 +15,8 @@ internal static class TelemetryUtil internal const string PollyDiagnosticSource = "Polly"; + public static string GetValueOrPlaceholder(this string? value) => value ?? "(null)"; + public static object AsBoxedBool(this bool value) => value switch { true => True,
diff --git a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs index 111da9d94dd..5df7c1bd9d3 100644 --- a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs @@ -72,11 +72,11 @@ public void WriteEvent_LoggingWithOutcome_Ok(bool noOutcome) if (noOutcome) { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: ''"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: ''"); } else { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: '200'"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: '200'"); } } @@ -99,11 +99,11 @@ public void WriteEvent_LoggingWithException_Ok(bool noOutcome) if (noOutcome) { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: ''"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: ''"); } else { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: 'Dummy message.'"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: 'Dummy message.'"); } } @@ -115,7 +115,7 @@ public void WriteEvent_LoggingWithoutInstanceName_Ok() var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList(); - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder[]/my-strategy', Operation Key: 'op-key', Result: ''"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Source: 'my-builder/(null)/my-strategy', Operation Key: 'op-key', Result: ''"); } [InlineData(ResilienceEventSeverity.Error, LogLevel.Error)] @@ -150,7 +150,7 @@ public void WriteExecutionAttempt_LoggingWithException_Ok() var messages = _logger.GetRecords(new EventId(3, "ExecutionAttempt")).ToList(); messages.Should().HaveCount(1); - messages[0].Message.Should().Be("Execution attempt. Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: 'Dummy message.', Handled: 'True', Attempt: '4', Execution Time: '123'"); + messages[0].Message.Should().Be("Execution attempt. Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: 'Dummy message.', Handled: 'True', Attempt: '4', Execution Time: '123'"); } [InlineData(true, true)] @@ -170,11 +170,11 @@ public void WriteExecutionAttempt_LoggingWithOutcome_Ok(bool noOutcome, bool han if (noOutcome) { string resultString = string.Empty; - messages[0].Message.Should().Be($"Execution attempt. Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: '{resultString}', Handled: '{handled}', Attempt: '4', Execution Time: '123'"); + messages[0].Message.Should().Be($"Execution attempt. Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: '{resultString}', Handled: '{handled}', Attempt: '4', Execution Time: '123'"); } else { - messages[0].Message.Should().Be($"Execution attempt. Source: 'my-builder[builder-instance]/my-strategy', Operation Key: 'op-key', Result: '200', Handled: '{handled}', Attempt: '4', Execution Time: '123'"); + messages[0].Message.Should().Be($"Execution attempt. Source: 'my-builder/builder-instance/my-strategy', Operation Key: 'op-key', Result: '200', Handled: '{handled}', Attempt: '4', Execution Time: '123'"); } messages[0].LogLevel.Should().Be(LogLevel.Warning); diff --git a/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs b/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs index f268075abb4..1f83d8c6095 100644 --- a/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs @@ -50,10 +50,10 @@ public void Execute_EnsureLogged(bool healthy) var messages = _logger.GetRecords(new EventId(1, "StrategyExecuting")).ToList(); messages.Should().HaveCount(1); - messages[0].Message.Should().Be("Resilience strategy executing. Source: 'my-builder[my-instance]', Operation Key: 'op-key', Result Type: 'void'"); + messages[0].Message.Should().Be("Resilience strategy executing. Source: 'my-builder/my-instance', Operation Key: 'op-key', Result Type: 'void'"); messages = _logger.GetRecords(new EventId(2, "StrategyExecuted")).ToList(); messages.Should().HaveCount(1); - messages[0].Message.Should().Match($"Resilience strategy executed. Source: 'my-builder[my-instance]', Operation Key: 'op-key', Result Type: 'void', Result: 'void', Execution Health: '{healthString}', Execution Time: *ms"); + messages[0].Message.Should().Match($"Resilience strategy executed. Source: 'my-builder/my-instance', Operation Key: 'op-key', Result Type: 'void', Result: 'void', Execution Health: '{healthString}', Execution Time: *ms"); messages[0].LogLevel.Should().Be(healthy ? LogLevel.Debug : LogLevel.Warning); // verify reported state @@ -78,11 +78,11 @@ public void Execute_WithException_EnsureLogged() var messages = _logger.GetRecords(new EventId(1, "StrategyExecuting")).ToList(); messages.Should().HaveCount(1); - messages[0].Message.Should().Be("Resilience strategy executing. Source: 'my-builder[my-instance]', Operation Key: 'op-key', Result Type: 'void'"); + messages[0].Message.Should().Be("Resilience strategy executing. Source: 'my-builder/my-instance', Operation Key: 'op-key', Result Type: 'void'"); messages = _logger.GetRecords(new EventId(2, "StrategyExecuted")).ToList(); messages.Should().HaveCount(1); - messages[0].Message.Should().Match($"Resilience strategy executed. Source: 'my-builder[my-instance]', Operation Key: 'op-key', Result Type: 'void', Result: 'Dummy message.', Execution Health: 'Healthy', Execution Time: *ms"); + messages[0].Message.Should().Match($"Resilience strategy executed. Source: 'my-builder/my-instance', Operation Key: 'op-key', Result Type: 'void', Result: 'Dummy message.', Execution Health: 'Healthy', Execution Time: *ms"); messages[0].Exception.Should().BeOfType<InvalidOperationException>(); } diff --git a/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs b/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs index 23ea7f45c3c..328f9f83431 100644 --- a/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs +++ b/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs @@ -25,4 +25,11 @@ public void AsBoxedInt_Ok() (-1).AsBoxedInt().Should().NotBeSameAs((-1).AsBoxedInt()); 100.AsBoxedInt().Should().NotBeSameAs(100.AsBoxedInt()); } + + [Fact] + public void GetValueOrPlaceholder_Ok() + { + TelemetryUtil.GetValueOrPlaceholder("dummy").Should().Be("dummy"); + TelemetryUtil.GetValueOrPlaceholder(null).Should().Be("(null)"); + } }
Confusing log entries when builder instance name not set Using Polly 8.0.0-alpha.7 where a builder has no name set, slightly confusing log messages are emitted. Messages are emitted with empty pairs of square brackets (e.g. `Retry[]`) which look like arrays, but aren't, and it isn't clear what they signify. For example. ``` [2023-07-26 11:14:11Z] info: Polly[3] Execution attempt. Source: 'Test/Retry[]/Test/Retry', Operation Key: 'Test.ExecuteAsync', Result: '42', Handled: 'False', Attempt: '1', Execution Time: '0.0991' [2023-07-26 11:14:11Z] warn: Polly[2] Resilience strategy executed. Source: 'Test/Retry[]', Operation Key: 'Test.ExecuteAsync', Result Type: 'Int32', Result: '42', Execution Health: 'Unhealthy', Execution Time: 115.0517ms [2023-07-26 11:14:11Z] warn: Polly[2] Resilience strategy executed. Source: 'Test/CircuitBreaker/ExecuteAsync[]', Operation Key: 'Test.ExecuteAsync', Result Type: 'Int32', Result: '42', Execution Health: 'Unhealthy', Execution Time: 117.2939ms [2023-07-26 11:14:11Z] warn: Polly[2] Resilience strategy executed. Source: 'Test/Timeout[]', Operation Key: 'Test.ExecuteAsync', Result Type: 'Int32', Result: '42', Execution Health: 'Unhealthy', Execution Time: 119.5119ms [2023-07-26 11:14:11Z] warn: Polly[2] Resilience strategy executed. Source: 'Test/RateLimit[]', Operation Key: 'Test.ExecuteAsync', Result Type: 'Int32', Result: '42', Execution Health: 'Unhealthy', Execution Time: 119.5671ms [2023-07-26 11:14:11Z] warn: Polly[2] Resilience strategy executed. Source: 'Test/ExecuteAsync[]', Operation Key: 'Test.ExecuteAsync', Result Type: 'Int32', Result: '42', Execution Health: 'Unhealthy', Execution Time: 119.5794ms ``` The log messages are being emitted from here: https://github.com/App-vNext/Polly/blob/b38e6c43bd4647a6e34b4e636f62c674139a22f5/src/Polly.Extensions/Telemetry/Log.cs#L11-L28 When elements of the log message are null, should be maybe replace them with a constant like `(unset)` or similar? Or should we change the format of the source to emit empty parts and be constructed in code behind an `IsEnabled(LogLevel)` check then just passed to the template as `'{Source}'`?
> When elements of the log message are null, should be maybe replace them with a constant like (unset) or similar? Possibly or just use the common `(null)` marker. `(null)[(null)]/MyStrategy` or maybe use `/(null)/(null)/MyStrategy` format. Wdyt? > Or should we change the format of the source to emit empty parts and be constructed in code behind an IsEnabled(LogLevel) check then just passed to the template as '{Source}'? When structured logging is used it's nice to have to filter only based on builder, instance or strategy. Merging everything into source limits that scenario. I'm happy enough with `(null)` in the rendered template. Yeah, maybe it's better to just go with all slashes rather than introduce the `[]` pairs?
2023-07-26T12:23:15Z
0.2
[]
['Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_LoggingWithoutInstanceName_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.Meter_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_MeteringWithoutEnrichers_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.OnTelemetryEvent_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteExecutionAttempt_NotEnabled_EnsureNotLogged', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.IsEnabled_true', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteExecutionAttempt_LoggingWithException_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteExecutionAttempt_LoggingWithOutcome_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteExecutionAttemptEvent_Metering_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_MeteringWithEnrichers_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_MeteringWithoutBuilderInstance_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_EnsureSeverityRespected', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_LoggingWithOutcome_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.WriteEvent_LoggingWithException_Ok', 'Polly.Extensions.Tests.Telemetry.ResilienceTelemetryDiagnosticSourceTests.Write_InvalidType_Nothing']
App-vNext/Polly
polly-1361
190f096a8b7094dd387fba93ec0826c187baa4d8
diff --git a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs index ab0e2048f24..fcd217b220c 100644 --- a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs @@ -78,7 +78,7 @@ protected override ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState> ResilienceContext context, TState state) { - _telemetry.Report("DummyEvent", context, "dummy-args"); + _telemetry.Report(new ResilienceEvent(ResilienceEventSeverity.Warning, "DummyEvent"), context, "dummy-args"); return callback(context, state); } } diff --git a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs index 3414d238f80..553cc7dc04b 100644 --- a/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs +++ b/src/Polly.Core/CircuitBreaker/Controller/CircuitStateController.cs @@ -128,7 +128,7 @@ public ValueTask CloseCircuitAsync(ResilienceContext context) if (_circuitState == CircuitState.Open && PermitHalfOpenCircuitTest_NeedsLock()) { _circuitState = CircuitState.HalfOpen; - _telemetry.Report(CircuitBreakerConstants.OnHalfOpenEvent, context, new OnCircuitHalfOpenedArguments()); + _telemetry.Report(new(ResilienceEventSeverity.Warning, CircuitBreakerConstants.OnHalfOpenEvent), context, new OnCircuitHalfOpenedArguments()); isHalfOpen = true; } @@ -269,7 +269,7 @@ private void CloseCircuit_NeedsLock(Outcome<T> outcome, bool manual, ResilienceC if (priorState != CircuitState.Closed) { var args = new OutcomeArguments<T, OnCircuitClosedArguments>(context, outcome, new OnCircuitClosedArguments(manual)); - _telemetry.Report(CircuitBreakerConstants.OnCircuitClosed, args); + _telemetry.Report(new(ResilienceEventSeverity.Information, CircuitBreakerConstants.OnCircuitClosed), args); if (_onClosed is not null) { @@ -320,7 +320,7 @@ private void OpenCircuitFor_NeedsLock(Outcome<T> outcome, TimeSpan breakDuration _circuitState = CircuitState.Open; var args = new OutcomeArguments<T, OnCircuitOpenedArguments>(context, outcome, new OnCircuitOpenedArguments(breakDuration, manual)); - _telemetry.Report(CircuitBreakerConstants.OnCircuitOpened, args); + _telemetry.Report(new(ResilienceEventSeverity.Error, CircuitBreakerConstants.OnCircuitOpened), args); if (_onOpened is not null) { diff --git a/src/Polly.Core/Fallback/FallbackResilienceStrategy.cs b/src/Polly.Core/Fallback/FallbackResilienceStrategy.cs index fd6db6966e3..f0939511d0d 100644 --- a/src/Polly.Core/Fallback/FallbackResilienceStrategy.cs +++ b/src/Polly.Core/Fallback/FallbackResilienceStrategy.cs @@ -29,7 +29,7 @@ protected override async ValueTask<Outcome<T>> ExecuteCallbackAsync<TState>(Func var onFallbackArgs = new OutcomeArguments<T, OnFallbackArguments>(context, outcome, new OnFallbackArguments()); - _telemetry.Report(FallbackConstants.OnFallback, onFallbackArgs); + _telemetry.Report(new(ResilienceEventSeverity.Warning, FallbackConstants.OnFallback), onFallbackArgs); if (_onFallback is not null) { diff --git a/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs b/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs index d96e0197d90..1034031ae64 100644 --- a/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs +++ b/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs @@ -126,7 +126,7 @@ private async ValueTask HandleOnHedgingAsync(ResilienceContext context, Outcome< outcome, args); - _telemetry.Report(HedgingConstants.OnHedgingEventName, onHedgingArgs); + _telemetry.Report(new(ResilienceEventSeverity.Warning, HedgingConstants.OnHedgingEventName), onHedgingArgs); if (OnHedging is not null) { diff --git a/src/Polly.Core/ResilienceContext.cs b/src/Polly.Core/ResilienceContext.cs index 4cdde32d1e9..5ada98899c9 100644 --- a/src/Polly.Core/ResilienceContext.cs +++ b/src/Polly.Core/ResilienceContext.cs @@ -64,7 +64,7 @@ private ResilienceContext() /// <remarks> /// If the number of resilience events is greater than zero it's an indication that the execution was unhealthy. /// </remarks> - public IReadOnlyCollection<ResilienceEvent> ResilienceEvents => _resilienceEvents; + public IReadOnlyList<ResilienceEvent> ResilienceEvents => _resilienceEvents; /// <summary> /// Gets a <see cref="ResilienceContext"/> instance from the pool. diff --git a/src/Polly.Core/Retry/RetryResilienceStrategy.cs b/src/Polly.Core/Retry/RetryResilienceStrategy.cs index a633dcb6fe0..9a6da5108ed 100644 --- a/src/Polly.Core/Retry/RetryResilienceStrategy.cs +++ b/src/Polly.Core/Retry/RetryResilienceStrategy.cs @@ -74,7 +74,7 @@ protected override async ValueTask<Outcome<T>> ExecuteCallbackAsync<TState>(Func } var onRetryArgs = new OutcomeArguments<T, OnRetryArguments>(context, outcome, new OnRetryArguments(attempt, delay, executionTime)); - _telemetry.Report(RetryConstants.OnRetryEvent, onRetryArgs); + _telemetry.Report(new(ResilienceEventSeverity.Warning, RetryConstants.OnRetryEvent), onRetryArgs); if (OnRetry is not null) { diff --git a/src/Polly.Core/Telemetry/ResilienceEvent.cs b/src/Polly.Core/Telemetry/ResilienceEvent.cs index be87dca76ac..fdc4710bc43 100644 --- a/src/Polly.Core/Telemetry/ResilienceEvent.cs +++ b/src/Polly.Core/Telemetry/ResilienceEvent.cs @@ -3,11 +3,12 @@ namespace Polly.Telemetry; /// <summary> /// Represents a resilience event that has been reported. /// </summary> +/// <param name="Severity">The severity of the event.</param> /// <param name="EventName">The event name.</param> /// <remarks> /// Always use the constructor when creating this struct, otherwise we do not guarantee binary compatibility. /// </remarks> -public readonly record struct ResilienceEvent(string EventName) +public readonly record struct ResilienceEvent(ResilienceEventSeverity Severity, string EventName) { /// <summary> /// Returns an <see cref="EventName"/>. diff --git a/src/Polly.Core/Telemetry/ResilienceEventSeverity.cs b/src/Polly.Core/Telemetry/ResilienceEventSeverity.cs new file mode 100644 index 00000000000..31607d60184 --- /dev/null +++ b/src/Polly.Core/Telemetry/ResilienceEventSeverity.cs @@ -0,0 +1,37 @@ +namespace Polly.Telemetry; + +/// <summary> +/// The severity of reported resilience event. +/// </summary> +public enum ResilienceEventSeverity +{ + /// <summary> + /// The resilience event is not recorded. + /// </summary> + None = 0, + + /// <summary> + /// The resilience event is used for debugging purposes only. + /// </summary> + Debug, + + /// <summary> + /// The resilience event is informational. + /// </summary> + Information, + + /// <summary> + /// The resilience event should be treated as a warning. + /// </summary> + Warning, + + /// <summary> + /// The resilience event should be treated as an error. + /// </summary> + Error, + + /// <summary> + /// The resilience event should be treated as a critical error. + /// </summary> + Critical, +} diff --git a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs index 100fc9073a2..9062ac77c87 100644 --- a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs +++ b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs @@ -27,25 +27,24 @@ internal ResilienceStrategyTelemetry(ResilienceTelemetrySource source, Diagnosti /// Reports an event that occurred in a resilience strategy. /// </summary> /// <typeparam name="TArgs">The arguments associated with this event.</typeparam> - /// <param name="eventName">The event name.</param> + /// <param name="resilienceEvent">The reported resilience event.</param> /// <param name="context">The resilience context associated with this event.</param> /// <param name="args">The event arguments.</param> - /// <exception cref="ArgumentNullException">Thrown when <paramref name="eventName"/> is <see langword="null"/>.</exception> - public void Report<TArgs>(string eventName, ResilienceContext context, TArgs args) + /// <exception cref="ArgumentNullException">Thrown when <paramref name="context"/> is <see langword="null"/>.</exception> + public void Report<TArgs>(ResilienceEvent resilienceEvent, ResilienceContext context, TArgs args) { - Guard.NotNull(eventName); Guard.NotNull(context); - AddResilienceEvent(eventName, context, args); + context.AddResilienceEvent(resilienceEvent); - if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(eventName)) + if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(resilienceEvent.EventName) || resilienceEvent.Severity == ResilienceEventSeverity.None) { return; } - var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, eventName, context, null, args!); + var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, resilienceEvent, context, null, args!); - DiagnosticSource.Write(eventName, telemetryArgs); + DiagnosticSource.Write(resilienceEvent.EventName, telemetryArgs); TelemetryEventArguments.Return(telemetryArgs); } @@ -55,37 +54,22 @@ public void Report<TArgs>(string eventName, ResilienceContext context, TArgs arg /// </summary> /// <typeparam name="TArgs">The arguments associated with this event.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> - /// <param name="eventName">The event name.</param> + /// <param name="resilienceEvent">The reported resilience event.</param> /// <param name="args">The event arguments.</param> - /// <exception cref="ArgumentNullException">Thrown when <paramref name="eventName"/> is <see langword="null"/>.</exception> - public void Report<TArgs, TResult>(string eventName, OutcomeArguments<TResult, TArgs> args) + public void Report<TArgs, TResult>(ResilienceEvent resilienceEvent, OutcomeArguments<TResult, TArgs> args) { - Guard.NotNull(eventName); + args.Context.AddResilienceEvent(resilienceEvent); - AddResilienceEvent(eventName, args.Context, args.Arguments); - - if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(eventName)) + if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(resilienceEvent.EventName) || resilienceEvent.Severity == ResilienceEventSeverity.None) { return; } - var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, eventName, args.Context, args.Outcome.AsOutcome(), args.Arguments!); + var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, resilienceEvent, args.Context, args.Outcome.AsOutcome(), args.Arguments!); - DiagnosticSource.Write(eventName, telemetryArgs); + DiagnosticSource.Write(resilienceEvent.EventName, telemetryArgs); TelemetryEventArguments.Return(telemetryArgs); } - - private static void AddResilienceEvent<TArgs>(string eventName, ResilienceContext context, TArgs args) - { - // ExecutionAttemptArguments is not reported as resilience event because that information is already contained - // in OnHedgingArguments and OnRetryArguments - if (args is ExecutionAttemptArguments attempt) - { - return; - } - - context.AddResilienceEvent(new ResilienceEvent(eventName)); - } } diff --git a/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs b/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs index 9d701004ecb..d115c9468ca 100644 --- a/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs +++ b/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs @@ -5,7 +5,7 @@ public sealed partial record class TelemetryEventArguments private static readonly ObjectPool<TelemetryEventArguments> Pool = new(() => new TelemetryEventArguments(), args => { args.Source = null!; - args.EventName = null!; + args.Event = default; args.Context = null!; args.Outcome = default; args.Arguments = null!; @@ -13,7 +13,7 @@ public sealed partial record class TelemetryEventArguments internal static TelemetryEventArguments Get( ResilienceTelemetrySource source, - string eventName, + ResilienceEvent resilienceEvent, ResilienceContext context, Outcome<object>? outcome, object arguments) @@ -21,7 +21,7 @@ internal static TelemetryEventArguments Get( var args = Pool.Get(); args.Source = source; - args.EventName = eventName; + args.Event = resilienceEvent; args.Context = context; args.Outcome = outcome; args.Arguments = arguments; diff --git a/src/Polly.Core/Telemetry/TelemetryEventArguments.cs b/src/Polly.Core/Telemetry/TelemetryEventArguments.cs index 1c98f3145f2..d3c66c51aae 100644 --- a/src/Polly.Core/Telemetry/TelemetryEventArguments.cs +++ b/src/Polly.Core/Telemetry/TelemetryEventArguments.cs @@ -18,9 +18,9 @@ private TelemetryEventArguments() public ResilienceTelemetrySource Source { get; private set; } = null!; /// <summary> - /// Gets the event name. + /// Gets the event. /// </summary> - public string EventName { get; private set; } = null!; + public ResilienceEvent Event { get; private set; } /// <summary> /// Gets the resilience context. diff --git a/src/Polly.Core/Telemetry/TelemetryUtil.cs b/src/Polly.Core/Telemetry/TelemetryUtil.cs index 7486edd855f..f2afd372dec 100644 --- a/src/Polly.Core/Telemetry/TelemetryUtil.cs +++ b/src/Polly.Core/Telemetry/TelemetryUtil.cs @@ -34,7 +34,9 @@ public static void ReportExecutionAttempt<TResult>( } var attemptArgs = ExecutionAttemptArguments.Get(attempt, executionTime, handled); - telemetry.Report<ExecutionAttemptArguments, TResult>(ExecutionAttempt, new(context, outcome, attemptArgs)); + telemetry.Report<ExecutionAttemptArguments, TResult>( + new(handled ? ResilienceEventSeverity.Warning : ResilienceEventSeverity.Information, ExecutionAttempt), + new(context, outcome, attemptArgs)); ExecutionAttemptArguments.Return(attemptArgs); } } diff --git a/src/Polly.Core/Timeout/TimeoutResilienceStrategy.cs b/src/Polly.Core/Timeout/TimeoutResilienceStrategy.cs index af3fb43a627..cfcf4e67327 100644 --- a/src/Polly.Core/Timeout/TimeoutResilienceStrategy.cs +++ b/src/Polly.Core/Timeout/TimeoutResilienceStrategy.cs @@ -60,7 +60,7 @@ protected internal override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<T if (isCancellationRequested && outcome.Exception is OperationCanceledException e && !previousToken.IsCancellationRequested) { var args = new OnTimeoutArguments(context, e, timeout); - _telemetry.Report(TimeoutConstants.OnTimeoutEvent, context, args); + _telemetry.Report(new(ResilienceEventSeverity.Error, TimeoutConstants.OnTimeoutEvent), context, args); if (OnTimeout is not null) { diff --git a/src/Polly.Core/Utils/ReloadableResilienceStrategy.cs b/src/Polly.Core/Utils/ReloadableResilienceStrategy.cs index 14d4c57ac8a..74ae6f8eba3 100644 --- a/src/Polly.Core/Utils/ReloadableResilienceStrategy.cs +++ b/src/Polly.Core/Utils/ReloadableResilienceStrategy.cs @@ -10,6 +10,8 @@ internal sealed class ReloadableResilienceStrategy : ResilienceStrategy public const string ReloadFailedEvent = "ReloadFailed"; + public const string OnReloadEvent = "OnReload"; + private readonly Func<CancellationToken> _onReload; private readonly Func<ResilienceStrategy> _resilienceStrategyFactory; private readonly ResilienceStrategyTelemetry _telemetry; @@ -50,16 +52,18 @@ private void RegisterOnReload(CancellationToken previousToken) _registration = token.Register(() => { + var context = ResilienceContext.Get().Initialize<VoidResult>(isSynchronous: true); + #pragma warning disable CA1031 // Do not catch general exception types try { + _telemetry.Report(new(ResilienceEventSeverity.Information, OnReloadEvent), context, new OnReloadArguments()); Strategy = _resilienceStrategyFactory(); } catch (Exception e) { - var context = ResilienceContext.Get().Initialize<VoidResult>(isSynchronous: true); var args = new OutcomeArguments<VoidResult, ReloadFailedArguments>(context, Outcome.FromException(e), new ReloadFailedArguments(e)); - _telemetry.Report(ReloadFailedEvent, args); + _telemetry.Report(new(ResilienceEventSeverity.Error, ReloadFailedEvent), args); ResilienceContext.Return(context); } #pragma warning restore CA1031 // Do not catch general exception types @@ -70,4 +74,6 @@ private void RegisterOnReload(CancellationToken previousToken) } internal readonly record struct ReloadFailedArguments(Exception Exception); + + internal readonly record struct OnReloadArguments(); } diff --git a/src/Polly.Extensions/Telemetry/Log.cs b/src/Polly.Extensions/Telemetry/Log.cs index c249b71b708..c68896994a6 100644 --- a/src/Polly.Extensions/Telemetry/Log.cs +++ b/src/Polly.Extensions/Telemetry/Log.cs @@ -1,45 +1,26 @@ +using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Logging; namespace Polly.Extensions.Telemetry; #pragma warning disable S107 // Methods should not have too many parameters +[ExcludeFromCodeCoverage] internal static partial class Log { - private const string StrategyExecutedMessage = "Resilience strategy executed. " + - "Builder Name: '{BuilderName}', " + - "Strategy Key: '{StrategyKey}', " + - "Result Type: '{ResultType}', " + - "Result: '{Result}', " + - "Execution Health: '{ExecutionHealth}', " + - "Execution Time: {ExecutionTime}ms"; - - private const string ResilienceEventMessage = "Resilience event occurred. " + + [LoggerMessage( + EventId = 0, + Message = "Resilience event occurred. " + "EventName: '{EventName}', " + "Builder Name: '{BuilderName}', " + "Strategy Name: '{StrategyName}', " + "Strategy Type: '{StrategyType}', " + "Strategy Key: '{StrategyKey}', " + - "Result: '{Result}'"; - - private const string ExecutionAttemptMessage = "Execution attempt. " + - "Builder Name: '{BuilderName}', " + - "Strategy Name: '{StrategyName}', " + - "Strategy Type: '{StrategyType}', " + - "Strategy Key: '{StrategyKey}', " + - "Result: '{Result}', " + - "Handled: '{Handled}', " + - "Attempt: '{Attempt}', " + - "Execution Time: '{ExecutionTimeMs}'"; - - private const string StrategyExecutingMessage = "Resilience strategy executing. " + - "Builder Name: '{BuilderName}', " + - "Strategy Key: '{StrategyKey}', " + - "Result Type: '{ResultType}'"; - - [LoggerMessage(0, LogLevel.Warning, ResilienceEventMessage, EventName = "ResilienceEvent")] + "Result: '{Result}'", + EventName = "ResilienceEvent")] public static partial void ResilienceEvent( this ILogger logger, + LogLevel logLevel, string eventName, string? builderName, string? strategyName, @@ -48,14 +29,30 @@ public static partial void ResilienceEvent( object? result, Exception? exception); - [LoggerMessage(1, LogLevel.Debug, StrategyExecutingMessage, EventName = "StrategyExecuting")] + [LoggerMessage( + 1, + LogLevel.Debug, + "Resilience strategy executing. " + + "Builder Name: '{BuilderName}', " + + "Strategy Key: '{StrategyKey}', " + + "Result Type: '{ResultType}'", + EventName = "StrategyExecuting")] public static partial void ExecutingStrategy( this ILogger logger, string? builderName, string? strategyKey, string resultType); - [LoggerMessage(EventId = 2, Message = StrategyExecutedMessage, EventName = "StrategyExecuted")] + [LoggerMessage( + EventId = 2, + Message = "Resilience strategy executed. " + + "Builder Name: '{BuilderName}', " + + "Strategy Key: '{StrategyKey}', " + + "Result Type: '{ResultType}', " + + "Result: '{Result}', " + + "Execution Health: '{ExecutionHealth}', " + + "Execution Time: {ExecutionTime}ms", + EventName = "StrategyExecuted")] public static partial void StrategyExecuted( this ILogger logger, LogLevel logLevel, @@ -67,7 +64,19 @@ public static partial void StrategyExecuted( double executionTime, Exception? exception); - [LoggerMessage(EventId = 3, Message = ExecutionAttemptMessage, EventName = "ExecutionAttempt", SkipEnabledCheck = true)] + [LoggerMessage( + EventId = 3, + Message = "Execution attempt. " + + "Builder Name: '{BuilderName}', " + + "Strategy Name: '{StrategyName}', " + + "Strategy Type: '{StrategyType}', " + + "Strategy Key: '{StrategyKey}', " + + "Result: '{Result}', " + + "Handled: '{Handled}', " + + "Attempt: '{Attempt}', " + + "Execution Time: '{ExecutionTimeMs}'", + EventName = "ExecutionAttempt", + SkipEnabledCheck = true)] public static partial void ExecutionAttempt( this ILogger logger, LogLevel level, diff --git a/src/Polly.Extensions/Telemetry/ResilienceContextExtensions.cs b/src/Polly.Extensions/Telemetry/ResilienceContextExtensions.cs index 87df8f617c0..58b15866c96 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceContextExtensions.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceContextExtensions.cs @@ -8,5 +8,16 @@ internal static class ResilienceContextExtensions public static string GetExecutionHealth(this ResilienceContext context) => context.IsExecutionHealthy() ? "Healthy" : "Unhealthy"; - public static bool IsExecutionHealthy(this ResilienceContext context) => context.ResilienceEvents.Count == 0; + public static bool IsExecutionHealthy(this ResilienceContext context) + { + for (int i = 0; i < context.ResilienceEvents.Count; i++) + { + if (context.ResilienceEvents[i].Severity > Polly.Telemetry.ResilienceEventSeverity.Information) + { + return false; + } + } + + return true; + } } diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs index df7452dcbe7..8c9540826f5 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs @@ -47,7 +47,8 @@ public override void Write(string name, object? value) private static void AddCommonTags(TelemetryEventArguments args, ResilienceTelemetrySource source, EnrichmentContext enrichmentContext) { - enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.EventName, args.EventName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.EventName, args.Event.EventName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.EventSeverity, args.Event.Severity.AsString())); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.BuilderName, source.BuilderName)); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyName, source.StrategyName)); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyType, source.StrategyType)); @@ -98,10 +99,10 @@ private void LogEvent(TelemetryEventArguments args) result = e.Message; } + var level = args.Event.Severity.AsLogLevel(); + if (args.Arguments is ExecutionAttemptArguments executionAttempt) { - var level = executionAttempt.Handled ? LogLevel.Warning : LogLevel.Debug; - if (_logger.IsEnabled(level)) { Log.ExecutionAttempt( @@ -120,7 +121,7 @@ private void LogEvent(TelemetryEventArguments args) } else { - Log.ResilienceEvent(_logger, args.EventName, args.Source.BuilderName, args.Source.StrategyName, args.Source.StrategyType, strategyKey, result, args.Outcome?.Exception); + Log.ResilienceEvent(_logger, level, args.Event.EventName, args.Source.BuilderName, args.Source.StrategyName, args.Source.StrategyType, strategyKey, result, args.Outcome?.Exception); } } } diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs index bbfbae10b50..0bf298bf67f 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs @@ -4,6 +4,8 @@ internal class ResilienceTelemetryTags { public const string EventName = "event-name"; + public const string EventSeverity = "event-severity"; + public const string BuilderName = "builder-name"; public const string StrategyName = "strategy-name"; @@ -21,4 +23,5 @@ internal class ResilienceTelemetryTags public const string AttemptNumber = "attempt-number"; public const string AttemptHandled = "attempt-handled"; + } diff --git a/src/Polly.Extensions/Telemetry/TelemetryUtil.cs b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs index bf07a06b0f6..c04a37efee7 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryUtil.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.Logging; +using Polly.Telemetry; + namespace Polly.Extensions.Telemetry; internal static class TelemetryUtil @@ -25,4 +28,25 @@ internal static class TelemetryUtil >= 0 and < MaxIntegers => Integers[value], _ => value, }; + + public static LogLevel AsLogLevel(this ResilienceEventSeverity severity) => severity switch + { + ResilienceEventSeverity.Debug => LogLevel.Debug, + ResilienceEventSeverity.Information => LogLevel.Information, + ResilienceEventSeverity.Warning => LogLevel.Warning, + ResilienceEventSeverity.Error => LogLevel.Error, + ResilienceEventSeverity.Critical => LogLevel.Critical, + _ => LogLevel.None, + }; + + public static string AsString(this ResilienceEventSeverity severity) => severity switch + { + ResilienceEventSeverity.None => nameof(ResilienceEventSeverity.None), + ResilienceEventSeverity.Debug => nameof(ResilienceEventSeverity.Debug), + ResilienceEventSeverity.Information => nameof(ResilienceEventSeverity.Information), + ResilienceEventSeverity.Warning => nameof(ResilienceEventSeverity.Warning), + ResilienceEventSeverity.Error => nameof(ResilienceEventSeverity.Error), + ResilienceEventSeverity.Critical => nameof(ResilienceEventSeverity.Critical), + _ => severity.ToString(), + }; } diff --git a/src/Polly.RateLimiting/RateLimiterResilienceStrategy.cs b/src/Polly.RateLimiting/RateLimiterResilienceStrategy.cs index 4e35648d823..3a284d12864 100644 --- a/src/Polly.RateLimiting/RateLimiterResilienceStrategy.cs +++ b/src/Polly.RateLimiting/RateLimiterResilienceStrategy.cs @@ -44,7 +44,7 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, T } var args = new OnRateLimiterRejectedArguments(context, lease, retryAfter); - _telemetry.Report(RateLimiterConstants.OnRateLimiterRejectedEvent, context, args); + _telemetry.Report(new(ResilienceEventSeverity.Error, RateLimiterConstants.OnRateLimiterRejectedEvent), context, args); if (OnLeaseRejected != null) {
diff --git a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs index b91f2fb830b..65460d9b9e6 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/Controller/CircuitStateControllerTests.cs @@ -59,7 +59,7 @@ public async Task IsolateAsync_Ok() _circuitBehavior.Setup(v => v.OnCircuitClosed()); await controller.CloseCircuitAsync(ResilienceContext.Get()); await controller.OnActionPreExecuteAsync(ResilienceContext.Get()); - context.ResilienceEvents.Should().Contain(new ResilienceEvent("OnCircuitOpened")); + context.ResilienceEvents.Should().Contain(new ResilienceEvent(ResilienceEventSeverity.Error, "OnCircuitOpened")); } [Fact] @@ -93,7 +93,7 @@ public async Task BreakAsync_Ok() await controller.OnActionPreExecuteAsync(ResilienceContext.Get()); _circuitBehavior.VerifyAll(); - context.ResilienceEvents.Should().Contain(new ResilienceEvent("OnCircuitClosed")); + context.ResilienceEvents.Should().Contain(new ResilienceEvent(ResilienceEventSeverity.Information, "OnCircuitClosed")); } [Fact] diff --git a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs index 08bc56967e6..437c3c1bec5 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs @@ -316,12 +316,12 @@ public async Task Complete_EnsureOriginalContextPreparedWithAcceptedOutcome(bool if (primary) { _resilienceContext.Properties.Should().HaveCount(1); - _resilienceContext.ResilienceEvents.Should().HaveCount(0); + _resilienceContext.ResilienceEvents.Should().HaveCount(1); } else { _resilienceContext.Properties.Should().HaveCount(2); - _resilienceContext.ResilienceEvents.Should().HaveCount(1); + _resilienceContext.ResilienceEvents.Should().HaveCount(4); } } @@ -456,7 +456,7 @@ private void ConfigureSecondaryTasks(params TimeSpan[] delays) return null; } - args.ActionContext.AddResilienceEvent(new ResilienceEvent("dummy-event")); + args.ActionContext.AddResilienceEvent(new ResilienceEvent(ResilienceEventSeverity.Information, "dummy-event")); return async () => { diff --git a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs index c3ef4868e90..ec17aae0205 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs @@ -915,8 +915,8 @@ public async Task ExecuteAsync_EnsureOnHedgingTelemetry() var strategy = Create(); await strategy.ExecuteAsync((_, _) => new ValueTask<string>(Failure), context, "state"); - context.ResilienceEvents.Should().HaveCount(_options.MaxHedgedAttempts); - context.ResilienceEvents.Select(v => v.EventName).Distinct().Should().ContainSingle("OnHedging"); + context.ResilienceEvents.Should().HaveCount(_options.MaxHedgedAttempts + 1); + context.ResilienceEvents.Select(v => v.EventName).Distinct().Should().HaveCount(2); } private void ConfigureHedging() diff --git a/test/Polly.Core.Tests/ResilienceContextTests.cs b/test/Polly.Core.Tests/ResilienceContextTests.cs index 8bf243a2003..67e28939fad 100644 --- a/test/Polly.Core.Tests/ResilienceContextTests.cs +++ b/test/Polly.Core.Tests/ResilienceContextTests.cs @@ -42,10 +42,10 @@ public void AddResilienceEvent_Ok() { var context = ResilienceContext.Get(); - context.AddResilienceEvent(new ResilienceEvent("Dummy")); + context.AddResilienceEvent(new ResilienceEvent(ResilienceEventSeverity.Information, "Dummy")); context.ResilienceEvents.Should().HaveCount(1); - context.ResilienceEvents.Should().Contain(new ResilienceEvent("Dummy")); + context.ResilienceEvents.Should().Contain(new ResilienceEvent(ResilienceEventSeverity.Information, "Dummy")); } [Fact] @@ -59,7 +59,7 @@ await TestUtilities.AssertWithTimeoutAsync(() => context.Initialize<bool>(true); context.CancellationToken.Should().Be(cts.Token); context.Properties.Set(new ResiliencePropertyKey<int>("abc"), 10); - context.AddResilienceEvent(new ResilienceEvent("dummy")); + context.AddResilienceEvent(new ResilienceEvent(ResilienceEventSeverity.Information, "dummy")); ResilienceContext.Return(context); AssertDefaults(context); diff --git a/test/Polly.Core.Tests/Telemetry/ResilienceEventTests.cs b/test/Polly.Core.Tests/Telemetry/ResilienceEventTests.cs index bfbf9a02e4f..e7ea2db478f 100644 --- a/test/Polly.Core.Tests/Telemetry/ResilienceEventTests.cs +++ b/test/Polly.Core.Tests/Telemetry/ResilienceEventTests.cs @@ -7,16 +7,19 @@ public class ResilienceEventTests [Fact] public void Ctor_Ok() { - var ev = new ResilienceEvent("A"); + var ev = new ResilienceEvent(ResilienceEventSeverity.Warning, "A"); ev.ToString().Should().Be("A"); + ev.Severity.Should().Be(ResilienceEventSeverity.Warning); + } [Fact] public void Equality_Ok() { - (new ResilienceEvent("A") == new ResilienceEvent("A")).Should().BeTrue(); - (new ResilienceEvent("A") != new ResilienceEvent("A")).Should().BeFalse(); - (new ResilienceEvent("A") == new ResilienceEvent("B")).Should().BeFalse(); + (new ResilienceEvent(ResilienceEventSeverity.Warning, "A") == new ResilienceEvent(ResilienceEventSeverity.Warning, "A")).Should().BeTrue(); + (new ResilienceEvent(ResilienceEventSeverity.Warning, "A") != new ResilienceEvent(ResilienceEventSeverity.Warning, "A")).Should().BeFalse(); + (new ResilienceEvent(ResilienceEventSeverity.Warning, "A") == new ResilienceEvent(ResilienceEventSeverity.Warning, "B")).Should().BeFalse(); + (new ResilienceEvent(ResilienceEventSeverity.Information, "A") == new ResilienceEvent(ResilienceEventSeverity.Warning, "A")).Should().BeFalse(); } } diff --git a/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs b/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs index ee53c762c14..743a6d3a1cd 100644 --- a/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs +++ b/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs @@ -22,38 +22,28 @@ public void Report_NoOutcome_OK() obj.Should().BeOfType<TelemetryEventArguments>(); var args = (TelemetryEventArguments)obj; - args.EventName.Should().Be("dummy-event"); + args.Event.EventName.Should().Be("dummy-event"); + args.Event.Severity.Should().Be(ResilienceEventSeverity.Warning); args.Outcome.Should().BeNull(); args.Source.StrategyName.Should().Be("strategy-name"); args.Source.StrategyType.Should().Be("strategy-type"); args.Source.BuilderProperties.Should().NotBeNull(); args.Arguments.Should().BeOfType<TestArguments>(); - args.EventName.Should().Be("dummy-event"); args.Outcome.Should().BeNull(); args.Context.Should().NotBeNull(); }); - _sut.Report("dummy-event", ResilienceContext.Get(), new TestArguments()); + _sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), ResilienceContext.Get(), new TestArguments()); _diagnosticSource.VerifyAll(); } - [Fact] - public void Report_Attempt_EnsureNotRecordedOnResilienceContext() - { - var context = ResilienceContext.Get(); - _diagnosticSource.Setup(o => o.IsEnabled("dummy-event")).Returns(false); - _sut.Report("dummy-event", context, ExecutionAttemptArguments.Get(0, TimeSpan.Zero, true)); - - context.ResilienceEvents.Should().BeEmpty(); - } - [Fact] public void Report_NoOutcomeWhenNotSubscribed_None() { _diagnosticSource.Setup(o => o.IsEnabled("dummy-event")).Returns(false); - _sut.Report("dummy-event", ResilienceContext.Get(), new TestArguments()); + _sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), ResilienceContext.Get(), new TestArguments()); _diagnosticSource.VerifyAll(); _diagnosticSource.VerifyNoOtherCalls(); @@ -66,8 +56,8 @@ public void ResilienceStrategyTelemetry_NoDiagnosticSource_Ok() var sut = new ResilienceStrategyTelemetry(source, null); var context = ResilienceContext.Get(); - sut.Invoking(s => s.Report("dummy", context, new TestArguments())).Should().NotThrow(); - sut.Invoking(s => s.Report("dummy", new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(1), new TestArguments()))).Should().NotThrow(); + sut.Invoking(s => s.Report(new(ResilienceEventSeverity.Warning, "dummy"), context, new TestArguments())).Should().NotThrow(); + sut.Invoking(s => s.Report(new(ResilienceEventSeverity.Warning, "dummy"), new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(1), new TestArguments()))).Should().NotThrow(); } [Fact] @@ -81,29 +71,42 @@ public void Report_Outcome_OK() obj.Should().BeOfType<TelemetryEventArguments>(); var args = (TelemetryEventArguments)obj; - args.EventName.Should().Be("dummy-event"); + args.Event.EventName.Should().Be("dummy-event"); + args.Event.Severity.Should().Be(ResilienceEventSeverity.Warning); args.Source.StrategyName.Should().Be("strategy-name"); args.Source.StrategyType.Should().Be("strategy-type"); args.Source.BuilderProperties.Should().NotBeNull(); args.Arguments.Should().BeOfType<TestArguments>(); - args.EventName.Should().Be("dummy-event"); args.Outcome.Should().NotBeNull(); args.Outcome!.Value.Result.Should().Be(99); args.Context.Should().NotBeNull(); }); var context = ResilienceContext.Get(); - _sut.Report("dummy-event", new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(99), new TestArguments())); + _sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(99), new TestArguments())); _diagnosticSource.VerifyAll(); } + [Fact] + public void Report_SeverityNone_Skipped() + { + _diagnosticSource.Setup(o => o.IsEnabled("dummy-event")).Returns(true); + + var context = ResilienceContext.Get(); + _sut.Report(new(ResilienceEventSeverity.None, "dummy-event"), new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(99), new TestArguments())); + _sut.Report(new(ResilienceEventSeverity.None, "dummy-event"), ResilienceContext.Get(), new TestArguments()); + + _diagnosticSource.VerifyAll(); + _diagnosticSource.VerifyNoOtherCalls(); + } + [Fact] public void Report_OutcomeWhenNotSubscribed_None() { _diagnosticSource.Setup(o => o.IsEnabled("dummy-event")).Returns(false); var context = ResilienceContext.Get(); - _sut.Report("dummy-event", new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(10), new TestArguments())); + _sut.Report(new(ResilienceEventSeverity.Warning, "dummy-event"), new OutcomeArguments<int, TestArguments>(context, Outcome.FromResult(10), new TestArguments())); _diagnosticSource.VerifyAll(); _diagnosticSource.VerifyNoOtherCalls(); diff --git a/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs b/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs index e2e870dd196..710546db6ef 100644 --- a/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs +++ b/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs @@ -10,11 +10,12 @@ public class TelemetryEventArgumentsTests public void Get_Ok() { var context = ResilienceContext.Get(); - var args = TelemetryEventArguments.Get(_source, "ev", context, Outcome.FromResult<object>("dummy"), "arg"); + var args = TelemetryEventArguments.Get(_source, new ResilienceEvent(ResilienceEventSeverity.Warning, "ev"), context, Outcome.FromResult<object>("dummy"), "arg"); args.Outcome!.Value.Result.Should().Be("dummy"); args.Context.Should().Be(context); - args.EventName.Should().Be("ev"); + args.Event.EventName.Should().Be("ev"); + args.Event.Severity.Should().Be(ResilienceEventSeverity.Warning); args.Source.Should().Be(_source); args.Arguments.Should().BeEquivalentTo("arg"); args.Context.Should().Be(context); @@ -24,7 +25,7 @@ public void Get_Ok() public void Return_EnsurePropertiesCleared() { var context = ResilienceContext.Get(); - var args = TelemetryEventArguments.Get(_source, "ev", context, Outcome.FromResult<object>("dummy"), "arg"); + var args = TelemetryEventArguments.Get(_source, new ResilienceEvent(ResilienceEventSeverity.Warning, "ev"), context, Outcome.FromResult<object>("dummy"), "arg"); TelemetryEventArguments.Return(args); @@ -32,7 +33,7 @@ public void Return_EnsurePropertiesCleared() { args.Outcome.Should().BeNull(); args.Context.Should().BeNull(); - args.EventName.Should().BeNull(); + args.Event.EventName.Should().BeNullOrEmpty(); args.Source.Should().BeNull(); args.Arguments.Should().BeNull(); args.Context.Should().BeNull(); diff --git a/test/Polly.Core.Tests/Utils/ReloadableResilienceStrategyTests.cs b/test/Polly.Core.Tests/Utils/ReloadableResilienceStrategyTests.cs index de4fa05067c..bd6b8f881c7 100644 --- a/test/Polly.Core.Tests/Utils/ReloadableResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Utils/ReloadableResilienceStrategyTests.cs @@ -49,7 +49,8 @@ public void ChangeTriggered_StrategyReloaded() sut.Strategy.Should().NotBe(strategy); } - _events.Should().HaveCount(0); + _events.Where(e => e.Event.EventName == "ReloadFailed").Should().HaveCount(0); + _events.Where(e => e.Event.EventName == "OnReload").Should().HaveCount(10); } [Fact] @@ -61,8 +62,14 @@ public void ChangeTriggered_FactoryError_LastStrategyUsedAndErrorReported() _cancellationTokenSource.Cancel(); sut.Strategy.Should().Be(strategy); - _events.Should().HaveCount(1); - var args = _events[0] + _events.Should().HaveCount(2); + + _events[0] + .Arguments + .Should() + .BeOfType<ReloadableResilienceStrategy.OnReloadArguments>(); + + var args = _events[1] .Arguments .Should() .BeOfType<ReloadableResilienceStrategy.ReloadFailedArguments>() diff --git a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs index 54e30e5f294..1142e3ed357 100644 --- a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs @@ -71,7 +71,7 @@ public void WriteEvent_LoggingWithOutcome_Ok(bool noOutcome) if (noOutcome) { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Result: '(null)'"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Result: ''"); } else { @@ -98,7 +98,7 @@ public void WriteEvent_LoggingWithException_Ok(bool noOutcome) if (noOutcome) { - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Result: '(null)'"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Result: ''"); } else { @@ -114,7 +114,29 @@ public void WriteEvent_LoggingWithoutStrategyKey_Ok() var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList(); - messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: '(null)', Result: '(null)'"); + messages[0].Message.Should().Be("Resilience event occurred. EventName: 'my-event', Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: '', Result: ''"); + } + + [InlineData(ResilienceEventSeverity.Error, LogLevel.Error)] + [InlineData(ResilienceEventSeverity.Warning, LogLevel.Warning)] + [InlineData(ResilienceEventSeverity.Information, LogLevel.Information)] + [InlineData(ResilienceEventSeverity.Debug, LogLevel.Debug)] + [InlineData(ResilienceEventSeverity.Critical, LogLevel.Critical)] + [InlineData(ResilienceEventSeverity.None, LogLevel.None)] + [InlineData((ResilienceEventSeverity)99, LogLevel.None)] + [Theory] + public void WriteEvent_EnsureSeverityRespected(ResilienceEventSeverity severity, LogLevel logLevel) + { + var telemetry = Create(); + ReportEvent(telemetry, null, severity: severity); + + var messages = _logger.GetRecords(new EventId(0, "ResilienceEvent")).ToList(); + + messages[0].LogLevel.Should().Be(logLevel); + + var events = GetEvents("resilience-events"); + events.Should().HaveCount(1); + var ev = events[0]["event-severity"].Should().Be(severity.ToString()); } [Fact] @@ -154,30 +176,7 @@ public void WriteExecutionAttempt_LoggingWithOutcome_Ok(bool noOutcome, bool han messages[0].Message.Should().Be($"Execution attempt. Builder Name: 'my-builder', Strategy Name: 'my-strategy', Strategy Type: 'my-strategy-type', Strategy Key: 'my-strategy-key', Result: '200', Handled: '{handled}', Attempt: '4', Execution Time: '123'"); } - if (handled) - { - messages[0].LogLevel.Should().Be(LogLevel.Warning); - } - else - { - messages[0].LogLevel.Should().Be(LogLevel.Debug); - } - - // verify reported state - var coll = messages[0].State.Should().BeAssignableTo<IReadOnlyList<KeyValuePair<string, object>>>().Subject; - coll.Count.Should().Be(9); - coll.AsEnumerable().Should().HaveCount(9); - (coll as IEnumerable).GetEnumerator().Should().NotBeNull(); - - for (int i = 0; i < coll.Count; i++) - { - if (!noOutcome) - { - coll[i].Value.Should().NotBeNull(); - } - } - - coll.Invoking(c => c[coll.Count + 1]).Should().Throw<IndexOutOfRangeException>(); + messages[0].LogLevel.Should().Be(LogLevel.Warning); } [Fact] @@ -212,8 +211,9 @@ public void WriteEvent_MeteringWithoutEnrichers_Ok(bool noOutcome, bool exceptio events.Should().HaveCount(1); var ev = events[0]; - ev.Count.Should().Be(7); + ev.Count.Should().Be(8); ev["event-name"].Should().Be("my-event"); + ev["event-severity"].Should().Be("Warning"); ev["strategy-type"].Should().Be("my-strategy-type"); ev["strategy-name"].Should().Be("my-strategy"); ev["strategy-key"].Should().Be("my-strategy-key"); @@ -251,8 +251,9 @@ public void WriteExecutionAttemptEvent_Metering_Ok(bool noOutcome, bool exceptio events.Should().HaveCount(1); var ev = events[0]; - ev.Count.Should().Be(9); + ev.Count.Should().Be(10); ev["event-name"].Should().Be("my-event"); + ev["event-severity"].Should().Be("Warning"); ev["strategy-type"].Should().Be("my-strategy-type"); ev["strategy-name"].Should().Be("my-strategy"); ev["strategy-key"].Should().Be("my-strategy-key"); @@ -299,7 +300,7 @@ public void WriteEvent_MeteringWithEnrichers_Ok(int count) var events = GetEvents("resilience-events"); var ev = events[0]; - ev.Count.Should().Be(DefaultDimensions + count + 1); + ev.Count.Should().Be(DefaultDimensions + count + 2); ev["other"].Should().Be("other-value"); for (int i = 0; i < count; i++) @@ -335,7 +336,8 @@ private static void ReportEvent( Outcome<object>? outcome, string? strategyKey = "my-strategy-key", ResilienceContext? context = null, - object? arg = null) + object? arg = null, + ResilienceEventSeverity severity = ResilienceEventSeverity.Warning) { context ??= ResilienceContext.Get(); var props = new ResilienceProperties(); @@ -345,7 +347,7 @@ private static void ReportEvent( } telemetry.ReportEvent( - "my-event", + new ResilienceEvent(severity, "my-event"), "my-builder", props, "my-strategy", diff --git a/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs b/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs index a20e4a15e86..18360068078 100644 --- a/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/TelemetryResilienceStrategyTests.cs @@ -43,7 +43,7 @@ public void Execute_EnsureLogged(bool healthy) { if (!healthy) { - ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent("dummy")); + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Warning, "dummy")); } }, ResilienceContext.Get(), string.Empty); @@ -154,7 +154,7 @@ public void Execute_WithResult_EnsureMetered(bool healthy) { if (!healthy) { - ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent("dummy")); + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Warning, "dummy")); } return true; @@ -179,6 +179,42 @@ public void Execute_WithResult_EnsureMetered(bool healthy) } } + [InlineData(true)] + [InlineData(false)] + [Theory] + public void Execute_ExecutionHealth(bool healthy) + { + var strategy = CreateStrategy(); + strategy.Execute( + (c, _) => + { + if (healthy) + { + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Information, "dummy")); + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Information, "dummy")); + } + else + { + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Information, "dummy")); + ((List<ResilienceEvent>)c.ResilienceEvents).Add(new ResilienceEvent(ResilienceEventSeverity.Warning, "dummy")); + } + + return true; + }, + ResilienceContext.Get(), string.Empty); + + var ev = _events.Single(v => v.Name == "strategy-execution-duration").Tags; + + if (healthy) + { + ev["execution-health"].Should().Be("Healthy"); + } + else + { + ev["execution-health"].Should().Be("Unhealthy"); + } + } + private TelemetryResilienceStrategy CreateStrategy() => new("my-builder", "my-key", _loggerFactory, (_, r) => r, new List<Action<EnrichmentContext>> { c => _enricher?.Invoke(c) }); public void Dispose() diff --git a/test/Polly.TestUtils/TestUtilities.cs b/test/Polly.TestUtils/TestUtilities.cs index 097de46aabd..b4e5aa7fbd0 100644 --- a/test/Polly.TestUtils/TestUtilities.cs +++ b/test/Polly.TestUtils/TestUtilities.cs @@ -78,7 +78,7 @@ void OnMeasurementRecorded<T>(Instrument instrument, T measurement, ReadOnlySpan #pragma warning disable S107 // Methods should not have too many parameters public static void ReportEvent( this DiagnosticSource source, - string eventName, + ResilienceEvent resilienceEvent, string builderName, ResilienceProperties builderProperties, string strategyName, @@ -88,9 +88,9 @@ public static void ReportEvent( object arguments) #pragma warning restore S107 // Methods should not have too many parameters { - source.Write(eventName, TelemetryEventArguments.Get( + source.Write(resilienceEvent.EventName, TelemetryEventArguments.Get( new ResilienceTelemetrySource(builderName, builderProperties, strategyName, strategyType), - eventName, + resilienceEvent, context, outcome, arguments)); @@ -122,7 +122,7 @@ public override void Write(string name, object? value) } // copy the args because these are pooled and in tests we want to preserve them - args = TelemetryEventArguments.Get(args.Source, args.EventName, args.Context, args.Outcome, arguments); + args = TelemetryEventArguments.Get(args.Source, args.Event, args.Context, args.Outcome, arguments); lock (_syncRoot) {
Expand the `ResilienceEvent` with the `Severity` This allows us to report `Informational` events and use the common-infra. Changes: - Add/Modify methods on `ResilienceStrategyTelemetry` to accept the serverity. - Make sure that `TelemetryResilienceStrategy` strategy reports unhealthy status only for events with high severity. - Consider whether to introduce new enum or re-use some existing one.
null
2023-06-27T12:00:50Z
0.2
[]
['Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.Flow_Closed_HalfOpen_Closed', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.Disposed_EnsureThrows', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.BreakAsync_Ok', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionFailureAsync_EnsureCorrectBehavior', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.IsolateAsync_Ok', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionFailure_EnsureLock', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.HalfOpen_EnsureCorrectStateTransitionAfterExecution', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionFailureAsync_VoidResult_EnsureBreakingExceptionNotSet', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionPreExecute_HalfOpen', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionPreExecute_CircuitOpenedByException', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionPreExecute_CircuitOpenedByValue', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionSuccess_EnsureCorrectBehavior', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.HalfOpen_EnsureBreakDuration', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.OnActionFailureAsync_EnsureBreakDurationNotOverflow', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.Flow_Closed_HalfOpen_Open_HalfOpen_Closed', 'Polly.Core.Tests.CircuitBreaker.Controller.CircuitStateControllerTests.Ctor_EnsureDefaults']
App-vNext/Polly
polly-1326
91e5384b8a77bf19d618587e4929bc687658f8ed
diff --git a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md index 56839c5e0a1..f4743763425 100644 --- a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md +++ b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md @@ -9,8 +9,8 @@ Job=MediumRun Toolchain=InProcessEmitToolchain IterationCount=15 LaunchCount=2 WarmupCount=10 ``` -| Method | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio | -|------------------------------------- |---------:|----------:|----------:|------:|-------:|----------:|------------:| -| ExecuteStrategyPipeline_V7 | 2.269 μs | 0.0136 μs | 0.0204 μs | 1.00 | 0.1106 | 2824 B | 1.00 | -| ExecuteStrategyPipeline_V8 | 1.861 μs | 0.0111 μs | 0.0155 μs | 0.82 | - | 40 B | 0.01 | -| ExecuteStrategyPipeline_Telemetry_V8 | 2.402 μs | 0.0104 μs | 0.0156 μs | 1.06 | - | 40 B | 0.01 | +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Allocated | Alloc Ratio | +|------------------------------------- |---------:|----------:|----------:|------:|--------:|-------:|----------:|------------:| +| ExecuteStrategyPipeline_V7 | 2.220 μs | 0.0164 μs | 0.0236 μs | 1.00 | 0.00 | 0.1106 | 2824 B | 1.00 | +| ExecuteStrategyPipeline_V8 | 1.901 μs | 0.0089 μs | 0.0127 μs | 0.86 | 0.01 | - | 40 B | 0.01 | +| ExecuteStrategyPipeline_Telemetry_V8 | 2.947 μs | 0.0077 μs | 0.0115 μs | 1.33 | 0.02 | - | 40 B | 0.01 | diff --git a/src/Polly.Core/Hedging/Controller/HedgingController.cs b/src/Polly.Core/Hedging/Controller/HedgingController.cs index 1138248d351..1cd7cc4e14e 100644 --- a/src/Polly.Core/Hedging/Controller/HedgingController.cs +++ b/src/Polly.Core/Hedging/Controller/HedgingController.cs @@ -1,4 +1,5 @@ using Polly.Hedging.Controller; +using Polly.Telemetry; namespace Polly.Hedging.Utils; @@ -10,6 +11,7 @@ internal sealed class HedgingController<T> private int _rentedExecutions; public HedgingController( + ResilienceStrategyTelemetry telemetry, TimeProvider provider, HedgingHandler<T> handler, int maxAttempts) @@ -20,7 +22,7 @@ public HedgingController( _executionPool = new ObjectPool<TaskExecution<T>>(() => { Interlocked.Increment(ref _rentedExecutions); - return new TaskExecution<T>(handler, pool); + return new TaskExecution<T>(handler, pool, provider, telemetry); }, _ => { diff --git a/src/Polly.Core/Hedging/Controller/TaskExecution.cs b/src/Polly.Core/Hedging/Controller/TaskExecution.cs index a75a5201fd3..4aa7eaca3a8 100644 --- a/src/Polly.Core/Hedging/Controller/TaskExecution.cs +++ b/src/Polly.Core/Hedging/Controller/TaskExecution.cs @@ -1,4 +1,6 @@ +using System; using Polly.Hedging.Utils; +using Polly.Telemetry; namespace Polly.Hedging.Controller; @@ -21,15 +23,21 @@ internal sealed class TaskExecution<T> { private readonly ResilienceContext _cachedContext = ResilienceContext.Get(); private readonly CancellationTokenSourcePool _cancellationTokenSourcePool; + private readonly TimeProvider _timeProvider; + private readonly ResilienceStrategyTelemetry _telemetry; private readonly HedgingHandler<T> _handler; private CancellationTokenSource? _cancellationSource; private CancellationTokenRegistration? _cancellationRegistration; private ResilienceContext? _activeContext; + private long _startExecutionTimestamp; + private long _stopExecutionTimestamp; - public TaskExecution(HedgingHandler<T> handler, CancellationTokenSourcePool cancellationTokenSourcePool) + public TaskExecution(HedgingHandler<T> handler, CancellationTokenSourcePool cancellationTokenSourcePool, TimeProvider timeProvider, ResilienceStrategyTelemetry telemetry) { _handler = handler; _cancellationTokenSourcePool = cancellationTokenSourcePool; + _timeProvider = timeProvider; + _telemetry = telemetry; } /// <summary> @@ -56,6 +64,10 @@ public TaskExecution(HedgingHandler<T> handler, CancellationTokenSourcePool canc public Action<TaskExecution<T>>? OnReset { get; set; } + public TimeSpan ExecutionTime => _timeProvider.GetElapsedTime(_startExecutionTimestamp, _stopExecutionTimestamp); + + public int Attempt { get; private set; } + public void AcceptOutcome() { if (ExecutionTaskSafe?.IsCompleted == true) @@ -83,8 +95,10 @@ public async ValueTask<bool> InitializeAsync<TResult, TState>( TState state, int attempt) { + Attempt = attempt; Type = type; _cancellationSource = _cancellationTokenSourcePool.Get(System.Threading.Timeout.InfiniteTimeSpan); + _startExecutionTimestamp = _timeProvider.GetTimestamp(); Properties.Replace(snapshot.OriginalProperties); if (snapshot.OriginalCancellationToken.CanBeCanceled) @@ -109,6 +123,7 @@ public async ValueTask<bool> InitializeAsync<TResult, TState>( } catch (Exception e) { + _stopExecutionTimestamp = _timeProvider.GetTimestamp(); ExecutionTaskSafe = ExecuteCreateActionException<TResult>(e); return true; } @@ -164,9 +179,12 @@ public async ValueTask ResetAsync() IsHandled = false; Properties.Clear(); OnReset = null; + Attempt = 0; _activeContext = null; _cachedContext.Reset(); _cancellationSource = null!; + _startExecutionTimestamp = 0; + _stopExecutionTimestamp = 0; } private async Task ExecuteSecondaryActionAsync<TResult>(Func<ValueTask<Outcome<TResult>>> action) @@ -182,6 +200,7 @@ private async Task ExecuteSecondaryActionAsync<TResult>(Func<ValueTask<Outcome<T outcome = new Outcome<TResult>(e); } + _stopExecutionTimestamp = _timeProvider.GetTimestamp(); await UpdateOutcomeAsync(outcome).ConfigureAwait(Context.ContinueOnCapturedContext); } @@ -203,6 +222,7 @@ private async Task ExecutePrimaryActionAsync<TResult, TState>(Func<ResilienceCon outcome = new Outcome<TResult>(e); } + _stopExecutionTimestamp = _timeProvider.GetTimestamp(); await UpdateOutcomeAsync(outcome).ConfigureAwait(Context.ContinueOnCapturedContext); } @@ -211,6 +231,7 @@ private async Task UpdateOutcomeAsync<TResult>(Outcome<TResult> outcome) var args = new OutcomeArguments<TResult, HedgingPredicateArguments>(Context, outcome, new HedgingPredicateArguments()); Outcome = outcome.AsOutcome(); IsHandled = await _handler.ShouldHandle.HandleAsync(args).ConfigureAwait(Context.ContinueOnCapturedContext); + TelemetryUtil.ReportExecutionAttempt(_telemetry, Context, outcome, Attempt, ExecutionTime, IsHandled); } private void PrepareContext(ref ContextSnapshot snapshot) diff --git a/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs b/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs index 88f8d763b0c..9a9e6dd6e41 100644 --- a/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs +++ b/src/Polly.Core/Hedging/HedgingResilienceStrategy.cs @@ -7,6 +7,7 @@ namespace Polly.Hedging; internal sealed class HedgingResilienceStrategy<T> : ResilienceStrategy { + private readonly TimeProvider _timeProvider; private readonly ResilienceStrategyTelemetry _telemetry; private readonly HedgingController<T> _controller; @@ -22,11 +23,12 @@ public HedgingResilienceStrategy( HedgingDelay = hedgingDelay; MaxHedgedAttempts = maxHedgedAttempts; HedgingDelayGenerator = hedgingDelayGenerator; + _timeProvider = timeProvider; HedgingHandler = hedgingHandler; OnHedging = onHedging; _telemetry = telemetry; - _controller = new HedgingController<T>(timeProvider, HedgingHandler, maxHedgedAttempts); + _controller = new HedgingController<T>(telemetry, timeProvider, HedgingHandler, maxHedgedAttempts); } public TimeSpan HedgingDelay { get; } @@ -75,7 +77,7 @@ private async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState>( attempt++; var continueOnCapturedContext = context.ContinueOnCapturedContext; var cancellationToken = context.CancellationToken; - + var start = _timeProvider.GetTimestamp(); if (cancellationToken.IsCancellationRequested) { return new Outcome<TResult>(new OperationCanceledException(cancellationToken).TrySetStackTrace()); @@ -97,7 +99,7 @@ private async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState>( await HandleOnHedgingAsync( context, new Outcome<TResult>(default(TResult)), - new OnHedgingArguments(attempt, HasOutcome: false)).ConfigureAwait(context.ContinueOnCapturedContext); + new OnHedgingArguments(attempt, HasOutcome: false, ExecutionTime: delay)).ConfigureAwait(context.ContinueOnCapturedContext); continue; } @@ -109,10 +111,11 @@ await HandleOnHedgingAsync( return outcome; } + var executionTime = _timeProvider.GetElapsedTime(start); await HandleOnHedgingAsync( context, outcome, - new OnHedgingArguments(attempt, HasOutcome: true)).ConfigureAwait(context.ContinueOnCapturedContext); + new OnHedgingArguments(attempt, HasOutcome: true, executionTime)).ConfigureAwait(context.ContinueOnCapturedContext); } } diff --git a/src/Polly.Core/Hedging/OnHedgingArguments.cs b/src/Polly.Core/Hedging/OnHedgingArguments.cs index b1930cced0b..4c963bd4985 100644 --- a/src/Polly.Core/Hedging/OnHedgingArguments.cs +++ b/src/Polly.Core/Hedging/OnHedgingArguments.cs @@ -8,4 +8,8 @@ namespace Polly.Hedging; /// Determines whether the outcome is available before loading the next hedged task. /// No outcome indicates that the previous action did not finish within the hedging delay. /// </param> -public record OnHedgingArguments(int Attempt, bool HasOutcome); +/// <param name="ExecutionTime"> +/// The execution time of hedging attempt or the hedging delay +/// in case the attempt was not finished in time. +/// </param> +public record OnHedgingArguments(int Attempt, bool HasOutcome, TimeSpan ExecutionTime); diff --git a/src/Polly.Core/Retry/OnRetryArguments.cs b/src/Polly.Core/Retry/OnRetryArguments.cs index 578106d0885..70e5e1926c9 100644 --- a/src/Polly.Core/Retry/OnRetryArguments.cs +++ b/src/Polly.Core/Retry/OnRetryArguments.cs @@ -5,4 +5,5 @@ namespace Polly.Retry; /// </summary> /// <param name="Attempt">The zero-based attempt number. The first attempt is 0, the second attempt is 1, and so on.</param> /// <param name="RetryDelay">The delay before the next retry.</param> -public record OnRetryArguments(int Attempt, TimeSpan RetryDelay); +/// <param name="ExecutionTime">The execution time of this attempt.</param> +public record OnRetryArguments(int Attempt, TimeSpan RetryDelay, TimeSpan ExecutionTime); diff --git a/src/Polly.Core/Retry/RetryResilienceStrategy.cs b/src/Polly.Core/Retry/RetryResilienceStrategy.cs index d653a83f3de..418c1b73020 100644 --- a/src/Polly.Core/Retry/RetryResilienceStrategy.cs +++ b/src/Polly.Core/Retry/RetryResilienceStrategy.cs @@ -57,10 +57,15 @@ protected internal override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<T while (true) { + var startTimestamp = _timeProvider.GetTimestamp(); var outcome = await ExecuteCallbackSafeAsync(callback, context, state).ConfigureAwait(context.ContinueOnCapturedContext); var shouldRetryArgs = new OutcomeArguments<TResult, RetryPredicateArguments>(context, outcome, new RetryPredicateArguments(attempt)); + var handle = await ShouldRetry.HandleAsync(shouldRetryArgs).ConfigureAwait(context.ContinueOnCapturedContext); + var executionTime = _timeProvider.GetElapsedTime(startTimestamp); - if (context.CancellationToken.IsCancellationRequested || IsLastAttempt(attempt) || !await ShouldRetry.HandleAsync(shouldRetryArgs).ConfigureAwait(context.ContinueOnCapturedContext)) + TelemetryUtil.ReportExecutionAttempt(_telemetry, context, outcome, attempt, executionTime, handle); + + if (context.CancellationToken.IsCancellationRequested || IsLastAttempt(attempt) || !handle) { return outcome; } @@ -76,7 +81,7 @@ protected internal override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<T } } - var onRetryArgs = new OutcomeArguments<TResult, OnRetryArguments>(context, outcome, new OnRetryArguments(attempt, delay)); + var onRetryArgs = new OutcomeArguments<TResult, OnRetryArguments>(context, outcome, new OnRetryArguments(attempt, delay, executionTime)); _telemetry.Report(RetryConstants.OnRetryEvent, onRetryArgs); if (OnRetry is not null) diff --git a/src/Polly.Core/Telemetry/ExecutionAttemptArguments.Pool.cs b/src/Polly.Core/Telemetry/ExecutionAttemptArguments.Pool.cs new file mode 100644 index 00000000000..38cee68d3df --- /dev/null +++ b/src/Polly.Core/Telemetry/ExecutionAttemptArguments.Pool.cs @@ -0,0 +1,22 @@ +namespace Polly.Telemetry; + +public partial class ExecutionAttemptArguments +{ + private static readonly ObjectPool<ExecutionAttemptArguments> Pool = new(() => new ExecutionAttemptArguments(), args => + { + args.ExecutionTime = TimeSpan.Zero; + args.Attempt = 0; + args.Handled = false; + }); + + internal static ExecutionAttemptArguments Get(int attempt, TimeSpan executionTime, bool handled) + { + var args = Pool.Get(); + args.Attempt = attempt; + args.ExecutionTime = executionTime; + args.Handled = handled; + return args; + } + + internal static void Return(ExecutionAttemptArguments args) => Pool.Return(args); +} diff --git a/src/Polly.Core/Telemetry/ExecutionAttemptArguments.cs b/src/Polly.Core/Telemetry/ExecutionAttemptArguments.cs new file mode 100644 index 00000000000..df3dc859f58 --- /dev/null +++ b/src/Polly.Core/Telemetry/ExecutionAttemptArguments.cs @@ -0,0 +1,39 @@ +namespace Polly.Telemetry; + +/// <summary> +/// Arguments that encapsulate the execution attempt for retries or hedging. +/// </summary> +public partial class ExecutionAttemptArguments +{ + /// <summary> + /// Initializes a new instance of the <see cref="ExecutionAttemptArguments"/> class. + /// </summary> + /// <param name="attempt">The execution attempt.</param> + /// <param name="executionTime">The execution time.</param> + /// <param name="handled">Determines whether the attempt was handled by the strategy.</param> + public ExecutionAttemptArguments(int attempt, TimeSpan executionTime, bool handled) + { + Attempt = attempt; + ExecutionTime = executionTime; + Handled = handled; + } + + private ExecutionAttemptArguments() + { + } + + /// <summary> + /// Gets the attempt number. + /// </summary> + public int Attempt { get; private set; } + + /// <summary> + /// Gets the execution time of the attempt. + /// </summary> + public TimeSpan ExecutionTime { get; private set; } + + /// <summary> + /// Gets a value indicating whether the outcome was handled by retry or hedging strategy. + /// </summary> + public bool Handled { get; private set; } +} diff --git a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs index ff3f7984ac0..100fc9073a2 100644 --- a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs +++ b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs @@ -18,6 +18,11 @@ internal ResilienceStrategyTelemetry(ResilienceTelemetrySource source, Diagnosti internal ResilienceTelemetrySource TelemetrySource { get; } + /// <summary> + /// Gets a value indicating whether telemetry is enabled. + /// </summary> + public bool IsEnabled => DiagnosticSource is not null; + /// <summary> /// Reports an event that occurred in a resilience strategy. /// </summary> @@ -31,7 +36,7 @@ public void Report<TArgs>(string eventName, ResilienceContext context, TArgs arg Guard.NotNull(eventName); Guard.NotNull(context); - context.AddResilienceEvent(new ResilienceEvent(eventName)); + AddResilienceEvent(eventName, context, args); if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(eventName)) { @@ -57,7 +62,7 @@ public void Report<TArgs, TResult>(string eventName, OutcomeArguments<TResult, T { Guard.NotNull(eventName); - args.Context.AddResilienceEvent(new ResilienceEvent(eventName)); + AddResilienceEvent(eventName, args.Context, args.Arguments); if (DiagnosticSource is null || !DiagnosticSource.IsEnabled(eventName)) { @@ -70,5 +75,17 @@ public void Report<TArgs, TResult>(string eventName, OutcomeArguments<TResult, T TelemetryEventArguments.Return(telemetryArgs); } + + private static void AddResilienceEvent<TArgs>(string eventName, ResilienceContext context, TArgs args) + { + // ExecutionAttemptArguments is not reported as resilience event because that information is already contained + // in OnHedgingArguments and OnRetryArguments + if (args is ExecutionAttemptArguments attempt) + { + return; + } + + context.AddResilienceEvent(new ResilienceEvent(eventName)); + } } diff --git a/src/Polly.Core/Telemetry/TelemetryUtil.cs b/src/Polly.Core/Telemetry/TelemetryUtil.cs index 567706215c9..7486edd855f 100644 --- a/src/Polly.Core/Telemetry/TelemetryUtil.cs +++ b/src/Polly.Core/Telemetry/TelemetryUtil.cs @@ -4,6 +4,8 @@ internal static class TelemetryUtil { internal const string PollyDiagnosticSource = "Polly"; + internal const string ExecutionAttempt = "ExecutionAttempt"; + internal static readonly ResiliencePropertyKey<string> StrategyKey = new("Polly.StrategyKey"); public static ResilienceStrategyTelemetry CreateTelemetry( @@ -17,4 +19,22 @@ public static ResilienceStrategyTelemetry CreateTelemetry( return new ResilienceStrategyTelemetry(telemetrySource, diagnosticSource); } + + public static void ReportExecutionAttempt<TResult>( + ResilienceStrategyTelemetry telemetry, + ResilienceContext context, + Outcome<TResult> outcome, + int attempt, + TimeSpan executionTime, + bool handled) + { + if (!telemetry.IsEnabled) + { + return; + } + + var attemptArgs = ExecutionAttemptArguments.Get(attempt, executionTime, handled); + telemetry.Report<ExecutionAttemptArguments, TResult>(ExecutionAttempt, new(context, outcome, attemptArgs)); + ExecutionAttemptArguments.Return(attemptArgs); + } } diff --git a/src/Polly.Core/Utils/TimeProvider.cs b/src/Polly.Core/Utils/TimeProvider.cs index d8b76d2453b..400d5ff93e3 100644 --- a/src/Polly.Core/Utils/TimeProvider.cs +++ b/src/Polly.Core/Utils/TimeProvider.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace Polly.Utils; #pragma warning disable S3872 // Parameter names should not duplicate the names of their methods @@ -6,6 +8,7 @@ namespace Polly.Utils; /// TEMPORARY ONLY, to be replaced with System.TimeProvider - https://github.com/dotnet/runtime/issues/36617 later. /// </summary> /// <remarks>We trimmed some of the API that's not relevant for us too.</remarks> +[ExcludeFromCodeCoverage] internal abstract class TimeProvider { private readonly double _tickFrequency; @@ -22,7 +25,7 @@ protected TimeProvider(long timestampFrequency) public long TimestampFrequency { get; } - public abstract long GetTimestamp(); + public virtual long GetTimestamp() => Environment.TickCount; public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp) => new((long)((endingTimestamp - startingTimestamp) * _tickFrequency)); diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs index 0f4a58bb38a..b0cfc2e0ab5 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs @@ -1,6 +1,5 @@ using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; -using Polly.Extensions.Utils; using Polly.Telemetry; namespace Polly.Extensions.Telemetry; @@ -22,10 +21,17 @@ public ResilienceTelemetryDiagnosticSource(TelemetryOptions options) Counter = Meter.CreateCounter<int>( "resilience-events", description: "Tracks the number of resilience events that occurred in resilience strategies."); + + AttemptDuration = Meter.CreateHistogram<double>( + "execution-attempt-duration", + unit: "ms", + description: "Tracks the duration of execution attempts."); } public Counter<int> Counter { get; } + public Histogram<double> AttemptDuration { get; } + public override bool IsEnabled(string name) => true; public override void Write(string name, object? value) @@ -39,16 +45,8 @@ public override void Write(string name, object? value) MeterEvent(args); } - private void MeterEvent(TelemetryEventArguments args) + private static void AddCommonTags(TelemetryEventArguments args, ResilienceTelemetrySource source, EnrichmentContext enrichmentContext) { - if (!Counter.Enabled) - { - return; - } - - var source = args.Source; - - var enrichmentContext = EnrichmentContext.Get(args.Context, args.Arguments, args.Outcome); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.EventName, args.EventName)); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.BuilderName, source.BuilderName)); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyName, source.StrategyName)); @@ -56,11 +54,35 @@ private void MeterEvent(TelemetryEventArguments args) enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyKey, source.BuilderProperties.GetValue(TelemetryUtil.StrategyKey, null!))); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ResultType, args.Context.GetResultType())); enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ExceptionName, args.Outcome?.Exception?.GetType().FullName)); - EnrichmentUtil.Enrich(enrichmentContext, _enrichers); + } - Counter.Add(1, enrichmentContext.TagsSpan); + private void MeterEvent(TelemetryEventArguments args) + { + var source = args.Source; + + if (args.Arguments is ExecutionAttemptArguments executionAttempt) + { + if (!AttemptDuration.Enabled) + { + return; + } - EnrichmentContext.Return(enrichmentContext); + var enrichmentContext = EnrichmentContext.Get(args.Context, args.Arguments, args.Outcome); + AddCommonTags(args, source, enrichmentContext); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.AttemptNumber, executionAttempt.Attempt.AsBoxedInt())); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.AttemptHandled, executionAttempt.Handled.AsBoxedBool())); + EnrichmentUtil.Enrich(enrichmentContext, _enrichers); + AttemptDuration.Record(executionAttempt.ExecutionTime.TotalMilliseconds, enrichmentContext.TagsSpan); + EnrichmentContext.Return(enrichmentContext); + } + else if (Counter.Enabled) + { + var enrichmentContext = EnrichmentContext.Get(args.Context, args.Arguments, args.Outcome); + AddCommonTags(args, source, enrichmentContext); + EnrichmentUtil.Enrich(enrichmentContext, _enrichers); + Counter.Add(1, enrichmentContext.TagsSpan); + EnrichmentContext.Return(enrichmentContext); + } } private void LogEvent(TelemetryEventArguments args) diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs index 0fe4708cb0e..bbfbae10b50 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryTags.cs @@ -17,4 +17,8 @@ internal class ResilienceTelemetryTags public const string ExceptionName = "exception-name"; public const string ExecutionHealth = "execution-health"; + + public const string AttemptNumber = "attempt-number"; + + public const string AttemptHandled = "attempt-handled"; } diff --git a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs index b9c275ff246..738fb6b803d 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs @@ -1,7 +1,5 @@ using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; -using Polly.Extensions.Telemetry; -using Polly.Extensions.Utils; using Polly.Utils; namespace Polly.Extensions.Telemetry; diff --git a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategyBuilderExtensions.cs b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategyBuilderExtensions.cs index b79940b6342..ad822a48292 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategyBuilderExtensions.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategyBuilderExtensions.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.Logging; using Polly.Extensions.Telemetry; -using Polly.Extensions.Utils; using Polly.Utils; namespace Polly; diff --git a/src/Polly.Extensions/Telemetry/TelemetryUtil.cs b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs new file mode 100644 index 00000000000..bf07a06b0f6 --- /dev/null +++ b/src/Polly.Extensions/Telemetry/TelemetryUtil.cs @@ -0,0 +1,28 @@ +namespace Polly.Extensions.Telemetry; + +internal static class TelemetryUtil +{ + private const int MaxIntegers = 100; + + private static readonly object[] Integers = Enumerable.Range(0, MaxIntegers).Select(v => (object)v).ToArray(); + + private static readonly object True = true; + + private static readonly object False = false; + + internal const string PollyDiagnosticSource = "Polly"; + + internal static readonly ResiliencePropertyKey<string> StrategyKey = new("Polly.StrategyKey"); + + public static object AsBoxedBool(this bool value) => value switch + { + true => True, + false => False, + }; + + public static object AsBoxedInt(this int value) => value switch + { + >= 0 and < MaxIntegers => Integers[value], + _ => value, + }; +} diff --git a/src/Polly.Extensions/Utils/TelemetryUtil.cs b/src/Polly.Extensions/Utils/TelemetryUtil.cs deleted file mode 100644 index 0b854951882..00000000000 --- a/src/Polly.Extensions/Utils/TelemetryUtil.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Polly.Extensions.Utils; - -internal static class TelemetryUtil -{ - internal const string PollyDiagnosticSource = "Polly"; - - internal static readonly ResiliencePropertyKey<string> StrategyKey = new("Polly.StrategyKey"); -}
diff --git a/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs b/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs index 77455c3b6e1..0fca74985fe 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/HedgingControllerTests.cs @@ -1,4 +1,5 @@ using Polly.Hedging.Utils; +using Polly.Telemetry; namespace Polly.Core.Tests.Hedging.Controller; @@ -7,7 +8,8 @@ public class HedgingControllerTests [Fact] public async Task Pooling_Ok() { - var controller = new HedgingController<int>(new HedgingTimeProvider(), HedgingHelper.CreateHandler<int>(_ => false, args => null), 3); + var telemetry = TestUtilities.CreateResilienceTelemetry(_ => { }); + var controller = new HedgingController<int>(telemetry, new HedgingTimeProvider(), HedgingHelper.CreateHandler<int>(_ => false, args => null), 3); var context1 = controller.GetContext(ResilienceContext.Get()); await PrepareAsync(context1); diff --git a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs index ea78a2a7aa3..c279c17d35f 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/HedgingExecutionContextTests.cs @@ -477,7 +477,8 @@ private HedgingExecutionContext<DisposableResult> Create() var pool = new ObjectPool<TaskExecution<DisposableResult>>( () => { - var execution = new TaskExecution<DisposableResult>(_hedgingHandler, CancellationTokenSourcePool.Create(_timeProvider)); + var telemetry = TestUtilities.CreateResilienceTelemetry(_ => { }); + var execution = new TaskExecution<DisposableResult>(_hedgingHandler, CancellationTokenSourcePool.Create(_timeProvider), _timeProvider, telemetry); _createdExecutions.Add(execution); return execution; }, diff --git a/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs b/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs index 63d005a329d..a0ddc532e15 100644 --- a/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs +++ b/test/Polly.Core.Tests/Hedging/Controller/TaskExecutionTests.cs @@ -1,6 +1,7 @@ using Polly.Hedging; using Polly.Hedging.Controller; using Polly.Hedging.Utils; +using Polly.Telemetry; using Polly.Utils; namespace Polly.Core.Tests.Hedging.Controller; @@ -12,10 +13,20 @@ public class TaskExecutionTests : IDisposable private readonly HedgingHandler<DisposableResult> _hedgingHandler; private readonly CancellationTokenSource _cts; private readonly HedgingTimeProvider _timeProvider; + private readonly ResilienceStrategyTelemetry _telemetry; + private readonly List<ExecutionAttemptArguments> _args = new(); private ContextSnapshot _snapshot; public TaskExecutionTests() { + _telemetry = TestUtilities.CreateResilienceTelemetry(args => + { + if (args.Arguments is ExecutionAttemptArguments attempt) + { + _args.Add(ExecutionAttemptArguments.Get(attempt.Attempt, attempt.ExecutionTime, attempt.Handled)); + } + }); + _timeProvider = new HedgingTimeProvider(); _cts = new CancellationTokenSource(); _hedgingHandler = HedgingHelper.CreateHandler<DisposableResult>(outcome => outcome switch @@ -44,12 +55,16 @@ await execution.InitializeAsync(HedgedTaskType.Primary, _snapshot, return new Outcome<DisposableResult>(new DisposableResult { Name = value }).AsValueTask(); }, "dummy-state", - 1); + 99); await execution.ExecutionTaskSafe!; ((DisposableResult)execution.Outcome.Result!).Name.Should().Be(value); execution.IsHandled.Should().Be(handled); AssertPrimaryContext(execution.Context, execution); + + _args.Should().HaveCount(1); + _args[0].Handled.Should().Be(handled); + _args[0].Attempt.Should().Be(99); } [Fact] @@ -284,5 +299,5 @@ private void CreateSnapshot(CancellationToken? token = null) return () => new DisposableResult { Name = Handled }.AsOutcomeAsync(); }; - private TaskExecution<DisposableResult> Create() => new(_hedgingHandler, CancellationTokenSourcePool.Create(TimeProvider.System)); + private TaskExecution<DisposableResult> Create() => new(_hedgingHandler, CancellationTokenSourcePool.Create(TimeProvider.System), _timeProvider, _telemetry); } diff --git a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs index 7801b062c4a..f88df19454a 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs @@ -80,6 +80,32 @@ public async Task Execute_CancellationRequested_Throws() outcome.Exception!.StackTrace.Should().Contain("Execute_CancellationRequested_Throws"); } + [Fact] + public void ExecutePrimaryAndSecondary_EnsureAttemptReported() + { + int timeStamp = 0; + _timeProvider.TimeStampProvider = () => + { + timeStamp += 1000; + return timeStamp; + }; + _options.MaxHedgedAttempts = 2; + ConfigureHedging(_ => true, args => () => "any".AsOutcomeAsync()); + var strategy = Create(); + + strategy.Execute(_ => "dummy"); + + var attempts = _events.Select(v => v.Arguments).OfType<ExecutionAttemptArguments>().ToArray(); + + attempts[0].Handled.Should().BeTrue(); + attempts[0].ExecutionTime.Should().Be(_timeProvider.GetElapsedTime(0, 1000)); + attempts[0].Attempt.Should().Be(0); + + attempts[1].Handled.Should().BeTrue(); + attempts[1].ExecutionTime.Should().Be(_timeProvider.GetElapsedTime(0, 1000)); + attempts[1].Attempt.Should().Be(1); + } + [InlineData(-1)] [InlineData(-1000)] [InlineData(0)] diff --git a/test/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs b/test/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs index 3a008e42cdf..d1f04d52a07 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingTimeProvider.cs @@ -21,10 +21,14 @@ public void Advance(TimeSpan diff) } } + public Func<int> TimeStampProvider { get; set; } = () => 0; + public List<DelayEntry> DelayEntries { get; } = new List<DelayEntry>(); public override DateTimeOffset UtcNow => _utcNow; + public override long GetTimestamp() => TimeStampProvider(); + public override void CancelAfter(CancellationTokenSource source, TimeSpan delay) { throw new NotSupportedException(); @@ -41,8 +45,6 @@ public override Task Delay(TimeSpan delayValue, CancellationToken cancellationTo return entry.Source.Task; } - public override long GetTimestamp() => throw new NotSupportedException(); - public record DelayEntry(TimeSpan Delay, TaskCompletionSource<bool> Source, DateTimeOffset TimeStamp) { public void Complete() diff --git a/test/Polly.Core.Tests/Helpers/FakeTimeProvider.cs b/test/Polly.Core.Tests/Helpers/FakeTimeProvider.cs index 969d6992555..d8a57bbcd46 100644 --- a/test/Polly.Core.Tests/Helpers/FakeTimeProvider.cs +++ b/test/Polly.Core.Tests/Helpers/FakeTimeProvider.cs @@ -41,6 +41,12 @@ public FakeTimeProvider SetupAnyDelay(CancellationToken cancellationToken = defa return this; } + public FakeTimeProvider SetupGetTimestamp() + { + Setup(x => x.GetTimestamp()).Returns(0); + return this; + } + public FakeTimeProvider SetupDelay(TimeSpan delay, CancellationToken cancellationToken = default) { Setup(x => x.Delay(delay, cancellationToken)).Returns(Task.CompletedTask); diff --git a/test/Polly.Core.Tests/Issues/IssuesTests.cs b/test/Polly.Core.Tests/Issues/IssuesTests.cs index c94cc022449..0bb15eef3b0 100644 --- a/test/Polly.Core.Tests/Issues/IssuesTests.cs +++ b/test/Polly.Core.Tests/Issues/IssuesTests.cs @@ -2,5 +2,5 @@ namespace Polly.Core.Tests.Issues; public partial class IssuesTests { - private FakeTimeProvider TimeProvider { get; } = new FakeTimeProvider().SetupUtcNow().SetupAnyDelay(); + private FakeTimeProvider TimeProvider { get; } = new FakeTimeProvider().SetupUtcNow().SetupAnyDelay().SetupGetTimestamp(); } diff --git a/test/Polly.Core.Tests/Retry/OnRetryArgumentsTests.cs b/test/Polly.Core.Tests/Retry/OnRetryArgumentsTests.cs index 1364e578802..3237ee134ed 100644 --- a/test/Polly.Core.Tests/Retry/OnRetryArgumentsTests.cs +++ b/test/Polly.Core.Tests/Retry/OnRetryArgumentsTests.cs @@ -7,9 +7,10 @@ public class OnRetryArgumentsTests [Fact] public void Ctor_Ok() { - var args = new OnRetryArguments(2, TimeSpan.FromSeconds(3)); + var args = new OnRetryArguments(2, TimeSpan.FromSeconds(3), TimeSpan.MaxValue); args.Attempt.Should().Be(2); args.RetryDelay.Should().Be(TimeSpan.FromSeconds(3)); + args.ExecutionTime.Should().Be(TimeSpan.MaxValue); } } diff --git a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs index 18e14b9dbec..009616d0b77 100644 --- a/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryResilienceStrategyTests.cs @@ -9,13 +9,15 @@ public class RetryResilienceStrategyTests { private readonly RetryStrategyOptions _options = new(); private readonly FakeTimeProvider _timeProvider = new(); - private readonly ResilienceStrategyTelemetry _telemetry; private readonly Mock<DiagnosticSource> _diagnosticSource = new(); + private ResilienceStrategyTelemetry _telemetry; public RetryResilienceStrategyTests() { _telemetry = TestUtilities.CreateResilienceTelemetry(_diagnosticSource.Object); _options.ShouldHandle = _ => new ValueTask<bool>(false); + + _timeProvider.SetupSequence(v => v.GetTimestamp()).Returns(0).Returns(100); } [Fact] @@ -207,6 +209,53 @@ public void OnRetry_EnsureCorrectArguments() delays[2].Should().Be(TimeSpan.FromSeconds(6)); } + [Fact] + public void OnRetry_EnsureExecutionTime() + { + _options.OnRetry = args => + { + args.Arguments.ExecutionTime.Should().Be(_timeProvider.Object.GetElapsedTime(100, 1000)); + + return default; + }; + + _options.ShouldHandle = _ => PredicateResult.True; + _options.RetryCount = 1; + _options.BackoffType = RetryBackoffType.Linear; + _timeProvider.SetupAnyDelay(); + _timeProvider + .SetupSequence(v => v.GetTimestamp()) + .Returns(100) + .Returns(1000) + .Returns(100) + .Returns(1000); + + var sut = CreateSut(); + + sut.Execute(() => 0); + } + + [Fact] + public void Execute_EnsureAttemptReported() + { + var called = false; + _timeProvider.SetupSequence(v => v.GetTimestamp()).Returns(100).Returns(1000); + _telemetry = TestUtilities.CreateResilienceTelemetry(args => + { + var attempt = args.Arguments.Should().BeOfType<ExecutionAttemptArguments>().Subject; + + attempt.Handled.Should().BeFalse(); + attempt.Attempt.Should().Be(0); + attempt.ExecutionTime.Should().Be(_timeProvider.Object.GetElapsedTime(100, 1000)); + called = true; + }); + + var sut = CreateSut(); + + sut.Execute(() => 0); + called.Should().BeTrue(); + } + [Fact] public void OnRetry_EnsureTelemetry() { diff --git a/test/Polly.Core.Tests/Telemetry/ExecutionAttemptArgumentsTests.cs b/test/Polly.Core.Tests/Telemetry/ExecutionAttemptArgumentsTests.cs new file mode 100644 index 00000000000..80947ff0843 --- /dev/null +++ b/test/Polly.Core.Tests/Telemetry/ExecutionAttemptArgumentsTests.cs @@ -0,0 +1,39 @@ +using System; +using Polly.Telemetry; + +namespace Polly.Extensions.Tests.Telemetry; + +public class ExecutionAttemptArgumentsTests +{ + [Fact] + public void Ctor_Ok() + { + var args = new ExecutionAttemptArguments(99, TimeSpan.MaxValue, true); + Assert.NotNull(args); + args.Attempt.Should().Be(99); + args.ExecutionTime.Should().Be(TimeSpan.MaxValue); + args.Handled.Should().BeTrue(); + } + + [Fact] + public void Get_Ok() + { + var args = ExecutionAttemptArguments.Get(99, TimeSpan.MaxValue, true); + Assert.NotNull(args); + args.Attempt.Should().Be(99); + args.ExecutionTime.Should().Be(TimeSpan.MaxValue); + args.Handled.Should().BeTrue(); + } + + [Fact] + public void Return_EnsurePropertiesCleared() + { + var args = ExecutionAttemptArguments.Get(99, TimeSpan.MaxValue, true); + + ExecutionAttemptArguments.Return(args); + + args.Attempt.Should().Be(0); + args.ExecutionTime.Should().Be(TimeSpan.Zero); + args.Handled.Should().BeFalse(); + } +} diff --git a/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs b/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs index 034683fc82b..bce36341bb0 100644 --- a/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs +++ b/test/Polly.Core.Tests/Telemetry/ResilienceStrategyTelemetryTests.cs @@ -38,6 +38,16 @@ public void Report_NoOutcome_OK() _diagnosticSource.VerifyAll(); } + [Fact] + public void Report_Attempt_EnsureNotRecordedOnResilienceContext() + { + var context = ResilienceContext.Get(); + _diagnosticSource.Setup(o => o.IsEnabled("dummy-event")).Returns(false); + _sut.Report("dummy-event", context, ExecutionAttemptArguments.Get(0, TimeSpan.Zero, true)); + + context.ResilienceEvents.Should().BeEmpty(); + } + [Fact] public void Report_NoOutcomeWhenNotSubscribed_None() { diff --git a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs index 2ebce931327..4fe0e37cc14 100644 --- a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs @@ -1,6 +1,7 @@ using System.Net.Http; using Microsoft.Extensions.Logging; using Polly.Extensions.Telemetry; +using Polly.Telemetry; namespace Polly.Extensions.Tests.Telemetry; @@ -31,8 +32,11 @@ public void Meter_Ok() { ResilienceTelemetryDiagnosticSource.Meter.Name.Should().Be("Polly"); ResilienceTelemetryDiagnosticSource.Meter.Version.Should().Be("1.0"); - new ResilienceTelemetryDiagnosticSource(new TelemetryOptions()) - .Counter.Description.Should().Be("Tracks the number of resilience events that occurred in resilience strategies."); + var source = new ResilienceTelemetryDiagnosticSource(new TelemetryOptions()); + + source.Counter.Description.Should().Be("Tracks the number of resilience events that occurred in resilience strategies."); + source.AttemptDuration.Description.Should().Be("Tracks the duration of execution attempts."); + source.AttemptDuration.Unit.Should().Be("ms"); } [Fact] @@ -151,6 +155,49 @@ public void WriteEvent_MeteringWithoutEnrichers_Ok(bool noOutcome, bool exceptio } } + [InlineData(true, false)] + [InlineData(false, false)] + [InlineData(true, true)] + [InlineData(false, true)] + [Theory] + public void WriteExecutionAttemptEvent_Metering_Ok(bool noOutcome, bool exception) + { + var telemetry = Create(); + var attemptArg = new ExecutionAttemptArguments(5, TimeSpan.FromSeconds(50), true); + Outcome<object>? outcome = noOutcome switch + { + false => null, + true when exception => new Outcome<object>(new InvalidOperationException("Dummy message.")), + _ => new Outcome<object>(true) + }; + ReportEvent(telemetry, outcome, context: ResilienceContext.Get().WithResultType<bool>(), arg: attemptArg); + + var events = GetEvents("execution-attempt-duration"); + events.Should().HaveCount(1); + var ev = events[0]; + + ev.Count.Should().Be(9); + ev["event-name"].Should().Be("my-event"); + ev["strategy-type"].Should().Be("my-strategy-type"); + ev["strategy-name"].Should().Be("my-strategy"); + ev["strategy-key"].Should().Be("my-strategy-key"); + ev["builder-name"].Should().Be("my-builder"); + ev["result-type"].Should().Be("Boolean"); + ev["attempt-number"].Should().Be(5); + ev["attempt-handled"].Should().Be(true); + + if (outcome?.Exception is not null) + { + ev["exception-name"].Should().Be("System.InvalidOperationException"); + } + else + { + ev["exception-name"].Should().Be(null); + } + + _events.Single(v => v.Name == "execution-attempt-duration").Measurement.Should().Be(50000); + } + [InlineData(1)] [InlineData(100)] [Theory] @@ -208,7 +255,12 @@ private ResilienceTelemetryDiagnosticSource Create(Action<ICollection<Action<Enr return new(options); } - private static void ReportEvent(ResilienceTelemetryDiagnosticSource telemetry, Outcome<object>? outcome, string? strategyKey = "my-strategy-key", ResilienceContext? context = null) + private static void ReportEvent( + ResilienceTelemetryDiagnosticSource telemetry, + Outcome<object>? outcome, + string? strategyKey = "my-strategy-key", + ResilienceContext? context = null, + object? arg = null) { context ??= ResilienceContext.Get(); var props = new ResilienceProperties(); @@ -225,6 +277,6 @@ private static void ReportEvent(ResilienceTelemetryDiagnosticSource telemetry, O "my-strategy-type", context, outcome, - new TestArguments()); + arg ?? new TestArguments()); } } diff --git a/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs b/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs new file mode 100644 index 00000000000..b2efdeec2f6 --- /dev/null +++ b/test/Polly.Extensions.Tests/Utils/TelemetryUtilTests.cs @@ -0,0 +1,29 @@ +using FluentAssertions; +using Polly.Extensions.Telemetry; + +namespace Polly.Extensions.Tests.Utils; + +public class TelemetryUtilTests +{ + [Fact] + public void AsBoxedPool_Ok() + { + TelemetryUtil.AsBoxedBool(true).Should().Be(true); + TelemetryUtil.AsBoxedBool(false).Should().Be(false); + } + + [Fact] + public void AsBoxedInt_Ok() + { + var hash = new HashSet<object>(); + + for (int i = 0; i < 100; i++) + { + i.AsBoxedInt().Should().BeSameAs(i.AsBoxedInt()); + i.AsBoxedInt().Should().Be(i); + } + + (-1).AsBoxedInt().Should().NotBeSameAs((-1).AsBoxedInt()); + 100.AsBoxedInt().Should().NotBeSameAs(100.AsBoxedInt()); + } +} diff --git a/test/Polly.TestUtils/MeteringEvent.cs b/test/Polly.TestUtils/MeteringEvent.cs index f422877d73c..ffe79df6d16 100644 --- a/test/Polly.TestUtils/MeteringEvent.cs +++ b/test/Polly.TestUtils/MeteringEvent.cs @@ -1,3 +1,3 @@ namespace Polly.TestUtils; -public record MeteringEvent(string Name, Dictionary<string, object?> Tags); +public record MeteringEvent(object Measurement, string Name, Dictionary<string, object?> Tags); diff --git a/test/Polly.TestUtils/TestUtilities.cs b/test/Polly.TestUtils/TestUtilities.cs index 540e83d4374..f4d8f5cbefc 100644 --- a/test/Polly.TestUtils/TestUtilities.cs +++ b/test/Polly.TestUtils/TestUtilities.cs @@ -70,7 +70,7 @@ public static IDisposable EnablePollyMetering(ICollection<MeteringEvent> events) meterListener.Start(); void OnMeasurementRecorded<T>(Instrument instrument, T measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state) - => events.Add(new MeteringEvent(instrument.Name, tags.ToArray().ToDictionary(v => v.Key, v => v.Value))); + => events.Add(new MeteringEvent(measurement!, instrument.Name, tags.ToArray().ToDictionary(v => v.Key, v => v.Value))); return meterListener; } @@ -113,9 +113,15 @@ private sealed class CallbackDiagnosticSource : DiagnosticSource public override void Write(string name, object? value) { var args = (TelemetryEventArguments)value!; + var arguments = args.Arguments; + + if (arguments is ExecutionAttemptArguments attempt) + { + arguments = ExecutionAttemptArguments.Get(attempt.Attempt, attempt.ExecutionTime, attempt.Handled); + } // copy the args because these are pooled and in tests we want to preserve them - args = TelemetryEventArguments.Get(args.Source, args.EventName, args.Context, args.Outcome, args.Arguments); + args = TelemetryEventArguments.Get(args.Source, args.EventName, args.Context, args.Outcome, arguments); _callback(args); } }
Track execution time for retries and hedging attempts We need to extend `OnHedgingArguments` and `OnRetryArguments` with the `ExecutionTime` property that allows tracking how long each attempt took. Additionally, we should also introduce `ExecutionAttemptArguments` that tracks the execution info for both hedging and retries. We can then hook and additional telemetry for these events.
null
2023-06-19T13:06:14Z
0.2
['Polly.Extensions.Tests.Telemetry.ExecutionAttemptArgumentsTests.Get_Ok', 'Polly.Extensions.Tests.Utils.TelemetryUtilTests.AsBoxedInt_Ok', 'Polly.Extensions.Tests.Telemetry.ExecutionAttemptArgumentsTests.Ctor_Ok', 'Polly.Extensions.Tests.Utils.TelemetryUtilTests.AsBoxedPool_Ok', 'Polly.Extensions.Tests.Telemetry.ExecutionAttemptArgumentsTests.Return_EnsurePropertiesCleared']
['Polly.Core.Tests.Hedging.Controller.HedgingControllerTests.Pooling_Ok']
App-vNext/Polly
polly-1321
6fcf0f68a116868f18d5be97e32d7a442d85f140
diff --git a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md index 761ed6b8320..56839c5e0a1 100644 --- a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md +++ b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.MultipleStrategiesBenchmark-report-github.md @@ -9,7 +9,8 @@ Job=MediumRun Toolchain=InProcessEmitToolchain IterationCount=15 LaunchCount=2 WarmupCount=10 ``` -| Method | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio | -|--------------------------- |---------:|----------:|----------:|------:|-------:|----------:|------------:| -| ExecuteStrategyPipeline_V7 | 2.227 μs | 0.0077 μs | 0.0116 μs | 1.00 | 0.1106 | 2824 B | 1.00 | -| ExecuteStrategyPipeline_V8 | 1.750 μs | 0.0060 μs | 0.0084 μs | 0.79 | - | 40 B | 0.01 | +| Method | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio | +|------------------------------------- |---------:|----------:|----------:|------:|-------:|----------:|------------:| +| ExecuteStrategyPipeline_V7 | 2.269 μs | 0.0136 μs | 0.0204 μs | 1.00 | 0.1106 | 2824 B | 1.00 | +| ExecuteStrategyPipeline_V8 | 1.861 μs | 0.0111 μs | 0.0155 μs | 0.82 | - | 40 B | 0.01 | +| ExecuteStrategyPipeline_Telemetry_V8 | 2.402 μs | 0.0104 μs | 0.0156 μs | 1.06 | - | 40 B | 0.01 | diff --git a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.TelemetryBenchmark-report-github.md b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.TelemetryBenchmark-report-github.md index f16cd939b84..c3ab5b54ae1 100644 --- a/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.TelemetryBenchmark-report-github.md +++ b/bench/BenchmarkDotNet.Artifacts/results/Polly.Core.Benchmarks.TelemetryBenchmark-report-github.md @@ -1,6 +1,6 @@ ``` ini -BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.1702/22H2/2022Update/SunValley2), VM=Hyper-V +BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.1848/22H2/2022Update/SunValley2), VM=Hyper-V Intel Xeon Platinum 8370C CPU 2.80GHz, 1 CPU, 16 logical and 8 physical cores .NET SDK=7.0.304 [Host] : .NET 7.0.7 (7.0.723.27404), X64 RyuJIT AVX2 @@ -9,9 +9,9 @@ Job=MediumRun Toolchain=InProcessEmitToolchain IterationCount=15 LaunchCount=2 WarmupCount=10 ``` -| Method | Telemetry | Enrichment | Mean | Error | StdDev | Gen0 | Allocated | -|-------- |---------- |----------- |------------:|---------:|----------:|-------:|----------:| -| **Execute** | **False** | **False** | **80.13 ns** | **0.324 ns** | **0.486 ns** | **-** | **-** | -| **Execute** | **False** | **True** | **74.33 ns** | **0.286 ns** | **0.392 ns** | **-** | **-** | -| **Execute** | **True** | **False** | **494.33 ns** | **3.973 ns** | **5.698 ns** | **0.0029** | **72 B** | -| **Execute** | **True** | **True** | **1,157.27 ns** | **7.130 ns** | **10.450 ns** | **0.0286** | **728 B** | +| Method | Telemetry | Enrichment | Mean | Error | StdDev | Allocated | +|-------- |---------- |----------- |------------:|---------:|---------:|----------:| +| **Execute** | **False** | **False** | **80.27 ns** | **1.992 ns** | **2.920 ns** | **-** | +| **Execute** | **False** | **True** | **79.68 ns** | **1.324 ns** | **1.982 ns** | **-** | +| **Execute** | **True** | **False** | **750.41 ns** | **4.875 ns** | **6.673 ns** | **-** | +| **Execute** | **True** | **True** | **1,034.73 ns** | **4.941 ns** | **7.242 ns** | **-** | diff --git a/bench/Polly.Core.Benchmarks/MultipleStrategiesBenchmark.cs b/bench/Polly.Core.Benchmarks/MultipleStrategiesBenchmark.cs index b7d1bca8861..8fd1769a4f0 100644 --- a/bench/Polly.Core.Benchmarks/MultipleStrategiesBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/MultipleStrategiesBenchmark.cs @@ -1,20 +1,32 @@ +using System.Diagnostics.Metrics; + namespace Polly.Core.Benchmarks; public class MultipleStrategiesBenchmark { + private MeterListener? _meterListener; private object? _strategyV7; private object? _strategyV8; + private object? _strategyTelemetryV8; [GlobalSetup] public void Setup() { - _strategyV7 = Helper.CreateStrategyPipeline(PollyVersion.V7); - _strategyV8 = Helper.CreateStrategyPipeline(PollyVersion.V8); + _meterListener = MeteringUtil.ListenPollyMetrics(); + _strategyV7 = Helper.CreateStrategyPipeline(PollyVersion.V7, false); + _strategyV8 = Helper.CreateStrategyPipeline(PollyVersion.V8, false); + _strategyTelemetryV8 = Helper.CreateStrategyPipeline(PollyVersion.V8, true); } + [GlobalCleanup] + public void Cleanup() => _meterListener?.Dispose(); + [Benchmark(Baseline = true)] public ValueTask ExecuteStrategyPipeline_V7() => _strategyV7!.ExecuteAsync(PollyVersion.V7); [Benchmark] public ValueTask ExecuteStrategyPipeline_V8() => _strategyV8!.ExecuteAsync(PollyVersion.V8); + + [Benchmark] + public ValueTask ExecuteStrategyPipeline_Telemetry_V8() => _strategyTelemetryV8!.ExecuteAsync(PollyVersion.V8); } diff --git a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs index 23143f6e3fe..32f1d1fd19c 100644 --- a/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs +++ b/bench/Polly.Core.Benchmarks/TelemetryBenchmark.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging.Abstractions; using Polly.Extensions.Telemetry; using Polly.Telemetry; @@ -7,13 +8,22 @@ namespace Polly.Core.Benchmarks; public class TelemetryBenchmark { private ResilienceStrategy? _strategy; + private MeterListener? _meterListener; [GlobalSetup] public void Prepare() { _strategy = Build(new ResilienceStrategyBuilder()); + + if (Telemetry) + { + _meterListener = MeteringUtil.ListenPollyMetrics(); + } } + [GlobalCleanup] + public void Cleanup() => _meterListener?.Dispose(); + [Params(true, false)] public bool Telemetry { get; set; } @@ -72,5 +82,4 @@ protected override ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, TState> return callback(context, state); } } - } diff --git a/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs b/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs index 548b4e1cb88..8a549667e75 100644 --- a/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs +++ b/bench/Polly.Core.Benchmarks/Utils/Helper.MultipleStrategies.cs @@ -1,10 +1,11 @@ using System.Threading.RateLimiting; +using Microsoft.Extensions.Logging.Abstractions; namespace Polly.Core.Benchmarks.Utils; internal static partial class Helper { - public static object CreateStrategyPipeline(PollyVersion technology) => technology switch + public static object CreateStrategyPipeline(PollyVersion technology, bool telemetry) => technology switch { PollyVersion.V7 => Policy.WrapAsync( Policy.HandleResult(Failure).Or<InvalidOperationException>().AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(30), 10, TimeSpan.FromSeconds(5)), @@ -40,6 +41,11 @@ internal static partial class Helper _ => PredicateResult.False } }); + + if (telemetry) + { + builder.EnableTelemetry(NullLoggerFactory.Instance); + } }), _ => throw new NotSupportedException() }; diff --git a/bench/Polly.Core.Benchmarks/Utils/MeteringUtil.cs b/bench/Polly.Core.Benchmarks/Utils/MeteringUtil.cs new file mode 100644 index 00000000000..3a4245c6dbc --- /dev/null +++ b/bench/Polly.Core.Benchmarks/Utils/MeteringUtil.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Metrics; + +namespace Polly.Core.Benchmarks.Utils; + +internal class MeteringUtil +{ + public static MeterListener ListenPollyMetrics() + { + var meterListener = new MeterListener + { + InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name is "Polly") + { + listener.EnableMeasurementEvents(instrument); + } + } + }; + + meterListener.SetMeasurementEventCallback<int>(OnMeasurementRecorded); + meterListener.Start(); + + static void OnMeasurementRecorded<T>( + Instrument instrument, + T measurement, + ReadOnlySpan<KeyValuePair<string, object?>> tags, + object? state) + { + // do nothing + } + + return meterListener; + } +} diff --git a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs index b3ae0d1b5bc..ff3f7984ac0 100644 --- a/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs +++ b/src/Polly.Core/Telemetry/ResilienceStrategyTelemetry.cs @@ -38,7 +38,11 @@ public void Report<TArgs>(string eventName, ResilienceContext context, TArgs arg return; } - DiagnosticSource.Write(eventName, new TelemetryEventArguments(TelemetrySource, eventName, context, null, args!)); + var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, eventName, context, null, args!); + + DiagnosticSource.Write(eventName, telemetryArgs); + + TelemetryEventArguments.Return(telemetryArgs); } /// <summary> @@ -60,7 +64,11 @@ public void Report<TArgs, TResult>(string eventName, OutcomeArguments<TResult, T return; } - DiagnosticSource.Write(eventName, new TelemetryEventArguments(TelemetrySource, eventName, args.Context, args.Outcome.AsOutcome(), args.Arguments!)); + var telemetryArgs = TelemetryEventArguments.Get(TelemetrySource, eventName, args.Context, args.Outcome.AsOutcome(), args.Arguments!); + + DiagnosticSource.Write(eventName, telemetryArgs); + + TelemetryEventArguments.Return(telemetryArgs); } } diff --git a/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs b/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs new file mode 100644 index 00000000000..9d701004ecb --- /dev/null +++ b/src/Polly.Core/Telemetry/TelemetryEventArguments.Pool.cs @@ -0,0 +1,33 @@ +namespace Polly.Telemetry; + +public sealed partial record class TelemetryEventArguments +{ + private static readonly ObjectPool<TelemetryEventArguments> Pool = new(() => new TelemetryEventArguments(), args => + { + args.Source = null!; + args.EventName = null!; + args.Context = null!; + args.Outcome = default; + args.Arguments = null!; + }); + + internal static TelemetryEventArguments Get( + ResilienceTelemetrySource source, + string eventName, + ResilienceContext context, + Outcome<object>? outcome, + object arguments) + { + var args = Pool.Get(); + + args.Source = source; + args.EventName = eventName; + args.Context = context; + args.Outcome = outcome; + args.Arguments = arguments; + + return args; + } + + internal static void Return(TelemetryEventArguments args) => Pool.Return(args); +} diff --git a/src/Polly.Core/Telemetry/TelemetryEventArguments.cs b/src/Polly.Core/Telemetry/TelemetryEventArguments.cs index 320c33aa6e8..1c98f3145f2 100644 --- a/src/Polly.Core/Telemetry/TelemetryEventArguments.cs +++ b/src/Polly.Core/Telemetry/TelemetryEventArguments.cs @@ -5,17 +5,35 @@ namespace Polly.Telemetry; /// <summary> /// The arguments of the telemetry event. /// </summary> -/// <param name="Source">The source of the event.</param> -/// <param name="EventName">The event name.</param> -/// <param name="Context">The resilience context.</param> -/// <param name="Outcome">The outcome of an execution.</param> -/// <param name="Arguments">The arguments associated with the event.</param> [EditorBrowsable(EditorBrowsableState.Never)] -public sealed record class TelemetryEventArguments( - ResilienceTelemetrySource Source, - string EventName, - ResilienceContext Context, - Outcome<object>? Outcome, - object Arguments) +public sealed partial record class TelemetryEventArguments { + private TelemetryEventArguments() + { + } + + /// <summary> + /// Gets the source of the event. + /// </summary> + public ResilienceTelemetrySource Source { get; private set; } = null!; + + /// <summary> + /// Gets the event name. + /// </summary> + public string EventName { get; private set; } = null!; + + /// <summary> + /// Gets the resilience context. + /// </summary> + public ResilienceContext Context { get; private set; } = null!; + + /// <summary> + /// Gets the outcome of an execution. + /// </summary> + public Outcome<object>? Outcome { get; private set; } + + /// <summary> + /// Gets the arguments associated with the event. + /// </summary> + public object Arguments { get; private set; } = null!; } diff --git a/src/Polly.Core/Utils/ObjectPool.cs b/src/Polly.Core/Utils/ObjectPool.cs index b34ca97fa38..886e38a1dc8 100644 --- a/src/Polly.Core/Utils/ObjectPool.cs +++ b/src/Polly.Core/Utils/ObjectPool.cs @@ -14,6 +14,11 @@ internal sealed class ObjectPool<T> private T? _fastItem; private int _numItems; + public ObjectPool(Func<T> createFunc, Action<T> reset) + : this(createFunc, o => { reset(o); return true; }) + { + } + public ObjectPool(Func<T> createFunc, Func<T, bool> returnFunc) : this(_ => createFunc(), returnFunc) { diff --git a/src/Polly.Extensions/Telemetry/EnrichmentContext.Pool.cs b/src/Polly.Extensions/Telemetry/EnrichmentContext.Pool.cs index 60224e48c8a..fc03506a254 100644 --- a/src/Polly.Extensions/Telemetry/EnrichmentContext.Pool.cs +++ b/src/Polly.Extensions/Telemetry/EnrichmentContext.Pool.cs @@ -26,6 +26,7 @@ internal static EnrichmentContext Get(ResilienceContext resilienceContext, objec internal static void Return(EnrichmentContext context) { + Array.Clear(context._tagsArray, 0, context.Tags.Count); context.Tags.Clear(); ContextPool.Return(context); } diff --git a/src/Polly.Extensions/Telemetry/EnrichmentContext.cs b/src/Polly.Extensions/Telemetry/EnrichmentContext.cs index 51b54c2a111..6a0c8e5ba2a 100644 --- a/src/Polly.Extensions/Telemetry/EnrichmentContext.cs +++ b/src/Polly.Extensions/Telemetry/EnrichmentContext.cs @@ -5,6 +5,10 @@ namespace Polly.Extensions.Telemetry; /// </summary> public sealed partial class EnrichmentContext { + private const int InitialArraySize = 20; + + private KeyValuePair<string, object?>[] _tagsArray = new KeyValuePair<string, object?>[InitialArraySize]; + private EnrichmentContext() { } @@ -27,5 +31,24 @@ private EnrichmentContext() /// <summary> /// Gets the tags associated with the resilience event. /// </summary> - public ICollection<KeyValuePair<string, object?>> Tags { get; } = new List<KeyValuePair<string, object?>>(); + public IList<KeyValuePair<string, object?>> Tags { get; } = new List<KeyValuePair<string, object?>>(); + + internal ReadOnlySpan<KeyValuePair<string, object?>> TagsSpan + { + get + { + // stryker disable once equality : no means to test this + if (Tags.Count > _tagsArray.Length) + { + Array.Resize(ref _tagsArray, Tags.Count); + } + + for (int i = 0; i < Tags.Count; i++) + { + _tagsArray[i] = Tags[i]; + } + + return _tagsArray.AsSpan(0, Tags.Count); + } + } } diff --git a/src/Polly.Extensions/Telemetry/EnrichmentUtil.cs b/src/Polly.Extensions/Telemetry/EnrichmentUtil.cs index 5575337cf16..b63606d53a0 100644 --- a/src/Polly.Extensions/Telemetry/EnrichmentUtil.cs +++ b/src/Polly.Extensions/Telemetry/EnrichmentUtil.cs @@ -1,31 +1,19 @@ +using System.Collections.Generic; + namespace Polly.Extensions.Telemetry; internal static class EnrichmentUtil { - public static void Enrich( - ref TagList tags, - List<Action<EnrichmentContext>> enrichers, - ResilienceContext resilienceContext, - Outcome<object>? outcome, - object? resilienceArguments) + public static void Enrich(EnrichmentContext context, List<Action<EnrichmentContext>> enrichers) { if (enrichers.Count == 0) { return; } - var context = EnrichmentContext.Get(resilienceContext, resilienceArguments, outcome); - foreach (var enricher in enrichers) { enricher(context); } - - foreach (var pair in context.Tags) - { - tags.Add(pair.Key, pair.Value); - } - - EnrichmentContext.Return(context); } } diff --git a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs index 55e637fa36a..0f4a58bb38a 100644 --- a/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs +++ b/src/Polly.Extensions/Telemetry/ResilienceTelemetryDiagnosticSource.cs @@ -41,20 +41,26 @@ public override void Write(string name, object? value) private void MeterEvent(TelemetryEventArguments args) { - var source = args.Source; - var tags = new TagList + if (!Counter.Enabled) { - { ResilienceTelemetryTags.EventName, args.EventName }, - { ResilienceTelemetryTags.BuilderName, source.BuilderName }, - { ResilienceTelemetryTags.StrategyName, source.StrategyName }, - { ResilienceTelemetryTags.StrategyType, source.StrategyType }, - { ResilienceTelemetryTags.StrategyKey, source.BuilderProperties.GetValue(TelemetryUtil.StrategyKey, null!) }, - { ResilienceTelemetryTags.ResultType, args.Context.GetResultType() }, - { ResilienceTelemetryTags.ExceptionName, args.Outcome?.Exception?.GetType().FullName } - }; - - EnrichmentUtil.Enrich(ref tags, _enrichers, args.Context, args.Outcome, args.Arguments); - Counter.Add(1, tags); + return; + } + + var source = args.Source; + + var enrichmentContext = EnrichmentContext.Get(args.Context, args.Arguments, args.Outcome); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.EventName, args.EventName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.BuilderName, source.BuilderName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyName, source.StrategyName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyType, source.StrategyType)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyKey, source.BuilderProperties.GetValue(TelemetryUtil.StrategyKey, null!))); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ResultType, args.Context.GetResultType())); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ExceptionName, args.Outcome?.Exception?.GetType().FullName)); + EnrichmentUtil.Enrich(enrichmentContext, _enrichers); + + Counter.Add(1, enrichmentContext.TagsSpan); + + EnrichmentContext.Return(enrichmentContext); } private void LogEvent(TelemetryEventArguments args) diff --git a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs index 34b7b5a485d..b9c275ff246 100644 --- a/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs +++ b/src/Polly.Extensions/Telemetry/TelemetryResilienceStrategy.cs @@ -1,5 +1,6 @@ using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; +using Polly.Extensions.Telemetry; using Polly.Extensions.Utils; using Polly.Utils; @@ -71,26 +72,33 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, T duration.TotalMilliseconds, outcome.Exception); - var tags = new TagList - { - { ResilienceTelemetryTags.BuilderName, _builderName }, - { ResilienceTelemetryTags.StrategyKey, _strategyKey }, - { ResilienceTelemetryTags.ResultType, context.GetResultType() }, - { ResilienceTelemetryTags.ExceptionName, outcome.Exception?.GetType().FullName }, - { ResilienceTelemetryTags.ExecutionHealth, context.GetExecutionHealth() } - }; - - EnrichmentUtil.Enrich(ref tags, _enrichers, context, CreateOutcome(outcome), resilienceArguments: null); - - ExecutionDuration.Record(duration.TotalMilliseconds, tags); + RecordDuration(context, outcome, duration); return outcome; } - private static Outcome<object> CreateOutcome<TResult>(Outcome<TResult> outcome) => - outcome.HasResult ? - new Outcome<object>(outcome.Result) : - new Outcome<object>(outcome.Exception!); + private static Outcome<object> CreateOutcome<TResult>(Outcome<TResult> outcome) => outcome.HasResult ? + new Outcome<object>(outcome.Result) : + new Outcome<object>(outcome.Exception!); + + private void RecordDuration<TResult>(ResilienceContext context, Outcome<TResult> outcome, TimeSpan duration) + { + if (!ExecutionDuration.Enabled) + { + return; + } + + var enrichmentContext = EnrichmentContext.Get(context, null, CreateOutcome(outcome)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.BuilderName, _builderName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.StrategyKey, _strategyKey)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ResultType, context.GetResultType())); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ExceptionName, outcome.Exception?.GetType().FullName)); + enrichmentContext.Tags.Add(new(ResilienceTelemetryTags.ExecutionHealth, context.GetExecutionHealth())); + EnrichmentUtil.Enrich(enrichmentContext, _enrichers); + + ExecutionDuration.Record(duration.TotalMilliseconds, enrichmentContext.TagsSpan); + EnrichmentContext.Return(enrichmentContext); + } private object? ExpandOutcome<TResult>(ResilienceContext context, Outcome<TResult> outcome) {
diff --git a/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs b/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs new file mode 100644 index 00000000000..a75aa1cdb01 --- /dev/null +++ b/test/Polly.Core.Tests/Telemetry/TelemetryEventArgumentsTests.cs @@ -0,0 +1,39 @@ +using System; +using Polly.Telemetry; + +namespace Polly.Extensions.Tests.Telemetry; + +public class TelemetryEventArgumentsTests +{ + private readonly ResilienceTelemetrySource _source = new("builder", new ResilienceProperties(), "strategy", "type"); + + [Fact] + public void Get_Ok() + { + var context = ResilienceContext.Get(); + var args = TelemetryEventArguments.Get(_source, "ev", context, new Outcome<object>("dummy"), "arg"); + + args.Outcome!.Value.Result.Should().Be("dummy"); + args.Context.Should().Be(context); + args.EventName.Should().Be("ev"); + args.Source.Should().Be(_source); + args.Arguments.Should().BeEquivalentTo("arg"); + args.Context.Should().Be(context); + } + + [Fact] + public void Return_EnsurePropertiesCleared() + { + var context = ResilienceContext.Get(); + var args = TelemetryEventArguments.Get(_source, "ev", context, new Outcome<object>("dummy"), "arg"); + + TelemetryEventArguments.Return(args); + + args.Outcome.Should().BeNull(); + args.Context.Should().BeNull(); + args.EventName.Should().BeNull(); + args.Source.Should().BeNull(); + args.Arguments.Should().BeNull(); + args.Context.Should().BeNull(); + } +} diff --git a/test/Polly.Core.Tests/Utils/ObjectPoolTests.cs b/test/Polly.Core.Tests/Utils/ObjectPoolTests.cs index 738c7080aec..b9383df28c9 100644 --- a/test/Polly.Core.Tests/Utils/ObjectPoolTests.cs +++ b/test/Polly.Core.Tests/Utils/ObjectPoolTests.cs @@ -8,7 +8,7 @@ public class ObjectPoolTests public void GetAnd_ReturnObject_SameInstance() { // Arrange - var pool = new ObjectPool<object>(() => new object(), _ => true); + var pool = new ObjectPool<object>(() => new object(), _ => { }); var obj1 = pool.Get(); pool.Return(obj1); diff --git a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs index ed5983c14c5..2ebce931327 100644 --- a/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs +++ b/test/Polly.Extensions.Tests/Telemetry/ResilienceTelemetryDiagnosticSourceTests.cs @@ -151,50 +151,39 @@ public void WriteEvent_MeteringWithoutEnrichers_Ok(bool noOutcome, bool exceptio } } - [InlineData(true)] - [InlineData(false)] + [InlineData(1)] + [InlineData(100)] [Theory] - public void WriteEvent_MeteringWithEnrichers_Ok(bool noOutcome) + public void WriteEvent_MeteringWithEnrichers_Ok(int count) { + const int DefaultDimensions = 7; var telemetry = Create(enrichers => { enrichers.Add(context => { - if (noOutcome) + for (int i = 0; i < count; i++) { - context.Outcome.Should().BeNull(); + context.Tags.Add(new KeyValuePair<string, object?>($"custom-{i}", $"custom-{i}-value")); } - else - { - context.Outcome!.Value.Result.Should().Be(true); - } - - context.Context.Should().NotBeNull(); - context.Arguments.Should().BeOfType<TestArguments>(); - context.Tags.Add(new KeyValuePair<string, object?>("custom-1", "custom-1-value")); }); enrichers.Add(context => { - context.Tags.Add(new KeyValuePair<string, object?>("custom-2", "custom-2-value")); + context.Tags.Add(new KeyValuePair<string, object?>("other", "other-value")); }); }); - ReportEvent(telemetry, noOutcome ? null : new Outcome<object>(true)); - ReportEvent(telemetry, noOutcome ? null : new Outcome<object>(true)); + ReportEvent(telemetry, new Outcome<object>(true)); var events = GetEvents("resilience-events"); var ev = events[0]; - ev.Count.Should().Be(9); + ev.Count.Should().Be(DefaultDimensions + count + 1); + ev["other"].Should().Be("other-value"); - ev["custom-1"].Should().Be("custom-1-value"); - ev["custom-2"].Should().Be("custom-2-value"); - - ev = events[1]; - ev.Count.Should().Be(9); - - ev["custom-1"].Should().Be("custom-1-value"); - ev["custom-2"].Should().Be("custom-2-value"); + for (int i = 0; i < count; i++) + { + ev[$"custom-{i}"].Should().Be($"custom-{i}-value"); + } } [Fact] diff --git a/test/Polly.TestUtils/TestUtilities.cs b/test/Polly.TestUtils/TestUtilities.cs index 08eb7b849f0..540e83d4374 100644 --- a/test/Polly.TestUtils/TestUtilities.cs +++ b/test/Polly.TestUtils/TestUtilities.cs @@ -88,7 +88,7 @@ public static void ReportEvent( object arguments) #pragma warning restore S107 // Methods should not have too many parameters { - source.Write(eventName, new TelemetryEventArguments( + source.Write(eventName, TelemetryEventArguments.Get( new ResilienceTelemetrySource(builderName, builderProperties, strategyName, strategyType), eventName, context, @@ -110,6 +110,13 @@ private sealed class CallbackDiagnosticSource : DiagnosticSource public override bool IsEnabled(string name) => true; - public override void Write(string name, object? value) => _callback((TelemetryEventArguments)value!); + public override void Write(string name, object? value) + { + var args = (TelemetryEventArguments)value!; + + // copy the args because these are pooled and in tests we want to preserve them + args = TelemetryEventArguments.Get(args.Source, args.EventName, args.Context, args.Outcome, args.Arguments); + _callback(args); + } } }
Reduce allocations in telemetry Revealed in #1311 - Use pooling for `TelemetryEventArguments`
null
2023-06-19T09:04:24Z
0.2
['Polly.Extensions.Tests.Telemetry.TelemetryEventArgumentsTests.Return_EnsurePropertiesCleared', 'Polly.Extensions.Tests.Telemetry.TelemetryEventArgumentsTests.Get_Ok']
[]
App-vNext/Polly
polly-1316
488bc103fb6f8126aa528a52efd904f19c0d0183
diff --git a/src/Polly.Core/CircuitBreaker/CircuitBreakerStrategyOptions.cs b/src/Polly.Core/CircuitBreaker/CircuitBreakerStrategyOptions.cs index 10fd7e77888..4c0c539fe96 100644 --- a/src/Polly.Core/CircuitBreaker/CircuitBreakerStrategyOptions.cs +++ b/src/Polly.Core/CircuitBreaker/CircuitBreakerStrategyOptions.cs @@ -37,10 +37,16 @@ public abstract class CircuitBreakerStrategyOptions<TResult> : ResilienceStrateg /// Gets or sets the predicates for the circuit breaker. /// </summary> /// <remarks> - /// Defaults to <see langword="null"/>. This property is required. + /// Defaults to a delegate that handles circuit breaker on any exception except <see cref="OperationCanceledException"/>. + /// This property is required. /// </remarks> [Required] - public Func<OutcomeArguments<TResult, CircuitBreakerPredicateArguments>, ValueTask<bool>>? ShouldHandle { get; set; } + public Func<OutcomeArguments<TResult, CircuitBreakerPredicateArguments>, ValueTask<bool>> ShouldHandle { get; set; } = args => args.Exception switch + { + OperationCanceledException => PredicateResult.False, + Exception => PredicateResult.True, + _ => PredicateResult.False + }; /// <summary> /// Gets or sets the event that is raised when the circuit resets to a <see cref="CircuitState.Closed"/> state. diff --git a/src/Polly.Core/Hedging/HedgingStrategyOptions.TResult.cs b/src/Polly.Core/Hedging/HedgingStrategyOptions.TResult.cs index 44ec334f2b6..a448243f5e7 100644 --- a/src/Polly.Core/Hedging/HedgingStrategyOptions.TResult.cs +++ b/src/Polly.Core/Hedging/HedgingStrategyOptions.TResult.cs @@ -45,10 +45,16 @@ public class HedgingStrategyOptions<TResult> : ResilienceStrategyOptions /// Gets or sets the predicate that determines whether a hedging should be performed for a given result. /// </summary> /// <remarks> - /// This property is required. Defaults to <see langword="null"/>. + /// Defaults to a delegate that hedges on any exception except <see cref="OperationCanceledException"/>. + /// This property is required. /// </remarks> [Required] - public Func<OutcomeArguments<TResult, HandleHedgingArguments>, ValueTask<bool>>? ShouldHandle { get; set; } + public Func<OutcomeArguments<TResult, HandleHedgingArguments>, ValueTask<bool>> ShouldHandle { get; set; } = args => args.Exception switch + { + OperationCanceledException => PredicateResult.False, + Exception => PredicateResult.True, + _ => PredicateResult.False + }; /// <summary> /// Gets or sets the hedging action generator that creates hedged actions. diff --git a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs index a112556ef94..48ecd7c3347 100644 --- a/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs +++ b/src/Polly.Core/Retry/RetryStrategyOptions.TResult.cs @@ -61,10 +61,16 @@ public class RetryStrategyOptions<TResult> : ResilienceStrategyOptions /// Gets or sets an outcome predicate that is used to register the predicates to determine if a retry should be performed. /// </summary> /// <remarks> - /// Defaults to <see langword="null"/>. This property is required. + /// Defaults to a delegate that retries on any exception except <see cref="OperationCanceledException"/>. + /// This property is required. /// </remarks> [Required] - public Func<OutcomeArguments<TResult, ShouldRetryArguments>, ValueTask<bool>>? ShouldRetry { get; set; } + public Func<OutcomeArguments<TResult, ShouldRetryArguments>, ValueTask<bool>> ShouldRetry { get; set; } = args => args.Exception switch + { + OperationCanceledException => PredicateResult.False, + Exception => PredicateResult.True, + _ => PredicateResult.False + }; /// <summary> /// Gets or sets the generator instance that is used to calculate the time between retries.
diff --git a/test/Polly.Core.Tests/CircuitBreaker/AdvancedCircuitBreakerOptionsTests.cs b/test/Polly.Core.Tests/CircuitBreaker/AdvancedCircuitBreakerOptionsTests.cs index d6b5d99d791..2859a9c0887 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/AdvancedCircuitBreakerOptionsTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/AdvancedCircuitBreakerOptionsTests.cs @@ -17,7 +17,7 @@ public void Ctor_Defaults() options.OnOpened.Should().BeNull(); options.OnClosed.Should().BeNull(); options.OnHalfOpened.Should().BeNull(); - options.ShouldHandle.Should().BeNull(); + options.ShouldHandle.Should().NotBeNull(); options.StrategyType.Should().Be("CircuitBreaker"); options.StrategyName.Should().BeNull(); @@ -27,10 +27,21 @@ public void Ctor_Defaults() options.MinimumThroughput = 2; options.SamplingDuration = TimeSpan.FromMilliseconds(500); - options.ShouldHandle = _ => PredicateResult.True; ValidationHelper.ValidateObject(options, "Dummy."); } + [Fact] + public async Task ShouldHandle_EnsureDefaults() + { + var options = new AdvancedCircuitBreakerStrategyOptions(); + var args = new CircuitBreakerPredicateArguments(); + var context = ResilienceContext.Get(); + + (await options.ShouldHandle(new(context, new Outcome<object>("dummy"), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<object>(new OperationCanceledException()), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<object>(new InvalidOperationException()), args))).Should().Be(true); + } + [Fact] public void Ctor_Generic_Defaults() { @@ -43,7 +54,7 @@ public void Ctor_Generic_Defaults() options.OnOpened.Should().BeNull(); options.OnClosed.Should().BeNull(); options.OnHalfOpened.Should().BeNull(); - options.ShouldHandle.Should().BeNull(); + options.ShouldHandle.Should().NotBeNull(); options.StrategyType.Should().Be("CircuitBreaker"); options.StrategyName.Should().BeNull(); @@ -53,7 +64,6 @@ public void Ctor_Generic_Defaults() options.MinimumThroughput = 2; options.SamplingDuration = TimeSpan.FromMilliseconds(500); - options.ShouldHandle = _ => PredicateResult.True; ValidationHelper.ValidateObject(options, "Dummy."); } diff --git a/test/Polly.Core.Tests/CircuitBreaker/SimpleCircuitBreakerOptionsTests.cs b/test/Polly.Core.Tests/CircuitBreaker/SimpleCircuitBreakerOptionsTests.cs index b35968bade0..d60f7050984 100644 --- a/test/Polly.Core.Tests/CircuitBreaker/SimpleCircuitBreakerOptionsTests.cs +++ b/test/Polly.Core.Tests/CircuitBreaker/SimpleCircuitBreakerOptionsTests.cs @@ -16,7 +16,7 @@ public void Ctor_Defaults() options.OnOpened.Should().BeNull(); options.OnClosed.Should().BeNull(); options.OnHalfOpened.Should().BeNull(); - options.ShouldHandle.Should().BeNull(); + options.ShouldHandle.Should().NotBeNull(); options.StrategyType.Should().Be("CircuitBreaker"); options.StrategyName.Should().BeNull(); @@ -24,10 +24,21 @@ public void Ctor_Defaults() options.FailureThreshold = 1; options.BreakDuration = TimeSpan.FromMilliseconds(500); - options.ShouldHandle = _ => PredicateResult.True; ValidationHelper.ValidateObject(options, "Dummy."); } + [Fact] + public async Task ShouldHandle_EnsureDefaults() + { + var options = new SimpleCircuitBreakerStrategyOptions(); + var args = new CircuitBreakerPredicateArguments(); + var context = ResilienceContext.Get(); + + (await options.ShouldHandle(new(context, new Outcome<object>("dummy"), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<object>(new OperationCanceledException()), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<object>(new InvalidOperationException()), args))).Should().Be(true); + } + [Fact] public void Ctor_Generic_Defaults() { @@ -38,7 +49,7 @@ public void Ctor_Generic_Defaults() options.OnOpened.Should().BeNull(); options.OnClosed.Should().BeNull(); options.OnHalfOpened.Should().BeNull(); - options.ShouldHandle.Should().BeNull(); + options.ShouldHandle.Should().NotBeNull(); options.StrategyType.Should().Be("CircuitBreaker"); options.StrategyName.Should().BeNull(); diff --git a/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs b/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs index c7a4a3ba50e..59b4e5d6019 100644 --- a/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs +++ b/test/Polly.Core.Tests/Hedging/HedgingStrategyOptionsTests.cs @@ -12,7 +12,7 @@ public async Task Ctor_EnsureDefaults() var options = new HedgingStrategyOptions<int>(); options.StrategyType.Should().Be("Hedging"); - options.ShouldHandle.Should().BeNull(); + options.ShouldHandle.Should().NotBeNull(); options.HedgingActionGenerator.Should().NotBeNull(); options.HedgingDelay.Should().Be(TimeSpan.FromSeconds(2)); options.MaxHedgedAttempts.Should().Be(2); @@ -23,6 +23,18 @@ public async Task Ctor_EnsureDefaults() (await action()).Result.Should().Be(99); } + [Fact] + public async Task ShouldHandle_EnsureDefaults() + { + var options = new HedgingStrategyOptions<int>(); + var args = new HandleHedgingArguments(); + var context = ResilienceContext.Get(); + + (await options.ShouldHandle(new(context, new Outcome<int>(0), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<int>(new OperationCanceledException()), args))).Should().Be(false); + (await options.ShouldHandle(new(context, new Outcome<int>(new InvalidOperationException()), args))).Should().Be(true); + } + [Fact] public void Validation() { diff --git a/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs b/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs index 544ec879af2..7242cb10b62 100644 --- a/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs +++ b/test/Polly.Core.Tests/Retry/RetryStrategyOptionsTests.cs @@ -12,7 +12,7 @@ public void Ctor_Ok() var options = new RetryStrategyOptions<int>(); options.StrategyType.Should().Be("Retry"); - options.ShouldRetry.Should().BeNull(); + options.ShouldRetry.Should().NotBeNull(); options.RetryDelayGenerator.Should().BeNull(); @@ -23,6 +23,18 @@ public void Ctor_Ok() options.BaseDelay.Should().Be(TimeSpan.FromSeconds(2)); } + [Fact] + public async Task ShouldHandle_EnsureDefaults() + { + var options = new RetryStrategyOptions<int>(); + var args = new ShouldRetryArguments(0); + var context = ResilienceContext.Get(); + + (await options.ShouldRetry(new(context, new Outcome<int>(0), args))).Should().Be(false); + (await options.ShouldRetry(new(context, new Outcome<int>(new OperationCanceledException()), args))).Should().Be(false); + (await options.ShouldRetry(new(context, new Outcome<int>(new InvalidOperationException()), args))).Should().Be(true); + } + [Fact] public void InvalidOptions() {
[V8] ShouldHandle, ShouldRetry etc. predicates should have reasonable defaults Currently when using the new API, it is required to specify `ShouldHandle` predicate for CircuitBreaker, `ShouldRetry` predicate for Retry and probably more. I think it would be beneficial to have some reasonable default predicates so that users don't need to specify it every time. For example I would consider reasonable default to handle all requests that throw exceptions (other than `OperationCancelledException`). Also it would be nice to have the defaults for Http scenarios (handling 5xx requests), because these will be common as well.
Yeah, I agree here, let's address this in alpha2. Would provide a nice out-of-box experience.
2023-06-16T14:01:05Z
0.2
['Polly.Core.Tests.CircuitBreaker.AdvancedCircuitBreakerOptionsTests.ShouldHandle_EnsureDefaults']
['Polly.Core.Tests.CircuitBreaker.AdvancedCircuitBreakerOptionsTests.Ctor_Defaults', 'Polly.Core.Tests.CircuitBreaker.AdvancedCircuitBreakerOptionsTests.InvalidOptions_Validate', 'Polly.Core.Tests.CircuitBreaker.AdvancedCircuitBreakerOptionsTests.Ctor_Generic_Defaults']
autofac/Autofac
autofac__autofac-1428
b222d0f635442dde23e219f14b2132932b028e81
diff --git a/src/Autofac/Core/NamedPropertyParameter.cs b/src/Autofac/Core/NamedPropertyParameter.cs index f94c74a7c..1723fad32 100644 --- a/src/Autofac/Core/NamedPropertyParameter.cs +++ b/src/Autofac/Core/NamedPropertyParameter.cs @@ -22,7 +22,7 @@ public class NamedPropertyParameter : ConstantParameter /// </summary> /// <param name="name">The name of the property.</param> /// <param name="value">The property value.</param> - public NamedPropertyParameter(string name, object value) + public NamedPropertyParameter(string name, object? value) : base(value, pi => { return pi.TryGetDeclaringProperty(out PropertyInfo? prop) && diff --git a/src/Autofac/NamedParameter.cs b/src/Autofac/NamedParameter.cs index 421301d1d..e8b38eeee 100644 --- a/src/Autofac/NamedParameter.cs +++ b/src/Autofac/NamedParameter.cs @@ -45,7 +45,7 @@ public class NamedParameter : ConstantParameter /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="value">The parameter value.</param> - public NamedParameter(string name, object value) + public NamedParameter(string name, object? value) : base(value, pi => pi.Name == name) => Name = Enforce.ArgumentNotNullOrEmpty(name, "name"); } diff --git a/src/Autofac/PositionalParameter.cs b/src/Autofac/PositionalParameter.cs index 92be04335..ce4db4c34 100644 --- a/src/Autofac/PositionalParameter.cs +++ b/src/Autofac/PositionalParameter.cs @@ -46,7 +46,7 @@ public class PositionalParameter : ConstantParameter /// </summary> /// <param name="position">The zero-based position of the parameter.</param> /// <param name="value">The parameter value.</param> - public PositionalParameter(int position, object value) + public PositionalParameter(int position, object? value) : base(value, pi => pi.Position == position && (pi.Member is ConstructorInfo)) { if (position < 0) diff --git a/src/Autofac/RegistrationExtensions.cs b/src/Autofac/RegistrationExtensions.cs index 18a2c1c1b..515a8d352 100644 --- a/src/Autofac/RegistrationExtensions.cs +++ b/src/Autofac/RegistrationExtensions.cs @@ -621,7 +621,7 @@ public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> WithProperty<TLimit, TReflectionActivatorData, TStyle>( this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration, string propertyName, - object propertyValue) + object? propertyValue) where TReflectionActivatorData : ReflectionActivatorData { return registration.WithProperty(new NamedPropertyParameter(propertyName, propertyValue)); @@ -684,11 +684,6 @@ public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> throw new ArgumentNullException(nameof(propertyExpression)); } - if (propertyValue == null) - { - throw new ArgumentNullException(nameof(propertyValue)); - } - var propertyInfo = (propertyExpression.Body as MemberExpression)?.Member as PropertyInfo ?? throw new ArgumentOutOfRangeException(nameof(propertyExpression), RegistrationExtensionsResources.ExpressionDoesNotReferToProperty); return registration.WithProperty(new NamedPropertyParameter(propertyInfo.Name, propertyValue)); }
diff --git a/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs b/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs index 0165a495f..b95b74bc8 100644 --- a/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs +++ b/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs @@ -398,6 +398,39 @@ public void DecoratedInstanceWithPropertyInjectionAllowingCircularReferencesStil instance.AssertProp(); } + [Fact] + public void WithPropertyDelegateAllowsNullValue() + { + // Issue 1427: WithProperty should consistently allow null values. + var builder = new ContainerBuilder(); + builder.RegisterType<HasPublicSetter>().WithProperty(t => t.Val, null); + var container = builder.Build(); + var instance = container.Resolve<HasPublicSetter>(); + Assert.Null(instance.Val); + } + + [Fact] + public void WithPropertyNamedAllowsNullValue() + { + // Issue 1427: WithProperty should consistently allow null values. + var builder = new ContainerBuilder(); + builder.RegisterType<HasPublicSetter>().WithProperty(nameof(HasPublicSetter.Val), null); + var container = builder.Build(); + var instance = container.Resolve<HasPublicSetter>(); + Assert.Null(instance.Val); + } + + [Fact] + public void WithPropertyTypedAllowsNullValue() + { + // Issue 1427: WithProperty should consistently allow null values. + var builder = new ContainerBuilder(); + builder.RegisterType<HasPublicSetter>().WithProperty(TypedParameter.From<string>(null)); + var container = builder.Build(); + var instance = container.Resolve<HasPublicSetter>(); + Assert.Null(instance.Val); + } + private class ConstructorParamNotAttachedToProperty { [SuppressMessage("SA1401", "SA1401")]
Inconsistent behavior of different RegistrationExtensions.WithProperty overloads regarding nullable properties ## Describe the Bug The `WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue)` throws when `propertyValue` is null, regardless whether `TProperty` is nullable. Nullable analysis does not flag an issue when passing `null`. The relevant check is here: https://github.com/autofac/Autofac/blob/b222d0f635442dde23e219f14b2132932b028e81/src/Autofac/RegistrationExtensions.cs#L687-L690 All other `WithProperty` overloads accept `null` or `null!`. ## Steps to Reproduce <!-- Tell us how to reproduce the issue. Ideally provide a failing unit test. --> ```c# using Autofac; using System; using Xunit; namespace Tests; public class WithPropertyTests { private class Test { public required int? Property { get; init; } } [Fact] public void WithProperty_NullPropertyValue() { var builder = new ContainerBuilder(); builder.RegisterType<Test>() .WithProperty(nameof(Test.Property), null!) .AsSelf(); builder.RegisterType<Test>() .WithProperty(new TypedParameter(typeof(int?), null)) .AsSelf(); Exception? exception = Record.Exception(() => builder.RegisterType<Test>() .WithProperty(t => t.Property, null) .AsSelf()); Assert.Null(exception); } } ``` ## Expected Behavior I would expect `WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue)` to accept a `null` `propertyValue` when `TProperty` is nullable, similar to the other overloads. ## Exception with Stack Trace ```text Xunit.Sdk.NullException Assert.Null() Failure: Value is not null Expected: null Actual: System.ArgumentNullException: Value cannot be null. (Parameter 'propertyValue') at Autofac.RegistrationExtensions.WithProperty[TLimit,TReflectionActivatorData,TStyle,TProperty](IRegistrationBuilder`3 registration, Expression`1 propertyExpression, TProperty propertyValue) at Tests.WithPropertyTests.<>c__DisplayClass1_0.<WithProperty_NullPropertyValue>b__0() in […]\Tests\WithPropertyTests.cs:line 27 at Xunit.Record.Exception(Func`1 testCode) in /_/src/xunit.core/Record.cs:line 47 at Tests.WithPropertyTests.WithProperty_NullPropertyValue() in […]\Tests\WithPropertyTests.cs:line 30 at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr) ``` ## Dependency Versions Autofac: 7.1.0 Inconsistent behavior of different RegistrationExtensions.WithProperty overloads regarding nullable properties ## Describe the Bug The `WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue)` throws when `propertyValue` is null, regardless whether `TProperty` is nullable. Nullable analysis does not flag an issue when passing `null`. The relevant check is here: https://github.com/autofac/Autofac/blob/b222d0f635442dde23e219f14b2132932b028e81/src/Autofac/RegistrationExtensions.cs#L687-L690 All other `WithProperty` overloads accept `null` or `null!`. ## Steps to Reproduce <!-- Tell us how to reproduce the issue. Ideally provide a failing unit test. --> ```c# using Autofac; using System; using Xunit; namespace Tests; public class WithPropertyTests { private class Test { public required int? Property { get; init; } } [Fact] public void WithProperty_NullPropertyValue() { var builder = new ContainerBuilder(); builder.RegisterType<Test>() .WithProperty(nameof(Test.Property), null!) .AsSelf(); builder.RegisterType<Test>() .WithProperty(new TypedParameter(typeof(int?), null)) .AsSelf(); Exception? exception = Record.Exception(() => builder.RegisterType<Test>() .WithProperty(t => t.Property, null) .AsSelf()); Assert.Null(exception); } } ``` ## Expected Behavior I would expect `WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue)` to accept a `null` `propertyValue` when `TProperty` is nullable, similar to the other overloads. ## Exception with Stack Trace ```text Xunit.Sdk.NullException Assert.Null() Failure: Value is not null Expected: null Actual: System.ArgumentNullException: Value cannot be null. (Parameter 'propertyValue') at Autofac.RegistrationExtensions.WithProperty[TLimit,TReflectionActivatorData,TStyle,TProperty](IRegistrationBuilder`3 registration, Expression`1 propertyExpression, TProperty propertyValue) at Tests.WithPropertyTests.<>c__DisplayClass1_0.<WithProperty_NullPropertyValue>b__0() in […]\Tests\WithPropertyTests.cs:line 27 at Xunit.Record.Exception(Func`1 testCode) in /_/src/xunit.core/Record.cs:line 47 at Tests.WithPropertyTests.WithProperty_NullPropertyValue() in […]\Tests\WithPropertyTests.cs:line 30 at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor) at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr) ``` ## Dependency Versions Autofac: 7.1.0
This is sort of an interesting thing where I'm not entirely sure what the right answer is. The reason I say that is that, generally speaking, we don't allow Autofac to "resolve null values." For example, you can't do this: ```csharp builder.RegisterInstance<IService>(null); ``` And if you have property injection enabled on something and say `container.InjectProperties(obj);` then Autofac will never intentionally inject a null value - you'd get an exception instead. On the other hand, as you point out, it doesn't look like things are consistent from a _parameter_ perspective - that we sometimes do allow null as a provided parameter and sometimes don't. And I agree, it should be consistent. My question is - in which direction should parameters be made consistent? Should we stop null everywhere (why are folks intentionally injecting a null?) or should we allow null everywhere ("I want to intentionally set this one parameter to null to force a particular constructor/property behavior")? On first glance it looks like most of the parameter mechanisms allow for null, which means making it consistently allow null for explicitly provided parameters would be the least breaking way to go, though it could be argued this is inconsistent with the nature of _resolved_ values since you can't resolve a null. @alistairjevans what do you think? I fully understand your concerns. In our case, we have a class with various required properties. We want some of these properties to be injected implicitly from other registrations and provide the missing properties using `WithProperty`. The missing properties don’t make sense to be registered generally. We have this issue with a nullable enum property. I think if the majority of the `WithProperty` overloads let you pass null, they probably all should. I consider `WithProperty` to be relatively advanced, so if users have a usecase where they have a property they explicitly want nulled, I'm ok with it. That differs from a scenario where you say "Autofac, resolve and provide that value for me", in which case that can never be null. Sounds good. I'll see if I can get a PR in to consistently allow null for this, unless someone beats me to it. This is sort of an interesting thing where I'm not entirely sure what the right answer is. The reason I say that is that, generally speaking, we don't allow Autofac to "resolve null values." For example, you can't do this: ```csharp builder.RegisterInstance<IService>(null); ``` And if you have property injection enabled on something and say `container.InjectProperties(obj);` then Autofac will never intentionally inject a null value - you'd get an exception instead. On the other hand, as you point out, it doesn't look like things are consistent from a _parameter_ perspective - that we sometimes do allow null as a provided parameter and sometimes don't. And I agree, it should be consistent. My question is - in which direction should parameters be made consistent? Should we stop null everywhere (why are folks intentionally injecting a null?) or should we allow null everywhere ("I want to intentionally set this one parameter to null to force a particular constructor/property behavior")? On first glance it looks like most of the parameter mechanisms allow for null, which means making it consistently allow null for explicitly provided parameters would be the least breaking way to go, though it could be argued this is inconsistent with the nature of _resolved_ values since you can't resolve a null. @alistairjevans what do you think? I fully understand your concerns. In our case, we have a class with various required properties. We want some of these properties to be injected implicitly from other registrations and provide the missing properties using `WithProperty`. The missing properties don’t make sense to be registered generally. We have this issue with a nullable enum property. I think if the majority of the `WithProperty` overloads let you pass null, they probably all should. I consider `WithProperty` to be relatively advanced, so if users have a usecase where they have a property they explicitly want nulled, I'm ok with it. That differs from a scenario where you say "Autofac, resolve and provide that value for me", in which case that can never be null. Sounds good. I'll see if I can get a PR in to consistently allow null for this, unless someone beats me to it.
2024-09-15T23:15:01Z
0.1
['Autofac.Specification.Test.Features.PropertyInjectionTests.WithPropertyNamedAllowsNullValue', 'Autofac.Specification.Test.Features.PropertyInjectionTests.WithPropertyDelegateAllowsNullValue', 'Autofac.Specification.Test.Features.PropertyInjectionTests.WithPropertyTypedAllowsNullValue']
['Autofac.Specification.Test.Features.PropertyInjectionTests.ParameterForConstructorShouldNotAttachToProperty', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectPropertiesOverwritesSetProperties', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredCanSetBaseClassProperties', 'Autofac.Specification.Test.Features.PropertyInjectionTests.DecoratedInstanceWithPropertyInjectionAllowingCircularReferencesStillInjects', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredUsingDelegateSelector', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredOverwritesSetProperties', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredDoesNotSetStaticSetter', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredUsingPropertySelector', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesNotSetIfNotSpecified', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredSetsWriteOnlyPublicProperty', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertyInjectionPassesNamedParameterOfTheInstanceTypeBeingInjectedOnto', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectUnsetPropertiesUsesPublicOnly', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectPropertiesWithPropertySelectorAllowsPrivateSet', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredDoesNotSetNonPublicSetter', 'Autofac.Specification.Test.Features.PropertyInjectionTests.SetterInjectionPrivateGet', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredUsingInlineDelegate', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertySpecifiedAsResolveParameterWhenAutowiredMayBeBothConstructorAndProperty', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectUnsetPropertiesSkipsSetProperties', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectPropertiesAllowsSeparationOfConstructorAndPropertyParameters', 'Autofac.Specification.Test.Features.PropertyInjectionTests.InjectPropertiesWithDelegateSelectorAllowsPrivateSet', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredSetsUnsetPublicSetter', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertiesAutowiredWithDelegateFactory', 'Autofac.Specification.Test.Features.PropertyInjectionTests.PropertySpecifiedAsResolveParameterWhenAutowired', 'Autofac.Specification.Test.Features.PropertyInjectionTests.EnumPropertiesCanBeAutowired']
autofac/Autofac
autofac__autofac-1424
488294e8eab11ff1381f70aa9018b18fe06dd6ac
diff --git a/src/Autofac/Features/Decorators/DecoratorMiddleware.cs b/src/Autofac/Features/Decorators/DecoratorMiddleware.cs index 4521c8d05..ef0c398c1 100644 --- a/src/Autofac/Features/Decorators/DecoratorMiddleware.cs +++ b/src/Autofac/Features/Decorators/DecoratorMiddleware.cs @@ -77,7 +77,15 @@ public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> return; } - var serviceParameter = new TypedParameter(serviceType, context.DecoratorContext.CurrentInstance); + // Issue 1330: A component registered with multiple services may need to + // be decorated when resolved in a different context. Lambda registered + // decorators assume an exact typed parameter but the multi-service + // registered decorators need the resolved version that can determine + // compatibility by casting. + var typedServiceParameter = new TypedParameter(serviceType, context.DecoratorContext.CurrentInstance); + var compatibleServiceParameter = new ResolvedParameter( + (pi, ctx) => serviceType.IsAssignableFrom(pi.ParameterType), + (pi, ctx) => context.DecoratorContext.CurrentInstance); var contextParameter = new TypedParameter(typeof(IDecoratorContext), context.DecoratorContext); Parameter[] resolveParameters; @@ -86,11 +94,11 @@ public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> if (parameterCount == 0) { - resolveParameters = new Parameter[] { serviceParameter, contextParameter }; + resolveParameters = new Parameter[] { typedServiceParameter, compatibleServiceParameter, contextParameter }; } else { - resolveParameters = new Parameter[parameterCount + 2]; + resolveParameters = new Parameter[parameterCount + 3]; var idx = 0; foreach (var existing in context.Parameters) @@ -99,7 +107,8 @@ public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> idx++; } - resolveParameters[idx++] = serviceParameter; + resolveParameters[idx++] = typedServiceParameter; + resolveParameters[idx++] = compatibleServiceParameter; resolveParameters[idx++] = contextParameter; }
diff --git a/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs b/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs index b64e07910..d9391c012 100644 --- a/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs +++ b/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs @@ -864,6 +864,35 @@ public void CanApplyDecoratorOnTypeThatImplementsTwoInterfaces() Assert.IsType<TransactionalCommandHandlerDecorator<CreateLocation>>(instance); } + [Fact] + public void ResolvesMultipleDecoratedServicesWhenResolvedByOtherServices() + { + // Issue 1330: A component registered with multiple services may need to + // be decorated when resolved in a different context. + var builder = new ContainerBuilder(); + builder.RegisterGeneric(typeof(ImplementorA<>)).As(typeof(IDecoratedService<>)).As(typeof(IService<>)); + builder.RegisterGeneric(typeof(ImplementorB<>)).As(typeof(IDecoratedService<>)).As(typeof(IService<>)); + builder.RegisterGenericDecorator(typeof(DecoratorA<>), typeof(IService<>)); + var container = builder.Build(); + + var services = container.Resolve<IEnumerable<IService<int>>>(); + + Assert.Collection( + services, + s => + { + var ds = s as IDecoratedService<int>; + Assert.IsType<DecoratorA<int>>(ds); + Assert.IsType<ImplementorA<int>>(ds.Decorated); + }, + s => + { + var ds = s as IDecoratedService<int>; + Assert.IsType<DecoratorA<int>>(ds); + Assert.IsType<ImplementorB<int>>(ds.Decorated); + }); + } + private interface ICommandHandler<T> { void Handle(T command);
[Autofac 6.4.0]: RegisterGenericDecorator() resolves incorrect instance for the decorated type ## Describe the Bug When I register a generic decorator for my command handlers with `RegisterGenericDecorator()` and then try to resolve all command handlers by `container.Resolve(IEnumerable<IHandler<Command>>)`, the returned decorators all decorate the same instance. ## Steps to Reproduce full code [here](https://github.com/ViktorDolezel/AutofacDecorators/blob/master/Program.cs) ```c# [TestFixture] public class ReproTest { [Test] public void ResolveAllDecoratedCommandHandlers_IsSuccessful() { //Arrange var builder = new ContainerBuilder(); builder.RegisterType(typeof(CommandHandler1)) .As(typeof(ICommandHandler<Command>)) .As(typeof(IHandler<Command>)); builder.RegisterType(typeof(CommandHandler2)) .As(typeof(ICommandHandler<Command>)) .As(typeof(IHandler<Command>)); builder.RegisterGenericDecorator( typeof(CommandHandlerDecorator<>), typeof(IHandler<>), context => context.ImplementationType.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICommandHandler<>)) ); var container = builder.Build(); //Act var commandHandlers = ((IEnumerable<IHandler<Command>>)container.Resolve(typeof(IEnumerable<IHandler<Command>>))).ToList(); //Assert Assert.AreEqual( ((CommandHandlerDecorator<Command>)commandHandlers[0]).Decorated.GetType(), typeof(CommandHandler1)); //fails, decorated is typeof(CommandHandler2) Assert.AreEqual( ((CommandHandlerDecorator<Command>)commandHandlers[1]).Decorated.GetType(), typeof(CommandHandler2)); } } interface IRequest { } interface IHandler<in TRequest> where TRequest : IRequest { public void Handle(TRequest request); } interface ICommand: IRequest { } interface ICommandHandler<in TCommand>: IHandler<TCommand> where TCommand: ICommand { } class Command : ICommand { } class CommandHandler1 : ICommandHandler<Command> { public void Handle(Command command) => Console.WriteLine("CommandHandler1"); } class CommandHandler2 : ICommandHandler<Command> { public void Handle(Command command) => Console.WriteLine("CommandHandler2"); } class CommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> where TCommand : ICommand { public ICommandHandler<TCommand> Decorated { get; } public CommandHandlerDecorator(ICommandHandler<TCommand> decorated) => Decorated = decorated; public void Handle(TCommand request) { Console.WriteLine($"Command Decorator for {Decorated.GetType().FullName}"); Decorated.Handle(request); } } ``` ## Expected Behavior the above unit test should pass: Without using decorators, `container.Resolve<IEnumerable<IHandler<Command>>()` returns expected `{ CommandHandler1, CommandHandler2 }`. With decorators, I'm expecting `{ CommandHandlerDecorator(CommandHandler1), CommandHandlerDecorator(CommandHandler2) }` but getting `{ CommandHandlerDecorator(CommandHandler2), CommandHandlerDecorator(CommandHandler2) }`. ## Dependency Versions Autofac: 6.4.0 ## Additional Info This was encountered with the MediatR library where MediatR works on its base interface `IRequest`. I have control over the registration part (the "Arrange" section in the unit test) but not how MediatR resolves the command handlers. In other words, the following solutions would not solve my issue: - Resolve by calling `Resolve(typeof(IEnumerable<ICommandHandler<Command>>)` rather than `Resolve(typeof(IEnumerable<IHandler<Command>>)` [_no control over that_] - Get rid of `ICommand` and `IQuery` [_but I needz them! for example, the `UnitOfWorkCommandHandlerDecorator` should only apply to CommandHandlers_] - ditch MediatR - use `IPipelineBehavior` of MediatR instead [_the problem is present for `MediatR.INofitication`s as well and those don't support pipelines_] (thank you for your time, you are appreciated!)
While I've not had the time to repro this or anything, it seems like the important aspect here is the `IEnumerable<T>` part. It's not that the decorator isn't decorating the right type _all the time_, it's that if you resolve _a list of all the handlers_ (`IEnumerable<T>`), that's when you see the behavior. It also means this line from the issue: > Without using decorators, `container.Resolve<IHandler<Command>>()` returns expected `{ CommandHandler1, CommandHandler2 }`. ...is actually somewhat incorrect and should be: > Without using decorators, `container.Resolve<IEnumerable<IHandler<Command>>>()` returns expected `{ CommandHandler1, CommandHandler2 }`. Again, that `IEnumerable<T>` is super key. Sir, you are correct, nice catch! I fixed it in the **Expected Behavior** section. Here's the corresponding _passing_ test from my [repo](https://github.com/ViktorDolezel/AutofacDecorators/blob/master/Program.cs) (without the decorator). ```csharp [Test] public void ResolveAllCommandHandlers_IsSuccessful() { //Arrange var builder = new ContainerBuilder(); builder.RegisterType(typeof(CommandHandler1)) .As(typeof(ICommandHandler<Command>)) .As(typeof(IHandler<Command>)); builder.RegisterType(typeof(CommandHandler2)) .As(typeof(ICommandHandler<Command>)) .As(typeof(IHandler<Command>)); var container = builder.Build(); //Act var commandHandlers = ((IEnumerable<IHandler<Command>>)container.Resolve(typeof(IEnumerable<IHandler<Command>>))).ToList(); //Assert Assert.AreEqual(commandHandlers[0].GetType(), typeof(CommandHandler1)); Assert.AreEqual(commandHandlers[1].GetType(), typeof(CommandHandler2)); } ``` And yes, `IEnumerable<T>` seems to be the issue. I started looking at this and tried adding a failing test using our test types in the [OpenGenericDecoratorTests](https://github.com/autofac/Autofac/blob/develop/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs) fixture. I wasn't able to replicate the issue. ```c# [Fact] public void CanResolveMultipleClosedGenericDecoratedServices() { var builder = new ContainerBuilder(); builder.RegisterType<StringImplementorA>().As<IDecoratedService<string>>(); builder.RegisterType<StringImplementorB>().As<IDecoratedService<string>>(); builder.RegisterGenericDecorator(typeof(DecoratorA<>), typeof(IDecoratedService<>)); var container = builder.Build(); var services = container.Resolve<IEnumerable<IDecoratedService<string>>>(); // This passes - the internal implementations are different types as expected. Assert.Collection( services, s => { Assert.IsType<DecoratorA<string>>(s); Assert.IsType<StringImplementorA>(s.Decorated); }, s => { Assert.IsType<DecoratorA<string>>(s); Assert.IsType<StringImplementorB>(s.Decorated); }); } public interface IDecoratedService<T> { IDecoratedService<T> Decorated { get; } } public class StringImplementorA : IDecoratedService<string> { public IDecoratedService<string> Decorated => this; } public class StringImplementorB : IDecoratedService<string> { public IDecoratedService<string> Decorated => this; } public class DecoratorA<T> : IDecoratedService<T> { public DecoratorA(IDecoratedService<T> decorated) { Decorated = decorated; } public IDecoratedService<T> Decorated { get; } } ``` I started looking at your repro, but it seems like there is _a lot_ in there. For example, I don't know that `IRequest` needs to be in there. I'm not sure why the repro needs to have things registered as both `ICommandHandler<T>` _and_ `IHandler<T>` (unless that's part of what makes it fail?). In order to really dig in here, I need the repro simplified a lot. - Remove the "passing" tests. I'm glad they're passing, but they also confuse the issue. - Remove any assembly scanning. - Remove any types that are not directly involved in observing the failure. Interfaces that implement other interfaces. Base types that are used in covariant/contravarient constraints (`IGeneric<in T>`, `IGeneric<out T>`). - Use the specific assertions with expected/actual in the right spot. For example, instead of asserting if types are equal, [`Assert.IsInstanceOf(Type expected, Type actual)`](https://docs.nunit.org/articles/nunit/writing-tests/assertions/classic-assertions/Assert.IsInstanceOf.html). While this one seems a little nitpicky, what I'm trying to do is make sure there's not something weird going on with equality checking and also make sure expected and actual are reported properly so we know what we're actually looking for. (Right now, the expected and actual are in the wrong spots so will report incorrectly.) Reducing the repro to the absolute minimum helps because it points us at very specific things to look at. With the more complex repro and all the additional types, it's hard to know if it's a covariant/contravariant problem, a registration problem, a problem that happens only if you register a component `As<T>` two different services, or what. Post the complete, minified repro here in this issue (not in a remote repo) and I can come back and revisit. Hi, thanks for looking into it. Here's a failing test that can be added to the [OpenGenericDecoratorTests](https://github.com/autofac/Autofac/blob/develop/test/Autofac.Test/Features/Decorators/OpenGenericDecoratorTests.cs). ``` [Fact] public void ResolvesMultipleDecoratedServicesWhenResolvedByOtherServices() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(ImplementorA<>)).As(typeof(IDecoratedService<>)).As(typeof(IService<>)); builder.RegisterGeneric(typeof(ImplementorB<>)).As(typeof(IDecoratedService<>)).As(typeof(IService<>)); builder.RegisterGenericDecorator(typeof(DecoratorA<>), typeof(IService<>)); var container = builder.Build(); var services = container.Resolve<IEnumerable<IService<int>>>(); Assert.Collection( services, s => { var ds = s as IDecoratedService<int>; Assert.IsType<DecoratorA<int>>(ds); Assert.IsType<ImplementorA<int>>(ds.Decorated); }, s => { var ds = s as IDecoratedService<int>; Assert.IsType<DecoratorA<int>>(ds); Assert.IsType<ImplementorB<int>>(ds.Decorated); }); } ``` Awesome, thanks for that, it helps. Looks like the difference is that the components are registered as two different services rather than just one - two `As` clauses. It should still work, but I'm guessing that's the key here. This is going to take some time to get to. I have a bunch of PRs I'm trying to work through and both I and the other maintainers are pretty swamped with day job stuff lately. Obviously we'll look into it, for sure, but it may not be _fast_. If you have time and can figure it out faster, we'd totally take a PR. I'll give it a try but it could be out of my league. Hi, trying to familiarize myself with the code base more and this problem looked interesting. Would something like this https://github.com/autofac/Autofac/compare/develop...jfbourke:Autofac:issue1330 be appropriate? Or is there a better place to look? @jfbourke I think the `DecoratorMiddleware` is a reasonable place to start looking, yes. Found some time to look into this again. A bit of a brain dump. In this case, we have resolved an IService and the appropriate decorator. The decorator needs an IDecoratedService instance but this cannot be supplied by the service on the context as the TypedParameter is being used and the predicate in that class performs an exact match only. This tracks to the ConstructorBinder which uses the availableParameters on the ResolveRequest to find matching items; if none match a ForBindFailure is returned which leads to the resolve of the unexpected ImplementorB. I can see two options at the moment (maybe there are more); 1. Add all the registrations in the context to the resolveParameters array (sample code shared previously), or 2. Switch from TypedParameter to IsInstanceOfTypeParameter for the serviceParameter; this is a new class that checks if the value we have is an instance of the type we need, e.g. ``` public IsInstanceOfTypeParameter(Type type, object? value) : base(value, pi => pi.ParameterType.IsInstanceOfType(value)) { Type = type ?? throw new ArgumentNullException(nameof(type)); } ``` Hi! I think I'm having a very close related problem here. I'm also using MediatR. I filed an issue on Mediatr repo, but after finding this issue, I think that the problem is related to autofac. I am using a decorator for decorating the handlers that are implementing the INotificationHandler. I have an example here to demonstrate the behaviour https://dotnetfiddle.net/5sIGzj What my sample code do is - defining the handlers to be decorated - defining the decorator implementation - register the container with mediator service - call MediatR publish method in order to let him resolve and call all the handlers. To my understanding, the problem is right here: https://github.com/jbogard/MediatR/blob/cac76bee59a0f61c99554d76d4c39d67810fb406/src/MediatR/Wrappers/NotificationHandlerWrapper.cs#L25 MediatR is using an IServiceProvider to get all the handlers implementing `INotificationHandler<TNotification>`. In my case `TNotification` is `IEventNotification<TestEvent>>`. In fact I verified that in my case this line `serviceFactory.GetServices<INotificationHandler<IEventNotification<TestEvent>>>();` indeed returns 2 decorators with the same decorated service inside. If instead I do not register the generic decorator, the above same line returns two distinct handlers as expected. Further testing: I've tried with a simpler decorator: `builder.RegisterGenericDecorator(typeof(MyDecorator<>), typeof(INotificationHandler<>));` ``` public class MyDecorator<T> : INotificationHandler<T> where T : INotification { private readonly INotificationHandler<T> _decorated; public MyDecorator(INotificationHandler<T> decorated) { _decorated = decorated; } public Task Handle(T notification, CancellationToken cancellationToken) { _decorated.Handle(notification, cancellationToken); return Task.CompletedTask; } } ``` The decorator is called too many times (I was expecting this) but when finally the right target is decorated, the injected decorated handler is always the same.
2024-08-14T21:53:18Z
0.1
['Autofac.Test.Features.Decorators.OpenGenericDecoratorTests.ResolvesMultipleDecoratedServicesWhenResolvedByOtherServices']
[]
autofac/Autofac
autofac__autofac-1364
d166b2c2e575f6e0fddfab54f38c46f24f43839d
diff --git a/bench/Autofac.BenchmarkProfiling/Autofac.BenchmarkProfiling.csproj b/bench/Autofac.BenchmarkProfiling/Autofac.BenchmarkProfiling.csproj index 248ba87d6..165a5eac8 100644 --- a/bench/Autofac.BenchmarkProfiling/Autofac.BenchmarkProfiling.csproj +++ b/bench/Autofac.BenchmarkProfiling/Autofac.BenchmarkProfiling.csproj @@ -2,7 +2,7 @@ <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>net6.0</TargetFramework> + <TargetFramework>net7.0</TargetFramework> <PlatformTarget>x64</PlatformTarget> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> diff --git a/bench/Autofac.Benchmarks/Autofac.Benchmarks.csproj b/bench/Autofac.Benchmarks/Autofac.Benchmarks.csproj index eb53fe099..a3de60a98 100644 --- a/bench/Autofac.Benchmarks/Autofac.Benchmarks.csproj +++ b/bench/Autofac.Benchmarks/Autofac.Benchmarks.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net6.0</TargetFramework> + <TargetFramework>net7.0</TargetFramework> <NoWarn>$(NoWarn);CS1591</NoWarn> <OutputType>Exe</OutputType> <GenerateProgramFile>false</GenerateProgramFile> diff --git a/bench/Autofac.Benchmarks/Benchmarks.cs b/bench/Autofac.Benchmarks/Benchmarks.cs index c4bd6f04c..93f20013a 100644 --- a/bench/Autofac.Benchmarks/Benchmarks.cs +++ b/bench/Autofac.Benchmarks/Benchmarks.cs @@ -6,27 +6,28 @@ public static class Benchmarks { public static readonly Type[] All = { - typeof(ChildScopeResolveBenchmark), - typeof(ConcurrencyBenchmark), - typeof(ConcurrencyNestedScopeBenchmark), - typeof(KeyedGenericBenchmark), - typeof(KeyedNestedBenchmark), - typeof(KeyedSimpleBenchmark), - typeof(KeylessGenericBenchmark), - typeof(KeylessNestedBenchmark), - typeof(KeylessNestedSharedInstanceBenchmark), - typeof(KeylessNestedLambdaBenchmark), - typeof(KeylessNestedSharedInstanceLambdaBenchmark), - typeof(KeylessSimpleBenchmark), - typeof(KeylessSimpleSharedInstanceBenchmark), - typeof(KeylessSimpleLambdaBenchmark), - typeof(KeylessSimpleSharedInstanceLambdaBenchmark), - typeof(DeepGraphResolveBenchmark), - typeof(EnumerableResolveBenchmark), - typeof(PropertyInjectionBenchmark), - typeof(RootContainerResolveBenchmark), - typeof(OpenGenericBenchmark), - typeof(MultiConstructorBenchmark), - typeof(LambdaResolveBenchmark), - }; + typeof(ChildScopeResolveBenchmark), + typeof(ConcurrencyBenchmark), + typeof(ConcurrencyNestedScopeBenchmark), + typeof(KeyedGenericBenchmark), + typeof(KeyedNestedBenchmark), + typeof(KeyedSimpleBenchmark), + typeof(KeylessGenericBenchmark), + typeof(KeylessNestedBenchmark), + typeof(KeylessNestedSharedInstanceBenchmark), + typeof(KeylessNestedLambdaBenchmark), + typeof(KeylessNestedSharedInstanceLambdaBenchmark), + typeof(KeylessSimpleBenchmark), + typeof(KeylessSimpleSharedInstanceBenchmark), + typeof(KeylessSimpleLambdaBenchmark), + typeof(KeylessSimpleSharedInstanceLambdaBenchmark), + typeof(DeepGraphResolveBenchmark), + typeof(EnumerableResolveBenchmark), + typeof(PropertyInjectionBenchmark), + typeof(RootContainerResolveBenchmark), + typeof(OpenGenericBenchmark), + typeof(MultiConstructorBenchmark), + typeof(LambdaResolveBenchmark), + typeof(RequiredPropertyBenchmark), + }; } diff --git a/bench/Autofac.Benchmarks/ConcurrencyBenchmak.cs b/bench/Autofac.Benchmarks/ConcurrencyBenchmark.cs similarity index 100% rename from bench/Autofac.Benchmarks/ConcurrencyBenchmak.cs rename to bench/Autofac.Benchmarks/ConcurrencyBenchmark.cs diff --git a/bench/Autofac.Benchmarks/RequiredPropertyBenchmark.cs b/bench/Autofac.Benchmarks/RequiredPropertyBenchmark.cs new file mode 100644 index 000000000..7b343afd2 --- /dev/null +++ b/bench/Autofac.Benchmarks/RequiredPropertyBenchmark.cs @@ -0,0 +1,61 @@ +using Autofac.Core; + +namespace Autofac.Benchmarks; + +public class RequiredPropertyBenchmark +{ + private IContainer _container; + + [GlobalSetup] + public void Setup() + { + var builder = new ContainerBuilder(); + + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<ConstructorComponent>(); + builder.RegisterType<RequiredPropertyComponent>(); + + _container = builder.Build(); + } + + [Benchmark(Baseline = true)] + public void NormalConstructor() + { + _container.Resolve<ConstructorComponent>(); + } + + [Benchmark] + public void RequiredProperties() + { + _container.Resolve<RequiredPropertyComponent>(); + } + + public class ServiceA + { + } + + public class ServiceB + { + } + + public class ConstructorComponent + { + public ConstructorComponent(ServiceA serviceA, ServiceB serviceB) + { + ServiceA = serviceA; + ServiceB = serviceB; + } + + public ServiceA ServiceA { get; } + + public ServiceB ServiceB { get; } + } + + public class RequiredPropertyComponent + { + required public ServiceA ServiceA { get; set; } + + required public ServiceA ServiceB { get; set; } + } +} diff --git a/global.json b/global.json index 1982217ab..ed6506965 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "7.0.100", + "version": "7.0.101", "rollForward": "latestFeature" }, diff --git a/src/Autofac/Core/Activators/Reflection/BoundConstructor.cs b/src/Autofac/Core/Activators/Reflection/BoundConstructor.cs index 3488b2e12..ad323b592 100644 --- a/src/Autofac/Core/Activators/Reflection/BoundConstructor.cs +++ b/src/Autofac/Core/Activators/Reflection/BoundConstructor.cs @@ -71,6 +71,12 @@ internal BoundConstructor(ConstructorBinder binder, ParameterInfo firstNonBindab /// </summary> public ConstructorBinder Binder { get; } + /// <summary> + /// Gets a value indicating whether the constructor has the SetsRequiredMembers attribute, + /// indicating we can skip population of required properties. + /// </summary> + public bool SetsRequiredMembers => Binder.SetsRequiredMembers; + /// <summary> /// Gets the constructor on the target type. The actual constructor used /// might differ, e.g. if using a dynamic proxy. diff --git a/src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs b/src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs index 08d07c4d9..bb70bb5b3 100644 --- a/src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs +++ b/src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs @@ -26,6 +26,10 @@ public ConstructorBinder(ConstructorInfo constructorInfo) Constructor = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo)); _constructorArgs = constructorInfo.GetParameters(); +#if NET7_0_OR_GREATER + SetsRequiredMembers = constructorInfo.GetCustomAttribute<SetsRequiredMembersAttribute>() is not null; +#endif + // If any of the parameters are unsafe, do not create an invoker, and store the parameter // that broke the rule. _illegalParameter = DetectIllegalParameter(_constructorArgs); @@ -44,6 +48,12 @@ public ConstructorBinder(ConstructorInfo constructorInfo) /// </summary> public ConstructorInfo Constructor { get; } + /// <summary> + /// Gets a value indicating whether the constructor has the SetsRequiredMembers attribute, + /// indicating we can skip population of required properties. + /// </summary> + public bool SetsRequiredMembers { get; } + /// <summary> /// Gets the set of parameters to bind against. /// </summary> diff --git a/src/Autofac/Core/Activators/Reflection/InjectableProperty.cs b/src/Autofac/Core/Activators/Reflection/InjectableProperty.cs new file mode 100644 index 000000000..f439f4cd5 --- /dev/null +++ b/src/Autofac/Core/Activators/Reflection/InjectableProperty.cs @@ -0,0 +1,69 @@ +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +using System.Globalization; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Text; +using Autofac.Core.Resolving; +using Autofac.Core.Resolving.Pipeline; +using Autofac.Util; +using Autofac.Util.Cache; + +namespace Autofac.Core.Activators.Reflection; + +/// <summary> +/// Holds an instance of a known property on a type instantiated by the <see cref="ReflectionActivator"/>. +/// </summary> +internal class InjectableProperty +{ + private readonly MethodInfo _setter; + private readonly ParameterInfo _setterParameter; + + /// <summary> + /// Initializes a new instance of the <see cref="InjectableProperty"/> class. + /// </summary> + /// <param name="prop">The property info.</param> + public InjectableProperty(PropertyInfo prop) + { + Property = prop; + + _setter = prop.SetMethod!; + + _setterParameter = _setter.GetParameters()[0]; + +#if NET7_0_OR_GREATER + IsRequired = prop.GetCustomAttribute<RequiredMemberAttribute>() is not null; +#endif + } + + /// <summary> + /// Gets the underlying property. + /// </summary> + public PropertyInfo Property { get; } + + /// <summary> + /// Gets a value indicating whether this field is marked as required. + /// </summary> + public bool IsRequired { get; } + + /// <summary> + /// Try and supply a value for this property using the given parameter. + /// </summary> + /// <param name="instance">The object instance.</param> + /// <param name="p">The parameter that may provide the value.</param> + /// <param name="ctxt">The component context.</param> + /// <returns>True if the parameter could provide a value, and the property was set. False otherwise.</returns> + public bool TrySupplyValue(object instance, Parameter p, IComponentContext ctxt) + { + if (p.CanSupplyValue(_setterParameter, ctxt, out var vp)) + { + Property.SetValue(instance, vp(), null); + + return true; + } + + return false; + } +} diff --git a/src/Autofac/Core/Activators/Reflection/InjectablePropertyState.cs b/src/Autofac/Core/Activators/Reflection/InjectablePropertyState.cs new file mode 100644 index 000000000..d5d55b860 --- /dev/null +++ b/src/Autofac/Core/Activators/Reflection/InjectablePropertyState.cs @@ -0,0 +1,30 @@ +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +namespace Autofac.Core.Activators.Reflection; + +/// <summary> +/// Structure used to track whether or not we have set a property during activation. +/// </summary> +internal struct InjectablePropertyState +{ + /// <summary> + /// Initializes a new instance of the <see cref="InjectablePropertyState"/> struct. + /// </summary> + /// <param name="property">The property.</param> + public InjectablePropertyState(InjectableProperty property) + { + Property = property; + Set = false; + } + + /// <summary> + /// Gets the property. + /// </summary> + public InjectableProperty Property { get; } + + /// <summary> + /// Gets or sets a value indicating whether this property has already been set. + /// </summary> + public bool Set { get; set; } +} diff --git a/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs b/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs index 0561d060b..1c0ad351c 100644 --- a/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs +++ b/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs @@ -4,9 +4,12 @@ using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using System.Text; using Autofac.Core.Resolving; using Autofac.Core.Resolving.Pipeline; +using Autofac.Util; +using Autofac.Util.Cache; namespace Autofac.Core.Activators.Reflection; @@ -21,6 +24,8 @@ public class ReflectionActivator : InstanceActivator, IInstanceActivator private readonly Parameter[] _defaultParameters; private ConstructorBinder[]? _constructorBinders; + private bool _anyRequiredMembers; + private InjectablePropertyState[]? _defaultFoundPropertySet; /// <summary> /// Initializes a new instance of the <see cref="ReflectionActivator"/> class. @@ -78,6 +83,40 @@ public void ConfigurePipeline(IComponentRegistryServices componentRegistryServic throw new ArgumentNullException(nameof(pipelineBuilder)); } +#if NET7_0_OR_GREATER + // The RequiredMemberAttribute has Inherit = false on its AttributeUsage options, + // so we can't use the expected GetCustomAttribute(inherit: true) option, and must walk the tree. + var currentType = _implementationType; + while (currentType is not null && !currentType.Equals(typeof(object))) + { + if (currentType.GetCustomAttribute<RequiredMemberAttribute>() is not null) + { + _anyRequiredMembers = true; + break; + } + + currentType = currentType.BaseType; + } +#else + _anyRequiredMembers = false; +#endif + + if (_anyRequiredMembers || _configuredProperties.Length > 0) + { + // Get the full set of properties. + var actualProperties = _implementationType + .GetRuntimeProperties() + .Where(pi => pi.CanWrite) + .ToList(); + + _defaultFoundPropertySet = new InjectablePropertyState[actualProperties.Count]; + + for (int idx = 0; idx < actualProperties.Count; idx++) + { + _defaultFoundPropertySet[idx] = new InjectablePropertyState(new InjectableProperty(actualProperties[idx])); + } + } + // Locate the possible constructors at container build time. var availableConstructors = ConstructorFinder.FindConstructors(_implementationType); @@ -96,6 +135,7 @@ public void ConfigurePipeline(IComponentRegistryServices componentRegistryServic if (binders.Length == 1) { UseSingleConstructorActivation(pipelineBuilder, binders[0]); + return; } else if (ConstructorSelector is IConstructorSelectorWithEarlyBinding earlyBindingSelector) @@ -147,7 +187,7 @@ private void UseSingleConstructorActivation(IResolvePipelineBuilder pipelineBuil var instance = boundConstructor.Instantiate(); - InjectProperties(instance, ctxt); + InjectProperties(instance, ctxt, boundConstructor, GetAllParameters(ctxt.Parameters)); ctxt.Instance = instance; @@ -171,7 +211,7 @@ private void UseSingleConstructorActivation(IResolvePipelineBuilder pipelineBuil var instance = bound.Instantiate(); - InjectProperties(instance, ctxt); + InjectProperties(instance, ctxt, bound, prioritisedParameters); ctxt.Instance = instance; @@ -204,7 +244,9 @@ private object ActivateInstance(IComponentContext context, IEnumerable<Parameter CheckNotDisposed(); - var allBindings = GetAllBindings(_constructorBinders!, context, parameters); + var prioritisedParameters = GetAllParameters(parameters); + + var allBindings = GetAllBindings(_constructorBinders!, context, prioritisedParameters); var selectedBinding = ConstructorSelector.SelectConstructorBinding(allBindings, parameters); @@ -218,21 +260,19 @@ private object ActivateInstance(IComponentContext context, IEnumerable<Parameter var instance = selectedBinding.Instantiate(); - InjectProperties(instance, context); + InjectProperties(instance, context, selectedBinding, prioritisedParameters); return instance; } - private BoundConstructor[] GetAllBindings(ConstructorBinder[] availableConstructors, IComponentContext context, IEnumerable<Parameter> parameters) + private BoundConstructor[] GetAllBindings(ConstructorBinder[] availableConstructors, IComponentContext context, IEnumerable<Parameter> allParameters) { - var prioritisedParameters = GetAllParameters(parameters); - var boundConstructors = new BoundConstructor[availableConstructors.Length]; var validBindings = availableConstructors.Length; for (var idx = 0; idx < availableConstructors.Length; idx++) { - var bound = availableConstructors[idx].Bind(prioritisedParameters, context); + var bound = availableConstructors[idx].Bind(allParameters, context); boundConstructors[idx] = bound; @@ -310,33 +350,112 @@ private string GetBindingFailureMessage(BoundConstructor[] constructorBindings) } } - private void InjectProperties(object instance, IComponentContext context) + private void InjectProperties(object instance, IComponentContext context, BoundConstructor constructor, IEnumerable<Parameter> allParameters) { - if (_configuredProperties.Length == 0) + // We only need to do any injection if we have a set of property information. + if (_defaultFoundPropertySet is null) { return; } - var actualProperties = instance - .GetType() - .GetRuntimeProperties() - .Where(pi => pi.CanWrite) - .ToList(); + // If this constructor sets all required members, + // and we have no configured properties, we can just jump out. + if (_configuredProperties.Length == 0 && constructor.SetsRequiredMembers) + { + return; + } + + var workingSetOfProperties = (InjectablePropertyState[])_defaultFoundPropertySet.Clone(); foreach (var configuredProperty in _configuredProperties) { - foreach (var actualProperty in actualProperties) + for (var propIdx = 0; propIdx < workingSetOfProperties.Length; propIdx++) { - var setter = actualProperty.SetMethod; + ref var prop = ref workingSetOfProperties[propIdx]; + + if (prop.Set) + { + // Skip, already seen. + continue; + } - if (setter != null && - configuredProperty.CanSupplyValue(setter.GetParameters()[0], context, out var vp)) + if (prop.Property.TrySupplyValue(instance, configuredProperty, context)) { - actualProperties.Remove(actualProperty); - actualProperty.SetValue(instance, vp(), null); + prop.Set = true; break; } } } + + if (_anyRequiredMembers && !constructor.SetsRequiredMembers) + { + List<InjectableProperty>? failingRequiredProperties = null; + + for (var propIdx = 0; propIdx < workingSetOfProperties.Length; propIdx++) + { + ref var prop = ref workingSetOfProperties[propIdx]; + + if (!prop.Property.IsRequired) + { + // Only auto-populate required properties. + continue; + } + + if (prop.Set) + { + // Only auto-populate things not already populated by a specific property + // being set. + continue; + } + + foreach (var parameter in allParameters) + { + if (parameter is NamedParameter || parameter is PositionalParameter) + { + // Skip Named and Positional parameters, because if someone uses 'value' as a + // constructor parameter name, it would also match the property, and cause confusion. + continue; + } + + if (prop.Property.TrySupplyValue(instance, parameter, context)) + { + prop.Set = true; + + break; + } + } + + if (!prop.Set) + { + failingRequiredProperties ??= new(); + failingRequiredProperties.Add(prop.Property); + } + } + + if (failingRequiredProperties is not null) + { + throw new DependencyResolutionException(BuildRequiredPropertyResolutionMessage(failingRequiredProperties)); + } + } + } + + private string BuildRequiredPropertyResolutionMessage(IReadOnlyList<InjectableProperty> failingRequiredProperties) + { + var propertyDescriptions = new StringBuilder(); + + foreach (var failed in failingRequiredProperties) + { + propertyDescriptions.AppendLine(); + propertyDescriptions.Append(failed.Property.Name); + propertyDescriptions.Append(" ("); + propertyDescriptions.Append(failed.Property.PropertyType.FullName); + propertyDescriptions.Append(')'); + } + + return string.Format( + CultureInfo.CurrentCulture, + ReflectionActivatorResources.RequiredPropertiesCouldNotBeBound, + _implementationType, + propertyDescriptions); } } diff --git a/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx b/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx index 947acb4d6..81ffa790c 100644 --- a/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx +++ b/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx @@ -1,17 +1,17 @@ <?xml version="1.0" encoding="utf-8"?> <root> - <!-- - Microsoft ResX Schema - + <!-- + Microsoft ResX Schema + Version 2.0 - - The primary goals of this format is to allow a simple XML format - that is mostly human readable. The generation and parsing of the - various data types are done through the TypeConverter classes + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes associated with the data types. - + Example: - + ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> @@ -26,36 +26,36 @@ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> - - There are any number of "resheader" rows that contain simple + + There are any number of "resheader" rows that contain simple name/value pairs. - - Each data row contains a name, and value. The row also contains a - type or mimetype. Type corresponds to a .NET class that support - text/value conversion through the TypeConverter architecture. - Classes that don't support this are serialized and stored with the + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the mimetype set. - - The mimetype is used for serialized objects, and tells the - ResXResourceReader how to depersist the object. This is currently not + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: - - Note - application/x-microsoft.net.object.binary.base64 is the format - that the ResXResourceWriter will generate, however the reader can + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. - + mimetype: application/x-microsoft.net.object.binary.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. - + mimetype: application/x-microsoft.net.object.soap.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 - value : The object must be serialized into a byte array + value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> @@ -128,4 +128,7 @@ See https://autofac.rtfd.io/help/no-constructors-bindable for more info.</value> </data> -</root> + <data name="RequiredPropertiesCouldNotBeBound" xml:space="preserve"> + <value>One or more of the required properties on type '{0}' could not be resolved:{1}</value> + </data> +</root> \ No newline at end of file
diff --git a/test/Autofac.Specification.Test/Features/RequiredPropertyTests.cs b/test/Autofac.Specification.Test/Features/RequiredPropertyTests.cs new file mode 100644 index 000000000..00dfe07b9 --- /dev/null +++ b/test/Autofac.Specification.Test/Features/RequiredPropertyTests.cs @@ -0,0 +1,355 @@ +// Copyright (c) Autofac Project. All rights reserved. +// Licensed under the MIT License. See LICENSE in the project root for license information. + +using System.Diagnostics.CodeAnalysis; +using Autofac.Core; + +namespace Autofac.Specification.Test.Features; + +#if NET7_0_OR_GREATER + +public class RequiredPropertyTests +{ + [Fact] + public void ResolveRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<Component>(); + + var container = builder.Build(); + + var component = container.Resolve<Component>(); + + Assert.NotNull(component.ServiceA); + Assert.NotNull(component.ServiceB); + } + + [Fact] + public void MissingRequiredPropertyServiceThrowsException() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>(); + + var container = builder.Build(); + + var exception = Assert.Throws<DependencyResolutionException>(() => container.Resolve<Component>()); + + Assert.Contains(nameof(Component.ServiceB), exception.InnerException.Message); + } + + [Fact] + public void CanMixConstructorsAndProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<MixedConstructorAndPropertyComponent>(); + + var container = builder.Build(); + + var component = container.Resolve<MixedConstructorAndPropertyComponent>(); + + Assert.NotNull(component.ServiceA); + Assert.NotNull(component.ServiceB); + } + + [Fact] + public void PropertiesPopulatedOnAllSubsequentResolves() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<Component>(); + + var container = builder.Build(); + + var component = container.Resolve<Component>(); + + Assert.NotNull(component.ServiceA); + Assert.NotNull(component.ServiceB); + + var component2 = container.Resolve<Component>(); + + Assert.NotNull(component2.ServiceA); + Assert.NotNull(component2.ServiceB); + + var component3 = container.Resolve<Component>(); + + Assert.NotNull(component3.ServiceA); + Assert.NotNull(component3.ServiceB); + } + + [Fact] + public void ExplicitParameterOverridesRequiredAutowiring() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<Component>().WithProperty(nameof(Component.ServiceB), new ServiceB { Tag = "custom" }); + + var container = builder.Build(); + + var component = container.Resolve<Component>(); + + Assert.Equal("custom", component.ServiceB.Tag); + } + + [Fact] + public void ExplicitParameterCanTakePlaceOfRegistration() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>().WithProperty(nameof(Component.ServiceB), new ServiceB { Tag = "custom" }); + + var container = builder.Build(); + + var component = container.Resolve<Component>(); + + Assert.Equal("custom", component.ServiceB.Tag); + } + + [Fact] + public void GeneralTypeParameterCanTakePlaceOfRegistration() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>().WithParameter(new TypedParameter(typeof(ServiceB), new ServiceB())); + + var container = builder.Build(); + + var component = container.Resolve<Component>(); + + Assert.NotNull(component.ServiceB); + } + + [Fact] + public void ParameterPassedAtResolveUsedForRequiredProperty() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>(); + + var container = builder.Build(); + + var component = container.Resolve<Component>(new TypedParameter(typeof(ServiceB), new ServiceB())); + + Assert.NotNull(component.ServiceB); + } + + [Fact] + public void NamedParametersIgnoredForRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>().WithParameter("value", new ServiceB()); + + var container = builder.Build(); + + Assert.Throws<DependencyResolutionException>(() => container.Resolve<Component>()); + } + + [Fact] + public void PositionalParametersIgnoredForRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<Component>().WithParameter(new PositionalParameter(0, new ServiceB())); + + var container = builder.Build(); + + Assert.Throws<DependencyResolutionException>(() => container.Resolve<Component>()); + } + + [Fact] + public void SetsRequiredMembersConstructorSkipsRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ConstructorComponent>(); + + var container = builder.Build(); + + var component = container.Resolve<ConstructorComponent>(); + + Assert.Null(component.ServiceA); + Assert.Null(component.ServiceB); + } + + [Fact] + public void SetsRequiredMembersConstructorSkipsRequiredPropertiesEvenWhenRegistered() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<ConstructorComponent>(); + + var container = builder.Build(); + + var component = container.Resolve<ConstructorComponent>(); + + Assert.Null(component.ServiceA); + Assert.Null(component.ServiceB); + } + + [Fact] + public void OnlySelectedConstructorConsideredForSetsRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterType<MultiConstructorComponent>(); + + var container = builder.Build(); + + var component = container.Resolve<MultiConstructorComponent>(); + + // Allowed to not be set, because empty constructor was selected. + Assert.Null(component.ServiceA); + + using var scope = container.BeginLifetimeScope(b => b.RegisterType<ServiceC>()); + + // Fails, because constructor with SetsRequiredProperties attribute is selected. + Assert.Throws<DependencyResolutionException>(() => scope.Resolve<MultiConstructorComponent>()); + } + + [Fact] + public void DerivedClassResolvesPropertiesInParent() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<DerivedComponent>(); + + var container = builder.Build(); + + var component = container.Resolve<DerivedComponent>(); + + Assert.NotNull(component.ServiceA); + Assert.NotNull(component.ServiceB); + } + + [Fact] + public void DerivedClassResolvesPropertiesInParentAndSelf() + { + var builder = new ContainerBuilder(); + builder.RegisterType<ServiceA>(); + builder.RegisterType<ServiceB>(); + builder.RegisterType<ServiceC>(); + builder.RegisterType<DerivedComponentWithProp>(); + + var container = builder.Build(); + + var component = container.Resolve<DerivedComponentWithProp>(); + + Assert.NotNull(component.ServiceA); + Assert.NotNull(component.ServiceB); + Assert.NotNull(component.ServiceC); + } + + [Fact] + public void CanResolveOpenGenericComponentRequiredProperties() + { + var builder = new ContainerBuilder(); + builder.RegisterGeneric(typeof(OpenGenericService<>)); + builder.RegisterGeneric(typeof(OpenGenericComponent<>)); + + var container = builder.Build(); + + var component = container.Resolve<OpenGenericComponent<int>>(); + + Assert.NotNull(component.Service); + } + + private class OpenGenericComponent<T> + { + required public OpenGenericService<T> Service { get; set; } + } + + private class OpenGenericService<T> + { + } + + private class ConstructorComponent + { + [SetsRequiredMembers] + public ConstructorComponent() + { + } + + required public ServiceA ServiceA { get; set; } + + required public ServiceB ServiceB { get; set; } + } + + private class MixedConstructorAndPropertyComponent + { + public MixedConstructorAndPropertyComponent(ServiceA serviceA) + { + ServiceA = serviceA; + } + + public ServiceA ServiceA { get; set; } + + required public ServiceB ServiceB { get; set; } + } + + private class MultiConstructorComponent + { + [SetsRequiredMembers] + public MultiConstructorComponent() + { + } + + public MultiConstructorComponent(ServiceC serviceC) + { + } + + required public ServiceA ServiceA { get; set; } + } + + private class Component + { + required public ServiceA ServiceA { get; set; } + + required public ServiceB ServiceB { get; set; } + } + + private class DerivedComponentWithProp : Component + { + public DerivedComponentWithProp() + { + } + + required public ServiceC ServiceC { get; set; } + } + + private class DerivedComponent : Component + { + } + + private class ServiceA + { + public ServiceA() + { + Tag = "Default"; + } + + public string Tag { get; set; } + } + + private class ServiceB + { + public ServiceB() + { + Tag = "Default"; + } + + public string Tag { get; set; } + } + + private class ServiceC + { + } +} + +#endif
Support for ```required``` properties ## Problem Statement Traditionally, Autofac creates objects by calling one of their constructors. The constructor accepts dependencies and then assigns/initializes values. Starting in C#11, dependencies can also be expressed using the ```required``` keyword. When a property is ```required```, if the constructor that was called does not have the ```[SetsRequiredMembers]``` attribute, the property must have a value set immediately following construction. Currently AutoFac does not support this core enhancement to object construction. ## Desired Solution When Autofac constructs an object, the constructor should be examined for ```[SetsRequiredMembers]```. If it is not found, all writable properties containing the ```RequiredMemberAttribute``` attribute should be injected. ```csharp public class Foo1 { //This should be injected public required Dependency? Dep { protected get; init; } } public class Foo2 { //This should not public required Dependency? Dep { protected get; init; } [SetsRequiredMembers] public Foo2() { this.Dep = null; } } ``` ## Additional Context Because C#11 introduces this core-level enhancement to object construction, the above rules should always be enabled. The following code will be helpful in implementing this enhancement: ```csharp public class PS : IPropertySelector { public static IPropertySelector Instance { get; } private static string RequiredAttributeName { get; } private static string SetsRequiredMembersAttributeName { get; } static PS() { Instance = new PS(); //The type names are stored as strings so that this can also be used with legacy .NET platforms RequiredAttributeName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; SetsRequiredMembersAttributeName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; } public bool NeedsPropertyInjection(ConstructorInfo constructorInfo) { var SetsRequiredMembers = constructorInfo.GetCustomAttributesData().Any(x => string.Equals(x.AttributeType.FullName, SetsRequiredMembersAttributeName, StringComparison.InvariantCultureIgnoreCase)); var ret = !SetsRequiredMembers; return ret; } public bool InjectProperty(PropertyInfo propertyInfo, object instance) { var ret = propertyInfo.CanWrite && propertyInfo.GetCustomAttributesData().Any(x => string.Equals(x.AttributeType.FullName, RequiredAttributeName, StringComparison.InvariantCultureIgnoreCase)) ; return ret; } } ```
Generally in favour of the feature to reduce user confusion when combined with the NRT analyser, I'm guessing it will determine that any required properties are non-null. Got some random questions/thoughts though of the top of my head... - Currently you have to invoke `PropertiesAutowired` on a registration to apply any property injection behaviour. Are you suggesting this is still the case? Or would this be applied to all registrations automatically? - Is there a compiler-generated attribute that indicates "this type has required properties"? - Does this feature combine with nullable reference types in any interesting ways? If someone has a `required ServiceA?` property, does that mean it _must_ be populated? Or is still a bit optional? - Do we _only_ apply this to `required` attributes? Or do non-required properties become optional injection automatically? Just trying to tease out some of the detail on this one... Hi @alistairjevans - **RE ```PropertiesAutowired```:** I believe that required properties should always be injected and should essentially be treated like "Constructor 2.0" **RE compiler-generated attribute**: Yes. See the code above. There are two attributes that work together: ``` RequiredAttributeName = "System.Runtime.CompilerServices.RequiredMemberAttribute"; SetsRequiredMembersAttributeName = "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute"; ``` **RE nullable reference types**: A required property _MUST be set although ```null``` is a valid value to set it to. I believe that if the nullable reference type is annotated, then autofac should throw an exception if it cannot provid a value since null is an invalid value in that case. **RE: Do we only apply this to required attributes?** This should be thought of as part of maintaining compatibility with the current .net object construction methodologies and should not be optional. The current ```PropertiesAutowired``` should continue to exist and operate as is since it provides similar (but not identical) capabilities. It might be worth finding out what, if anything, the Microsoft container is going to do here. They sometimes make unspoken/undocumented assumptions on how things will work. If we do something different we'll need a way to "switch to MS compatible behavior" (see: lifetime scopes aren't hierarchical). @tillig, looks like the answer to that is not yet known: https://github.com/dotnet/runtime/issues/76854 I think I'm a little reluctant to enable property-autowiring "by default", mostly due to user confusion from the different behaviour between 'required' properties and 'optional' properties. Say I have two properties on a component, of type `A` and `B`. Type `A` is marked as `required`, and `B` is not. I *always* register a service of type `A`, but `B` is condtionally registered (e.g. by tenant). When I resolve my component, in this scenario `A` would always be populated, and `B` would never be, however if I call `PropertiesAutowired()` on the registration, then `B` *will* sometimes be populated, but the behaviour of `A` will be the same. This feels like it will absolutely result in users raising issues where "this property is set, but this one isn't, even though it's registered...". So it still feels like property injection needs to be opt-in somehow...there probably is a small number of changes we could make that gives us a decent compromise: - We can check for the `RequiredMemberAttribute` on a type when we build the registration; if it is present, but `PropertiesAutowired` has not been called, we can throw a suitably informative exception. - When executing `AutowiringPropertyInjector.InjectProperties`, if a property is marked as `required`, but is excluded by a custom property selector, we can throw an exception. - If we fail to resolve a service for a property marked with `RequiredMemberAttribute`, we throw an exception. - Optionally, to enable users who genuinely want this behaviour *everywhere*, we could add a `ContainerBuilder.GlobalPropertiesAutowired()` method that injects `PropertiesAutowired()` onto every registration. Technically this is already possible with a registered event handler, but a shortcut may be useful. Related to this, how would I enable ```PropertiesAutowired``` on ```AnyConcreteTypeNotAlreadyRegisteredSource```? @TonyValenti good point with ACTNARS. @alistairjevans My gut says both that you're right, inconsistent behavior will be a problem. But I also think if a property is marked required then it's part of object initialization so it probably has to happen. This seems particularly to affect reflection-based construction (individual types, open generics) since the compiler would ostensibly stop a lambda from returning an incomplete object. I haven't thought this totally through, but I wonder if part of the constructor locator process needs to also locate required properties and add those to a list of always-initialized properties. Not full autowired properties, but also not something you have to opt into. If props autowiring is opted in, then the set of properties to wire is the _union_ of required and whatever else can be populated. If a required property can't be filled in, a similar exception to the constructor exception gets thrown, but with an explanation about it being a property. I think this could be cached like we cache constructors to save a bit on perf, but it's definitely going to be a non-zero hit since, at a minimum, we'll always have to check the cache for the (likely empty) list of required properties. I'm reluctant to make a final decision until we know what M.E.DI is doing simply because the path of least resistance is to be compatible. I added a comment to that dotnet issue. I don't know if they'll even address it, looks like it's been there for a bit with no other commentary. We may need to make a decision here and then just post to them what we did as a way to try to inform what they do, then hope for compatibility. Thanks @tillig - I'm really hopeful this gets implemented. Being able to have required properties be injected would enable me to remove a ton of code in my application. I have a set of base classes that are extended 3-4 levels deep. Currently, Every constructor at every level of the inheritance chain has to collect and forward parameters to its base constructor. That's nothing unique to me, I'm just particularly affected by it. Anyways, injecting to required properties would allow me to remove close to 1600 constructors in my code base and enable me to remove about 600 auxiliary classes. I really hope this gets some traction. **_Just adding to the thread what I wrote in the original "required properties proposal" in C#, it explains very well some benefits:_** With **required** properties, we end up creating an alternative way to specify a constructor without bloat the ctor with a lot of parameters. ```csharp public class Person { public required string FirstName { get; init; } public required string MiddleName { get; init; } public required string LastName { get; init; } } ``` Now, assuming Dependency Injectors can understand what I am asking, we can change code like this ```csharp public class SomeClass { private readonly IDbContext _dbContext; private readonly ILogger _logger; private readonly IOptions _options; public SomeClass(IDbContext dbContext, ILogger logger, IOptions options) { _dbContext = dbContext; _logger = logger; _options = options; } } public class SomeDerivedClass : SomeClass { private readonly IMailService _mailService; public SomeDerivedClass(IDbContext dbContext, ILogger logger, IOptions options, IMailService mailService) :base(dbContext, logger, options) { _mailService = mailService; } } ``` in this instead: ```csharp public class SomeClass { public required IDbContext DbContext { get; init; } public required ILogger Logger { get; init; } public required IOptions<AppSettings> Options { get; init; } } public class SomeDerivedClass : SomeClass { public required IMailService MailService { get; init; } } ``` This is a LOT of less boilerplate error-prone code! And the "required" is the key here. I know that currently it is partially supported by Dependency Injectors (property injection), but it is rarely used and I think if the Injector finds a "required" property it will be better than using a settable property. I don't think we need to be sold on the value of the feature. At this point it's more a question of how it should work and how we can remain compatible with M.E.DI. I'm almost more concerned about that compatibility issue because trying to retrofit compatibility has caused us a lot of trouble in the past. Folks, for whatever reason, choose Autofac as the underlying container and then complain when it isn't identical to the Microsoft container. Hi @tillig - What is the right way to get input from MS regarding this? I can really use this feature and want to do whatever is necessary to drive this enhancement forward. @TonyValenti if I had a way, I'd have used it. I don't have any more visibility or leverage into their process than you do. I commented on the issue linked earlier, that's all I can do. You can comment there, too, if you like. Working through things that may affect every user of a container or framework is not a fast process. @tillig - We have a response from Microsoft! https://github.com/dotnet/runtime/issues/76854
2023-01-28T10:34:13Z
0.1
['Autofac.Specification.Test.Features.RequiredPropertyTests.CanResolveOpenGenericComponentRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.PositionalParametersIgnoredForRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.GeneralTypeParameterCanTakePlaceOfRegistration', 'Autofac.Specification.Test.Features.RequiredPropertyTests.CanMixConstructorsAndProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.SetsRequiredMembersConstructorSkipsRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.ExplicitParameterCanTakePlaceOfRegistration', 'Autofac.Specification.Test.Features.RequiredPropertyTests.MissingRequiredPropertyServiceThrowsException', 'Autofac.Specification.Test.Features.RequiredPropertyTests.ResolveRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.ParameterPassedAtResolveUsedForRequiredProperty', 'Autofac.Specification.Test.Features.RequiredPropertyTests.DerivedClassResolvesPropertiesInParent', 'Autofac.Specification.Test.Features.RequiredPropertyTests.NamedParametersIgnoredForRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.PropertiesPopulatedOnAllSubsequentResolves', 'Autofac.Specification.Test.Features.RequiredPropertyTests.SetsRequiredMembersConstructorSkipsRequiredPropertiesEvenWhenRegistered', 'Autofac.Specification.Test.Features.RequiredPropertyTests.OnlySelectedConstructorConsideredForSetsRequiredProperties', 'Autofac.Specification.Test.Features.RequiredPropertyTests.ExplicitParameterOverridesRequiredAutowiring', 'Autofac.Specification.Test.Features.RequiredPropertyTests.DerivedClassResolvesPropertiesInParentAndSelf']
[]
autofac/Autofac
autofac__autofac-1362
0c79d7bce06173e358c748a0a3f64f311a901f7f
diff --git a/bench/Autofac.BenchmarkProfiling/Program.cs b/bench/Autofac.BenchmarkProfiling/Program.cs index 007338158..0bf1280ad 100644 --- a/bench/Autofac.BenchmarkProfiling/Program.cs +++ b/bench/Autofac.BenchmarkProfiling/Program.cs @@ -84,14 +84,14 @@ static void Main(string[] args) // Workload method is generated differently when BenchmarkDotNet actually runs; we'll need to wrap it in the set of parameters. // It's way slower than they way they do it, but it should still give us good profiler results. - Action<int> workloadAction = (repeat) => + void workloadAction(int repeat) { while (repeat > 0) { selectedCase.Descriptor.WorkloadMethod.Invoke(benchInstance, selectedCase.Parameters.Items.Select(x => x.Value).ToArray()); repeat--; } - }; + } setupAction.InvokeSingle(); diff --git a/src/Autofac/Core/Activators/Reflection/DefaultConstructorFinder.cs b/src/Autofac/Core/Activators/Reflection/DefaultConstructorFinder.cs index 469328d48..dbb1eba63 100644 --- a/src/Autofac/Core/Activators/Reflection/DefaultConstructorFinder.cs +++ b/src/Autofac/Core/Activators/Reflection/DefaultConstructorFinder.cs @@ -45,14 +45,7 @@ public ConstructorInfo[] FindConstructors(Type targetType) private static ConstructorInfo[] GetDefaultPublicConstructors(Type type) { - var retval = ReflectionCacheSet.Shared.Internal.DefaultPublicConstructors + return ReflectionCacheSet.Shared.Internal.DefaultPublicConstructors .GetOrAdd(type, t => t.GetDeclaredPublicConstructors()); - - if (retval.Length == 0) - { - throw new NoConstructorsFoundException(type); - } - - return retval; } } diff --git a/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundException.cs b/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundException.cs index 9162b4fc5..ea2d23800 100644 --- a/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundException.cs +++ b/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundException.cs @@ -13,61 +13,82 @@ public class NoConstructorsFoundException : Exception /// <summary> /// Initializes a new instance of the <see cref="NoConstructorsFoundException"/> class. /// </summary> - /// <param name="offendingType">The <see cref="System.Type"/> whose constructor was not found.</param> - public NoConstructorsFoundException(Type offendingType) - : this(offendingType, FormatMessage(offendingType)) + /// <param name="offendingType">The <see cref="Type"/> whose constructor was not found.</param> + /// <param name="constructorFinder">The <see cref="IConstructorFinder"/> that was used to scan for the constructors.</param> + public NoConstructorsFoundException(Type offendingType, IConstructorFinder constructorFinder) + : this(offendingType, constructorFinder, FormatMessage(offendingType, constructorFinder)) { } /// <summary> /// Initializes a new instance of the <see cref="NoConstructorsFoundException"/> class. /// </summary> - /// <param name="offendingType">The <see cref="System.Type"/> whose constructor was not found.</param> + /// <param name="offendingType">The <see cref="Type"/> whose constructor was not found.</param> + /// <param name="constructorFinder">The <see cref="IConstructorFinder"/> that was used to scan for the constructors.</param> /// <param name="message">Exception message.</param> - public NoConstructorsFoundException(Type offendingType, string message) + public NoConstructorsFoundException(Type offendingType, IConstructorFinder constructorFinder, string message) : base(message) { OffendingType = offendingType ?? throw new ArgumentNullException(nameof(offendingType)); + ConstructorFinder = constructorFinder ?? throw new ArgumentNullException(nameof(constructorFinder)); } /// <summary> /// Initializes a new instance of the <see cref="NoConstructorsFoundException"/> class. /// </summary> - /// <param name="offendingType">The <see cref="System.Type"/> whose constructor was not found.</param> + /// <param name="offendingType">The <see cref="Type"/> whose constructor was not found.</param> + /// <param name="constructorFinder">The <see cref="IConstructorFinder"/> that was used to scan for the constructors.</param> /// <param name="innerException">The inner exception.</param> - public NoConstructorsFoundException(Type offendingType, Exception innerException) - : this(offendingType, FormatMessage(offendingType), innerException) + public NoConstructorsFoundException(Type offendingType, IConstructorFinder constructorFinder, Exception innerException) + : this(offendingType, constructorFinder, FormatMessage(offendingType, constructorFinder), innerException) { } /// <summary> /// Initializes a new instance of the <see cref="NoConstructorsFoundException"/> class. /// </summary> - /// <param name="offendingType">The <see cref="System.Type"/> whose constructor was not found.</param> + /// <param name="offendingType">The <see cref="Type"/> whose constructor was not found.</param> + /// <param name="constructorFinder">The <see cref="IConstructorFinder"/> that was used to scan for the constructors.</param> /// <param name="message">Exception message.</param> /// <param name="innerException">The inner exception.</param> - public NoConstructorsFoundException(Type offendingType, string message, Exception innerException) + public NoConstructorsFoundException(Type offendingType, IConstructorFinder constructorFinder, string message, Exception innerException) : base(message, innerException) { OffendingType = offendingType ?? throw new ArgumentNullException(nameof(offendingType)); + ConstructorFinder = constructorFinder ?? throw new ArgumentNullException(nameof(constructorFinder)); } + /// <summary> + /// Gets the finder used when locating constructors. + /// </summary> + /// <value> + /// An <see cref="IConstructorFinder"/> that was used when scanning the + /// <see cref="OffendingType"/> to find constructors. + /// </value> + public IConstructorFinder ConstructorFinder { get; private set; } + /// <summary> /// Gets the type without found constructors. /// </summary> /// <value> - /// A <see cref="System.Type"/> that was processed by an <see cref="IConstructorFinder"/> - /// or similar mechanism and was determined to have no available constructors. + /// A <see cref="Type"/> that was processed by the + /// <see cref="ConstructorFinder"/> and was determined to have no available + /// constructors. /// </value> public Type OffendingType { get; private set; } - private static string FormatMessage(Type offendingType) + private static string FormatMessage(Type offendingType, IConstructorFinder constructorFinder) { if (offendingType == null) { throw new ArgumentNullException(nameof(offendingType)); } - return string.Format(CultureInfo.CurrentCulture, NoConstructorsFoundExceptionResources.Message, offendingType.FullName); + if (constructorFinder == null) + { + throw new ArgumentNullException(nameof(constructorFinder)); + } + + return string.Format(CultureInfo.CurrentCulture, NoConstructorsFoundExceptionResources.Message, offendingType.FullName, constructorFinder.GetType().FullName); } } diff --git a/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundExceptionResources.resx b/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundExceptionResources.resx index 6ebd2a7e4..03fa3f43c 100644 --- a/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundExceptionResources.resx +++ b/src/Autofac/Core/Activators/Reflection/NoConstructorsFoundExceptionResources.resx @@ -1,17 +1,17 @@ <?xml version="1.0" encoding="utf-8"?> <root> - <!-- - Microsoft ResX Schema - + <!-- + Microsoft ResX Schema + Version 2.0 - - The primary goals of this format is to allow a simple XML format - that is mostly human readable. The generation and parsing of the - various data types are done through the TypeConverter classes + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes associated with the data types. - + Example: - + ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> @@ -26,36 +26,36 @@ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> - - There are any number of "resheader" rows that contain simple + + There are any number of "resheader" rows that contain simple name/value pairs. - - Each data row contains a name, and value. The row also contains a - type or mimetype. Type corresponds to a .NET class that support - text/value conversion through the TypeConverter architecture. - Classes that don't support this are serialized and stored with the + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the mimetype set. - - The mimetype is used for serialized objects, and tells the - ResXResourceReader how to depersist the object. This is currently not + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: - - Note - application/x-microsoft.net.object.binary.base64 is the format - that the ResXResourceWriter will generate, however the reader can + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. - + mimetype: application/x-microsoft.net.object.binary.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. - + mimetype: application/x-microsoft.net.object.soap.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 - value : The object must be serialized into a byte array + value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> @@ -118,6 +118,6 @@ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="Message" xml:space="preserve"> - <value>No accessible constructors were found for the type '{0}'.</value> + <value>No constructors on type '{0}' can be found with the constructor finder '{1}'.</value> </data> -</root> \ No newline at end of file +</root> diff --git a/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs b/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs index 3dd6f8467..0561d060b 100644 --- a/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs +++ b/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs @@ -83,7 +83,7 @@ public void ConfigurePipeline(IComponentRegistryServices componentRegistryServic if (availableConstructors.Length == 0) { - throw new NoConstructorsFoundException(_implementationType, string.Format(CultureInfo.CurrentCulture, ReflectionActivatorResources.NoConstructorsAvailable, _implementationType, ConstructorFinder)); + throw new NoConstructorsFoundException(_implementationType, ConstructorFinder); } var binders = new ConstructorBinder[availableConstructors.Length]; @@ -131,7 +131,7 @@ private void UseSingleConstructorActivation(IResolvePipelineBuilder pipelineBuil // This is not going to happen, because there is only 1 constructor, that constructor has no parameters, // so there are no conditions under which GetConstructorInvoker will return null in this path. // Throw an error here just in case (and to satisfy nullability checks). - throw new NoConstructorsFoundException(_implementationType, string.Format(CultureInfo.CurrentCulture, ReflectionActivatorResources.NoConstructorsAvailable, _implementationType, ConstructorFinder)); + throw new NoConstructorsFoundException(_implementationType, ConstructorFinder); } // If there are no arguments to the constructor, bypass all argument binding and pre-bind the constructor. diff --git a/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx b/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx index 120f587f3..947acb4d6 100644 --- a/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx +++ b/src/Autofac/Core/Activators/Reflection/ReflectionActivatorResources.resx @@ -1,17 +1,17 @@ <?xml version="1.0" encoding="utf-8"?> <root> - <!-- - Microsoft ResX Schema - + <!-- + Microsoft ResX Schema + Version 2.0 - - The primary goals of this format is to allow a simple XML format - that is mostly human readable. The generation and parsing of the - various data types are done through the TypeConverter classes + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes associated with the data types. - + Example: - + ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> @@ -26,36 +26,36 @@ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> - - There are any number of "resheader" rows that contain simple + + There are any number of "resheader" rows that contain simple name/value pairs. - - Each data row contains a name, and value. The row also contains a - type or mimetype. Type corresponds to a .NET class that support - text/value conversion through the TypeConverter architecture. - Classes that don't support this are serialized and stored with the + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the mimetype set. - - The mimetype is used for serialized objects, and tells the - ResXResourceReader how to depersist the object. This is currently not + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: - - Note - application/x-microsoft.net.object.binary.base64 is the format - that the ResXResourceWriter will generate, however the reader can + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. - + mimetype: application/x-microsoft.net.object.binary.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. - + mimetype: application/x-microsoft.net.object.soap.base64 - value : The object must be serialized with + value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 - value : The object must be serialized into a byte array + value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> @@ -120,9 +120,6 @@ <data name="ConstructorSelectorCannotSelectAnInvalidBinding" xml:space="preserve"> <value>The constructor selector provided by '{0}' selected a binding that cannot be instantiated. Selectors must return a constructor where 'CanInstantiate' is true.</value> </data> - <data name="NoConstructorsAvailable" xml:space="preserve"> - <value>No constructors on type '{0}' can be found with the constructor finder '{1}'.</value> - </data> <data name="NoConstructorsBindable" xml:space="preserve"> <value>None of the constructors found with '{0}' on type '{1}' can be invoked with the available services and parameters:{2}</value> </data> diff --git a/src/Autofac/Features/OpenGenerics/OpenGenericDecoratorRegistrationSource.cs b/src/Autofac/Features/OpenGenerics/OpenGenericDecoratorRegistrationSource.cs index c5c05c226..7195926b4 100644 --- a/src/Autofac/Features/OpenGenerics/OpenGenericDecoratorRegistrationSource.cs +++ b/src/Autofac/Features/OpenGenerics/OpenGenericDecoratorRegistrationSource.cs @@ -64,9 +64,13 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun throw new ArgumentNullException(nameof(registrationAccessor)); } - if (OpenGenericServiceBinder.TryBindOpenGenericService(service, _registrationData.Services, _activatorData.ImplementationType, out Type? constructedImplementationType, out Service[]? services)) + if (service is not IServiceWithType swt) + { + return Enumerable.Empty<IComponentRegistration>(); + } + + if (OpenGenericServiceBinder.TryBindOpenGenericTypedService(swt, _registrationData.Services, _activatorData.ImplementationType, out Type? constructedImplementationType, out Service[]? services)) { - var swt = (IServiceWithType)service; var fromService = _activatorData.FromService.ChangeType(swt.ServiceType); return registrationAccessor(fromService) diff --git a/src/Autofac/Features/OpenGenerics/OpenGenericDelegateRegistrationSource.cs b/src/Autofac/Features/OpenGenerics/OpenGenericDelegateRegistrationSource.cs index 0f4c0f1ef..4cd32cc35 100644 --- a/src/Autofac/Features/OpenGenerics/OpenGenericDelegateRegistrationSource.cs +++ b/src/Autofac/Features/OpenGenerics/OpenGenericDelegateRegistrationSource.cs @@ -47,7 +47,12 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun throw new ArgumentNullException(nameof(registrationAccessor)); } - if (OpenGenericServiceBinder.TryBindOpenGenericDelegate(service, _registrationData.Services, _activatorData.Factory, out var constructedFactory, out Service[]? services)) + if (service is not IServiceWithType swt) + { + yield break; + } + + if (OpenGenericServiceBinder.TryBindOpenGenericDelegateService(swt, _registrationData.Services, _activatorData.Factory, out var constructedFactory, out Service[]? services)) { // Pass the pipeline builder from the original registration to the 'CreateRegistration'. // So the original registration will contain all of the pipeline stages originally added, plus anything we want to add. diff --git a/src/Autofac/Features/OpenGenerics/OpenGenericRegistrationSource.cs b/src/Autofac/Features/OpenGenerics/OpenGenericRegistrationSource.cs index 73bd1b1c3..bd0a9426b 100644 --- a/src/Autofac/Features/OpenGenerics/OpenGenericRegistrationSource.cs +++ b/src/Autofac/Features/OpenGenerics/OpenGenericRegistrationSource.cs @@ -59,7 +59,12 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun throw new ArgumentNullException(nameof(registrationAccessor)); } - if (OpenGenericServiceBinder.TryBindOpenGenericService(service, _registrationData.Services, _activatorData.ImplementationType, out Type? constructedImplementationType, out Service[]? services)) + if (service is not IServiceWithType swt) + { + yield break; + } + + if (OpenGenericServiceBinder.TryBindOpenGenericTypedService(swt, _registrationData.Services, _activatorData.ImplementationType, out Type? constructedImplementationType, out Service[]? services)) { // Pass the pipeline builder from the original registration to the 'CreateRegistration'. // So the original registration will contain all of the pipeline stages originally added, plus anything we want to add. diff --git a/src/Autofac/Features/OpenGenerics/OpenGenericServiceBinder.cs b/src/Autofac/Features/OpenGenerics/OpenGenericServiceBinder.cs index e7de4266f..670c596e6 100644 --- a/src/Autofac/Features/OpenGenerics/OpenGenericServiceBinder.cs +++ b/src/Autofac/Features/OpenGenerics/OpenGenericServiceBinder.cs @@ -12,60 +12,6 @@ namespace Autofac.Features.OpenGenerics; /// </summary> internal static class OpenGenericServiceBinder { - /// <summary> - /// Given a closed generic service (that is being requested), creates a closed generic implementation type - /// and associated services from the open generic implementation and services. - /// </summary> - /// <param name="closedService">The closed generic service to bind.</param> - /// <param name="configuredOpenGenericServices">The set of configured open generic services.</param> - /// <param name="openGenericImplementationType">The implementation type of the open generic.</param> - /// <param name="constructedImplementationType">The built closed generic implementation type.</param> - /// <param name="constructedServices">The built closed generic services.</param> - /// <returns>True if the closed generic service can be bound. False otherwise.</returns> - public static bool TryBindOpenGenericService( - Service closedService, - IEnumerable<Service> configuredOpenGenericServices, - Type openGenericImplementationType, - [NotNullWhen(returnValue: true)] out Type? constructedImplementationType, - [NotNullWhen(returnValue: true)] out Service[]? constructedServices) - { - if (closedService is IServiceWithType swt) - { - return TryBindOpenGenericTypedService(swt, configuredOpenGenericServices, openGenericImplementationType, out constructedImplementationType, out constructedServices); - } - - constructedImplementationType = null; - constructedServices = null; - return false; - } - - /// <summary> - /// Given a closed generic service (that is being requested), creates a closed generic implementation type - /// and associated services from the open generic implementation and services. - /// </summary> - /// <param name="closedService">The closed generic service to bind.</param> - /// <param name="configuredOpenGenericServices">The set of configured open generic services.</param> - /// <param name="openGenericFactory">Delegate responsible for generating an instance of a closed generic based on the open generic type being registered.</param> - /// <param name="constructedFactory">The built closed generic implementation type.</param> - /// <param name="constructedServices">The built closed generic services.</param> - /// <returns>True if the closed generic service can be bound. False otherwise.</returns> - public static bool TryBindOpenGenericDelegate( - Service closedService, - IEnumerable<Service> configuredOpenGenericServices, - Func<IComponentContext, Type[], IEnumerable<Parameter>, object> openGenericFactory, - [NotNullWhen(returnValue: true)] out Func<IComponentContext, IEnumerable<Parameter>, object>? constructedFactory, - [NotNullWhen(returnValue: true)] out Service[]? constructedServices) - { - if (closedService is IServiceWithType swt) - { - return TryBindOpenGenericDelegateService(swt, configuredOpenGenericServices, openGenericFactory, out constructedFactory, out constructedServices); - } - - constructedFactory = null; - constructedServices = null; - return false; - } - /// <summary> /// Given a closed generic service (that is being requested), creates a closed generic implementation type /// and associated services from the open generic implementation and services. @@ -76,6 +22,7 @@ public static bool TryBindOpenGenericDelegate( /// <param name="constructedImplementationType">The built closed generic implementation type.</param> /// <param name="constructedServices">The built closed generic services.</param> /// <returns>True if the closed generic service can be bound. False otherwise.</returns> + [SuppressMessage("CA1851", "CA1851", Justification = "The CPU cost in enumerating the list of services is low, while allocating a new list saves little in CPU but costs a lot in allocations.")] public static bool TryBindOpenGenericTypedService( IServiceWithType serviceWithType, IEnumerable<Service> configuredOpenGenericServices, @@ -88,7 +35,7 @@ public static bool TryBindOpenGenericTypedService( var definitionService = (IServiceWithType)serviceWithType.ChangeType(serviceWithType.ServiceType.GetGenericTypeDefinition()); var serviceGenericArguments = serviceWithType.ServiceType.GetGenericArguments(); - if (configuredOpenGenericServices.Cast<IServiceWithType>().Any(s => s.Equals(definitionService))) + if (configuredOpenGenericServices.OfType<IServiceWithType>().Any(s => s.Equals(definitionService))) { var implementorGenericArguments = TryMapImplementationGenericArguments( openGenericImplementationType, serviceWithType.ServiceType, definitionService.ServiceType, serviceGenericArguments); @@ -99,7 +46,7 @@ public static bool TryBindOpenGenericTypedService( var constructedImplementationTypeTmp = openGenericImplementationType.MakeGenericType(implementorGenericArguments!); var implementedServices = configuredOpenGenericServices - .Cast<IServiceWithType>() + .OfType<IServiceWithType>() .Where(s => s.ServiceType.GetGenericArguments().Length == serviceGenericArguments.Length) .Select(s => new { ServiceWithType = s, GenericService = s.ServiceType.MakeGenericType(serviceGenericArguments) }) .Where(p => p.GenericService.IsAssignableFrom(constructedImplementationTypeTmp)) @@ -131,6 +78,7 @@ public static bool TryBindOpenGenericTypedService( /// <param name="constructedFactory">The built closed generic implementation type.</param> /// <param name="constructedServices">The built closed generic services.</param> /// <returns>True if the closed generic service can be bound. False otherwise.</returns> + [SuppressMessage("CA1851", "CA1851", Justification = "The CPU cost in enumerating the list of services is low, while allocating a new list saves little in CPU but costs a lot in allocations.")] public static bool TryBindOpenGenericDelegateService( IServiceWithType serviceWithType, IEnumerable<Service> configuredOpenGenericServices, @@ -143,7 +91,7 @@ public static bool TryBindOpenGenericDelegateService( var definitionService = (IServiceWithType)serviceWithType.ChangeType(serviceWithType.ServiceType.GetGenericTypeDefinition()); var serviceGenericArguments = serviceWithType.ServiceType.GetGenericArguments(); - if (configuredOpenGenericServices.Cast<IServiceWithType>().Any(s => s.Equals(definitionService))) + if (configuredOpenGenericServices.OfType<IServiceWithType>().Any(s => s.Equals(definitionService))) { constructedFactory = (ctx, parameters) => openGenericFactory(ctx, serviceGenericArguments, parameters); @@ -257,6 +205,7 @@ private static Type[] GetInterfaces(Type implementationType, Type serviceType) = .Where(i => i.Name == serviceType.Name && i.Namespace == serviceType.Namespace) .ToArray(); + [SuppressMessage("CA1851", "CA1851", Justification = "The CPU cost in enumerating the list of services is low, while allocating a new list saves little in CPU but costs a lot in allocations.")] private static Type? TryFindServiceArgumentForImplementationArgumentDefinition(Type implementationGenericArgumentDefinition, IEnumerable<KeyValuePair<Type, Type>> serviceArgumentDefinitionToArgument) { var matchingRegularType = serviceArgumentDefinitionToArgument
diff --git a/test/Autofac.Test/Core/Activators/Reflection/DefaultConstructorFinderTests.cs b/test/Autofac.Test/Core/Activators/Reflection/DefaultConstructorFinderTests.cs index 18c3f812c..ca21ab499 100644 --- a/test/Autofac.Test/Core/Activators/Reflection/DefaultConstructorFinderTests.cs +++ b/test/Autofac.Test/Core/Activators/Reflection/DefaultConstructorFinderTests.cs @@ -34,6 +34,16 @@ public void CanFindNonPublicConstructorsUsingFinderFunction() Assert.Contains(privateConstructor, constructors); } + [Fact] + public void SupportsZeroPublicConstructorTypes() + { + var finder = new DefaultConstructorFinder(); + var targetType = typeof(NoPublicConstructors); + var constructors = finder.FindConstructors(targetType).ToList(); + + Assert.Empty(constructors); + } + internal class HasConstructors { public HasConstructors() @@ -44,4 +54,11 @@ private HasConstructors(int value) { } } + + internal class NoPublicConstructors + { + private NoPublicConstructors() + { + } + } }
Inconsistent error reporting when no constructors are found ## Describe the Bug I was in the process of writing documentation to explain what to do when the set `IConstructorFinder` is unable to find any constructors on a component type and noticed we have multiple potential reporting mechanisms for the issue: - If using the `DefaultConstructorFinder`, [that finder throws its own `NoConstructorsFoundException`](https://github.com/autofac/Autofac/blob/0c79d7bce06173e358c748a0a3f64f311a901f7f/src/Autofac/Core/Activators/Reflection/DefaultConstructorFinder.cs#L53) using a default message: `No accessible constructors were found for the type '{0}'.` - If using a custom `IConstructorFinder`, [the `ReflectionActivator` throws the `NoConstructorsFoundException`](https://github.com/autofac/Autofac/blob/0c79d7bce06173e358c748a0a3f64f311a901f7f/src/Autofac/Core/Activators/Reflection/ReflectionActivator.cs#L86) but with a custom error message: `No constructors on type '{0}' can be found with the constructor finder '{1}'.` This is not only inconsistent (the interface `IConstructorFinder` indicates you can/should return an empty set and let the activator deal with it) but it also makes it hard to document or prescribe troubleshooting for since the message is so different from one report to another. I propose: - Remove the exception throwing from `DefaultConstructorFinder`. Let the `ReflectionActivator` handle it. - Update the `NoConstructorsFoundException` to have a constructor that takes two parameters - the type being scanned and the type of the constructor finder - and use the message from the `ReflectionActivator` as the message for that constructor. That would make the message (and stack trace) consistent across the default and specified constructor finder and would make documenting the issue easier.
null
2023-01-04T20:22:31Z
0.1
['Autofac.Test.Core.Activators.Reflection.DefaultConstructorFinderTests.SupportsZeroPublicConstructorTypes']
['Autofac.Test.Core.Activators.Reflection.DefaultConstructorFinderTests.FindsPublicConstructorsOnlyByDefault', 'Autofac.Test.Core.Activators.Reflection.DefaultConstructorFinderTests.CanFindNonPublicConstructorsUsingFinderFunction']
autofac/Autofac
autofac__autofac-1352
3465490bfa192512e3db61a1d9a2441d7c10171f
diff --git a/src/Autofac/Features/Decorators/DecoratorContext.cs b/src/Autofac/Features/Decorators/DecoratorContext.cs index 3929fbdbd..d674814a8 100644 --- a/src/Autofac/Features/Decorators/DecoratorContext.cs +++ b/src/Autofac/Features/Decorators/DecoratorContext.cs @@ -1,6 +1,8 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. +using Autofac.Core; + namespace Autofac.Features.Decorators; /// <summary> @@ -8,6 +10,8 @@ namespace Autofac.Features.Decorators; /// </summary> public sealed class DecoratorContext : IDecoratorContext { + private readonly IComponentContext _componentContext; + /// <inheritdoc /> public Type ImplementationType { get; private set; } @@ -23,13 +27,18 @@ public sealed class DecoratorContext : IDecoratorContext /// <inheritdoc /> public object CurrentInstance { get; private set; } + /// <inheritdoc /> + public IComponentRegistry ComponentRegistry => _componentContext.ComponentRegistry; + private DecoratorContext( + IComponentContext componentContext, Type implementationType, Type serviceType, object currentInstance, IReadOnlyList<Type>? appliedDecoratorTypes = null, IReadOnlyList<object>? appliedDecorators = null) { + _componentContext = componentContext; ImplementationType = implementationType; ServiceType = serviceType; CurrentInstance = currentInstance; @@ -40,13 +49,14 @@ private DecoratorContext( /// <summary> /// Create a new <see cref="DecoratorContext"/>. /// </summary> + /// <param name="componentContext">The component context this decorator context sits in.</param> /// <param name="implementationType">The type of the concrete implementation.</param> /// <param name="serviceType">The service type being decorated.</param> /// <param name="implementationInstance">The instance of the implementation to be decorated.</param> /// <returns>A new decorator context.</returns> - internal static DecoratorContext Create(Type implementationType, Type serviceType, object implementationInstance) + internal static DecoratorContext Create(IComponentContext componentContext, Type implementationType, Type serviceType, object implementationInstance) { - return new DecoratorContext(implementationType, serviceType, implementationInstance); + return new DecoratorContext(componentContext, implementationType, serviceType, implementationInstance); } /// <summary> @@ -64,6 +74,9 @@ internal DecoratorContext UpdateContext(object decoratorInstance) appliedDecoratorTypes.AddRange(AppliedDecoratorTypes); appliedDecoratorTypes.Add(decoratorInstance.GetType()); - return new DecoratorContext(ImplementationType, ServiceType, decoratorInstance, appliedDecoratorTypes, appliedDecorators); + return new DecoratorContext(_componentContext, ImplementationType, ServiceType, decoratorInstance, appliedDecoratorTypes, appliedDecorators); } + + /// <inheritdoc /> + public object ResolveComponent(ResolveRequest request) => _componentContext.ResolveComponent(request); } diff --git a/src/Autofac/Features/Decorators/DecoratorMiddleware.cs b/src/Autofac/Features/Decorators/DecoratorMiddleware.cs index d4abceebc..4521c8d05 100644 --- a/src/Autofac/Features/Decorators/DecoratorMiddleware.cs +++ b/src/Autofac/Features/Decorators/DecoratorMiddleware.cs @@ -62,7 +62,7 @@ public void Execute(ResolveRequestContext context, Action<ResolveRequestContext> if (context.DecoratorContext is null) { - context.DecoratorContext = DecoratorContext.Create(context.Instance.GetType(), serviceType, context.Instance); + context.DecoratorContext = DecoratorContext.Create(context, context.Instance.GetType(), serviceType, context.Instance); } else { diff --git a/src/Autofac/Features/Decorators/IDecoratorContext.cs b/src/Autofac/Features/Decorators/IDecoratorContext.cs index 164065884..bffd31db5 100644 --- a/src/Autofac/Features/Decorators/IDecoratorContext.cs +++ b/src/Autofac/Features/Decorators/IDecoratorContext.cs @@ -6,7 +6,7 @@ namespace Autofac.Features.Decorators; /// <summary> /// Defines the context interface used during the decoration process. /// </summary> -public interface IDecoratorContext +public interface IDecoratorContext : IComponentContext { /// <summary> /// Gets the implementation type of the service that is being decorated.
diff --git a/test/Autofac.Specification.Test/Features/DecoratorTests.cs b/test/Autofac.Specification.Test/Features/DecoratorTests.cs index 87382fa0b..77e1cc4c0 100644 --- a/test/Autofac.Specification.Test/Features/DecoratorTests.cs +++ b/test/Autofac.Specification.Test/Features/DecoratorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. +using Autofac.Core; using Autofac.Features.Decorators; using Autofac.Features.Metadata; using Autofac.Features.OwnedInstances; @@ -1252,6 +1253,40 @@ public void OpenGenericInModuleCanBeDecoratoredByDecoratorOutsideModuleWhereModu Assert.IsType<GenericComponent<int>>(((GenericDecorator<int>)instance).Decorated); } + [Fact] + public void DecoratorConditionalFunctionCanResolveFromContext() + { + var builder = new ContainerBuilder(); + builder.RegisterInstance(new ConditionalShouldDecorate { ShouldDecorate = true }); + builder.RegisterType<ImplementorA>().As<IDecoratedService>(); + builder.RegisterDecorator<DecoratorA, IDecoratedService>(context => context.Resolve<ConditionalShouldDecorate>().ShouldDecorate); + + var container = builder.Build(); + + var instance = container.Resolve<IDecoratedService>(); + + Assert.IsType<DecoratorA>(instance); + Assert.IsType<ImplementorA>(instance.Decorated); + } + + [Fact] + public void DecoratorConditionalFunctionThrowsCircularDependencyErrorOnResolveSelf() + { + var builder = new ContainerBuilder(); + builder.RegisterInstance(new ConditionalShouldDecorate { ShouldDecorate = true }); + builder.RegisterType<ImplementorA>().As<IDecoratedService>(); + builder.RegisterDecorator<DecoratorA, IDecoratedService>(context => + { + // Can't do this; circular reference. + context.Resolve<IDecoratedService>(); + return true; + }); + + var container = builder.Build(); + + Assert.Throws<DependencyResolutionException>(() => container.Resolve<IDecoratedService>()); + } + private class MyMetadata { public int A { get; set; } @@ -1457,4 +1492,9 @@ public GenericDecorator(IGenericService<T> decorated) public IGenericService<T> Decorated { get; } } + + private class ConditionalShouldDecorate + { + public bool ShouldDecorate { get; set; } + } } diff --git a/test/Autofac.Test/Features/Decorators/DecoratorContextTests.cs b/test/Autofac.Test/Features/Decorators/DecoratorContextTests.cs index bfc5636c3..24f3bdd78 100644 --- a/test/Autofac.Test/Features/Decorators/DecoratorContextTests.cs +++ b/test/Autofac.Test/Features/Decorators/DecoratorContextTests.cs @@ -12,7 +12,7 @@ public void CreateSetsContextToPreDecoratedState() { const string implementationInstance = "Initial"; - var context = DecoratorContext.Create(typeof(string), typeof(string), implementationInstance); + var context = DecoratorContext.Create(Factory.CreateEmptyContext(), typeof(string), typeof(string), implementationInstance); Assert.Equal(typeof(string), context.ServiceType); Assert.Equal(typeof(string), context.ImplementationType); @@ -25,7 +25,7 @@ public void CreateSetsContextToPreDecoratedState() public void UpdateAddsDecoratorStateToContext() { const string implementationInstance = "Initial"; - var context = DecoratorContext.Create(typeof(string), typeof(string), implementationInstance); + var context = DecoratorContext.Create(Factory.CreateEmptyContext(), typeof(string), typeof(string), implementationInstance); const string decoratorA = "DecoratorA"; context = context.UpdateContext(decoratorA); diff --git a/test/Autofac.Test/Features/Decorators/DecoratorServiceTests.cs b/test/Autofac.Test/Features/Decorators/DecoratorServiceTests.cs index 10cb15a62..03c64c850 100644 --- a/test/Autofac.Test/Features/Decorators/DecoratorServiceTests.cs +++ b/test/Autofac.Test/Features/Decorators/DecoratorServiceTests.cs @@ -19,7 +19,7 @@ public void ConditionDefaultsToTrueWhenNotProvided() { var service = new DecoratorService(typeof(string)); - var context = DecoratorContext.Create(typeof(string), typeof(string), "A"); + var context = DecoratorContext.Create(Factory.CreateEmptyContext(), typeof(string), typeof(string), "A"); Assert.True(service.Condition(context)); }
Allow access to constructed container when deciding whether or not a decorator should be applied ## Problem Statement There is support today for conditionally applying decorators by providing a lambda on the `RegisterDecorator` call. However, only information about the instance being decorated is provided there, so it is impossible to request something from the container that could be relevant to making the decision. I have a scenario where I need to inspect an `IOptionsSnapshot<T>` object with a specific setting to decide whether or not a given decorator should be applied. This must be done everytime the decorator is attempted to be resolved, so that the setting can work "in real time" (i.e. without having to restart the application). ## Desired Solution The overload to `Decorate` that takes a decision predicate should be expanded to also provide the `IContainer` itself so that the caller can resolve services from the container at the time of the decision is made. https://github.com/autofac/Autofac/blob/f56d1fe90f322042ecdf35ecc38cabeb71b27295/src/Autofac/RegistrationExtensions.Decorators.cs#L162 This should have a variation such as: ```csharp public static void RegisterDecorator<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TDecorator, TService>( this ContainerBuilder builder, Func<IDecoratorContext, IContainer, bool>? condition = null) where TDecorator : notnull, TService ``` ## Alternatives You've Considered As a poor-man's alternative, I used the overloads that don't take a concrete decorator (which expose `IContainer`) and then manually constructed my decorator there based on a service registered in the container, or used the `instance` value when no decoration was needed. This works, but is more convoluted/less flexible. ```csharp builder.RegisterDecorator<IMyService>( (context, parameters, instance) => { if (context.Resolve<IOptionsSnapshot<MyOptions>>().Value.EnableStuffing) { return new StuffedService(instance); } else { return instance; } }); ``` This also becomes unwieldy when the concrete decorator takes more dependencies, as you have to also manually resolve each one.
OK, I can see the benefit of being able to resolve services inside the condition callback. Might I propose though that instead of adding `IContainer` or a similar scope to the callback signature, we make `IDecoratorContext` derive from `IComponentContext`? That means the decorator context would provide all the resolve functionality of `IContainer`/`ILifetimeScope` without modifying the signature, so you could do: ```csharp builder.RegisterDecorator<MyDecorator, IMyService>( context => context.Resolve<IOptionsSnapshot<MyOptions>>().Value.EnableStuffing) ``` Does that seem ok, and would you be willing to raise a PR to that effect? I actually don't think the changes are particularly complicated; when we create the `DecoratorContext` in `DecoratorMiddleware` we can pass in the `ResolveRequestContext`, and route all requests done via `DecoratorContext` through that provided request context. > Might I propose though that instead of adding `IContainer` or a similar scope to the callback signature, we make `IDecoratorContext` derive from `IComponentContext`? > > That means the decorator context would provide all the resolve functionality of `IContainer`/`ILifetimeScope` without modifying the signature, so you could do: > > ```cs > builder.RegisterDecorator<MyDecorator, IMyService>( > context => context.Resolve<IOptionsSnapshot<MyOptions>>().Value.EnableStuffing) > ``` > > Does that seem ok... That's perfectly fine in my book. >..., and would you be willing to raise a PR to that effect? It is unlikely I'll be able to, but not impossible. I'm actually only dealing with Autofac here in a legacy integration, which is where I stumbled upon the situation I described. If I do, I'll let everyone know by replying here before starting though.
2022-10-02T18:06:01Z
0.1
[]
['Autofac.Specification.Test.Features.DecoratorTests.DecoratorRegistrationsGetAppliedInOrderAdded', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenSingleDecoratorRegistered', 'Autofac.Specification.Test.Features.DecoratorTests.StartableTypesCanBeDecorated', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenNoDecoratorsRegistered', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenMultipleDecoratorRegistered', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorInheritsDecoratedLifetimeWhenInstancePerDependency', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorRegisteredAsLambdaCanAcceptAdditionalParameters', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesWithMultipleDecoratorsInstancePerLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorCanBeRegisteredInChildLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesThenLatestServiceWithSingleInstance', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorInheritsDecoratedLifetimeWhenInstancePerMatchingLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.OpenGenericInModuleCanBeDecoratoredByDecoratorOutsideModuleWhereModuleRegisteredFirst', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesInstancePerLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithFunc', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesWithMultipleDecorators', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorAppliedOnlyOnceToComponentWithExternalRegistrySource', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorCanBeAppliedTwice', 'Autofac.Specification.Test.Features.DecoratorTests.OpenGenericCanBeDecoratedFromInsideAModuleDecoratorRegisteredSecond', 'Autofac.Specification.Test.Features.DecoratorTests.CanApplyDecoratorConditionallyAtRuntime', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratedRegistrationCanIncludeImplementationType', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorAndDecoratedBothDisposedWhenSingleInstance', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithOwned', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenTargetHasOnActivatingHandlerOnType', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithStronglyTypedMeta', 'Autofac.Specification.Test.Features.DecoratorTests.CanInjectDecoratorContextAsSnapshot', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorsApplyToNamedAndDefaultServices', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorAndDecoratedBothDisposedWhenInstancePerDependency', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorCanBeAppliedToServiceRegisteredInChildLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesWithMultipleDecoratorsSingleInstance', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesThenLatestService', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorsApplyToKeyedServices', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorAndDecoratedBothDisposedWhenInstancePerLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorRegisteredAsLambdaCanBeResolved', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesSingleInstance', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorCanBeAppliedTwiceIntentionallyWithExternalRegistrySource', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServices', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorRegisteredOnLambdaWithCast', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenTargetHasOnActivatedHandlerOnType', 'Autofac.Specification.Test.Features.DecoratorTests.ParametersArePassedThroughDecoratorChain', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenRegisteredWithoutGenericConstraint', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithMeta', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenTargetHasOnActivatedHandlerOnInterface', 'Autofac.Specification.Test.Features.DecoratorTests.OpenGenericCanBeDecoratedFromInsideAModuleDecoratorRegisteredFirst', 'Autofac.Specification.Test.Features.DecoratorTests.OpenGenericInModuleCanBeDecoratoredByDecoratorOutsideModuleWhereModuleRegisteredSecond', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithLazy', 'Autofac.Specification.Test.Features.DecoratorTests.ParametersCanBeConfiguredOnDecoratedService', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorCanBeAppliedTwiceInChildLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorInheritsDecoratedLifetimeWhenInstancePerLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorShouldBeAppliedRegardlessOfServiceOrder', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveMultipleDecoratedServicesWithMultipleDecoratorsThenLatestService', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorAndDecoratedBothDisposedWhenInstancePerMatchingLifetimeScope', 'Autofac.Specification.Test.Features.DecoratorTests.ResolvesDecoratedServiceWhenTargetHasOnActivatingHandlerOnInterface', 'Autofac.Specification.Test.Features.DecoratorTests.DecoratorInheritsDecoratedLifetimeWhenSingleInstance', 'Autofac.Specification.Test.Features.DecoratorTests.CanResolveDecoratorWithLazyWithMetadata']
StackExchange/StackExchange.Redis
stackexchange__stackexchangeredis-2397
1364ef83fedb2e09035cc77ae2ac9b1b9c0ebc90
diff --git a/docs/ReleaseNotes.md b/docs/ReleaseNotes.md index d1cd9e7cb..dd5d92f83 100644 --- a/docs/ReleaseNotes.md +++ b/docs/ReleaseNotes.md @@ -8,6 +8,7 @@ Current package versions: ## Unreleased +- Fix [#2392](https://github.com/StackExchange/StackExchange.Redis/issues/2392): Dequeue *all* timed out messages from the backlog when not connected (including Fire+Forget) ([#2397 by kornelpal](https://github.com/StackExchange/StackExchange.Redis/pull/2397)) - Fix [#2400](https://github.com/StackExchange/StackExchange.Redis/issues/2400): Expose `ChannelMessageQueue` as `IAsyncEnumerable<ChannelMessage>` ([#2402 by mgravell](https://github.com/StackExchange/StackExchange.Redis/pull/2402)) - Add: support for `CLIENT SETINFO` (lib name/version) during handshake; opt-out is via `ConfigurationOptions`; also support read of `resp`, `lib-ver` and `lib-name` via `CLIENT LIST` ([#2414 by mgravell](https://github.com/StackExchange/StackExchange.Redis/pull/2414)) diff --git a/src/StackExchange.Redis/PhysicalBridge.cs b/src/StackExchange.Redis/PhysicalBridge.cs index efcd6518f..7fa8af27f 100644 --- a/src/StackExchange.Redis/PhysicalBridge.cs +++ b/src/StackExchange.Redis/PhysicalBridge.cs @@ -869,14 +869,14 @@ private void CheckBacklogForTimeouts() while (_backlog.TryPeek(out Message? message)) { // See if the message has pass our async timeout threshold - // or has otherwise been completed (e.g. a sync wait timed out) which would have cleared the ResultBox - if (!message.HasTimedOut(now, timeout, out var _) || message.ResultBox == null) break; // not a timeout - we can stop looking + // Note: All timed out messages must be dequeued, even when no completion is needed, to be able to dequeue and complete other timed out messages. + if (!message.HasTimedOut(now, timeout, out var _)) break; // not a timeout - we can stop looking lock (_backlog) { // Peek again since we didn't have lock before... // and rerun the exact same checks as above, note that it may be a different message now if (!_backlog.TryPeek(out message)) break; - if (!message.HasTimedOut(now, timeout, out var _) && message.ResultBox != null) break; + if (!message.HasTimedOut(now, timeout, out var _)) break; if (!BacklogTryDequeue(out var message2) || (message != message2)) // consume it for real { @@ -884,10 +884,15 @@ private void CheckBacklogForTimeouts() } } - // Tell the message it has failed - // Note: Attempting to *avoid* reentrancy/deadlock issues by not holding the lock while completing messages. - var ex = Multiplexer.GetException(WriteResult.TimeoutBeforeWrite, message, ServerEndPoint); - message.SetExceptionAndComplete(ex, this); + // We only handle async timeouts here, synchronous timeouts are handled upstream. + // Those sync timeouts happen in ConnectionMultiplexer.ExecuteSyncImpl() via Monitor.Wait. + if (message.ResultBoxIsAsync) + { + // Tell the message it has failed + // Note: Attempting to *avoid* reentrancy/deadlock issues by not holding the lock while completing messages. + var ex = Multiplexer.GetException(WriteResult.TimeoutBeforeWrite, message, ServerEndPoint); + message.SetExceptionAndComplete(ex, this); + } } }
diff --git a/tests/StackExchange.Redis.Tests/Issues/Issue2392Tests.cs b/tests/StackExchange.Redis.Tests/Issues/Issue2392Tests.cs new file mode 100644 index 000000000..fe3e9673d --- /dev/null +++ b/tests/StackExchange.Redis.Tests/Issues/Issue2392Tests.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace StackExchange.Redis.Tests.Issues +{ + public class Issue2392Tests : TestBase + { + public Issue2392Tests(ITestOutputHelper output) : base(output) { } + + [Fact] + public async Task Execute() + { + var options = new ConfigurationOptions() + { + BacklogPolicy = new() + { + QueueWhileDisconnected = true, + AbortPendingOnConnectionFailure = false, + }, + AbortOnConnectFail = false, + ConnectTimeout = 1, + ConnectRetry = 0, + AsyncTimeout = 1, + SyncTimeout = 1, + AllowAdmin = true, + }; + options.EndPoints.Add("127.0.0.1:1234"); + + using var conn = await ConnectionMultiplexer.ConnectAsync(options, Writer); + var key = Me(); + var db = conn.GetDatabase(); + var server = conn.GetServerSnapshot()[0]; + + // Fail the connection + conn.AllowConnect = false; + server.SimulateConnectionFailure(SimulatedFailureType.All); + Assert.False(conn.IsConnected); + + await db.StringGetAsync(key, flags: CommandFlags.FireAndForget); + var ex = await Assert.ThrowsAnyAsync<Exception>(() => db.StringGetAsync(key).WithTimeout(5000)); + Assert.True(ex is RedisTimeoutException or RedisConnectionException); + } + } +}
[FireAndForget, Timeouts] Redis won't timeout requests if there is connection issue and FireAnfForget request is queued Hi, recently we observed that when Redis is not accessible to our microservices than they stop responding to requests. This was quite a shock as we always relayed on Redis as on service that is not guaranteed. Therefore we strongly relay on short timeouts and in case Redis is not available we always upstream requests to source of truth. However some time ago we started to use FireAndForget flag for requests that did not require to complete (best effort). This was ideal when invalidating cache and similar use cases. It seems that when we queue such request in time when there is network partition to Redis instance or some fail over procedure is in progress than all subsequent request to Redis on every thread using same connection multiplexer hangs for ever (until Redis instance is back and accessible). Check this simple test: ```csharp [Fact] public async Task IssueReproduction() { // connection to fake service var connection = await ConnectionMultiplexer.ConnectAsync(new ConfigurationOptions { EndPoints = new EndPointCollection(new List<EndPoint>{new DnsEndPoint("localhost", 1111)}), AsyncTimeout = 500, SyncTimeout = 500, ConnectTimeout = 500, ConnectRetry = 0, AbortOnConnectFail = false }); // Timeouts works when we try to get something from Redis var stopwatch = Stopwatch.StartNew(); try { await connection.GetDatabase().StringGetAsync("fake-key"); } catch (RedisTimeoutException) { } stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); // After we try to set something it will work as well stopwatch.Restart(); try { await connection.GetDatabase().StringSetAsync("fake-key", "value", TimeSpan.FromHours(1), flags: CommandFlags.None); } catch (RedisTimeoutException) { } stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); // It still works when we get something stopwatch.Restart(); try { await connection.GetDatabase().StringGetAsync("fake-key"); } catch (RedisTimeoutException) { } stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); // It works for first fire-and-forget set stopwatch.Restart(); try { await connection.GetDatabase().StringSetAsync("fake-key", "value", TimeSpan.FromHours(1), flags: CommandFlags.FireAndForget); } catch (RedisTimeoutException) { } stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2)); // BUT after first fire and forget set it stops respecting timeouts and hangs all future requests for ever await connection.GetDatabase().StringGetAsync("fake-key"); throw new Exception("THIS WILL NOT BE THROWN!"); } ``` We are on latest version of `StackExchange.Redis` assembly `2.6.96`. Is it right approach to use FireAndForget mode to speed such invalidations/updates when we hope it will succeed but we do not want to block parent request waiting for Redis response? Like I said best effort to set something in cache in background. Is it expected that it disrupt timeouts for every subsequent request?
This seems odd; I agree that this isn't intentional but a quick glance at the code doesn't show any obvious smoking guns - the timeout detection code doesn't check for F+F, it just checks the write time - and the write time is written regardless. Will need to look. I've forgot to mention it hangs on .NET6 and .NET7. Any luck identifying issue behind ? @mgravell have you looked at this issue ? It seems serious problem if someone relay on F+F mode and timeouts. I've tried to check where it hangs and it seems that this line is issue: https://github.com/StackExchange/StackExchange.Redis/blob/main/src/StackExchange.Redis/PhysicalBridge.cs#L873 For F+F request `message.ResultBox` is `null` which breaks `CheckBacklogForTimeouts` and pending in queue messages that should be timeout are not timeouting. Should there be `continue`? There still is issue with this `_backlog` which you simply `TryPeek` so you want cheek next requests Not sure if that is any option :P but removing ` || message.ResultBox == null` does a job :P for this timeout issue. Introduced within: https://github.com/StackExchange/StackExchange.Redis/commit/7dda23a036892a53cba6781a413ee0efb2d304fd#diff-c64610826746e4cc2aeb0edf12469d2ea64583486a9246f7493d197bc33c6af1R856 Perhaps you need better way to determine completed messages. > have you looked at this issue Briefly, as per my previous comment - when I looked at the *other* place timeout can happen, in the sent queue. Ultimately, this isn't my day job, and not everything can be done immediately. I do agree with your analysis about the pending queue and the `null` result box. The "simple" fix here would be to rip F+F messages from the pending queue and drop them on the floor (there's nobody to tell about a timeout). It *might* be possible to do something more exotic, though, that preserves them - even if we simply dequeue them, reset their timeout, and enqueue them back at the end. I'll have a think about which might be more desirable in the F+F area. I would assume that if someone is explicitly using F+F option he doesn't care about being informed whether operation succeeded or failed and is accepting the "best effort" nature of this operation like in pattern below: 1. try retrieving data from cache 2. if not present take data from source of truth 2.1 after retrieving data from source of truth populate cache using F+F Probably the the worst thing we can do here is hang in operation which is assumed to be "best effort" anyway. In this context it make sense to remove F+F messages from the pending queue as soon as they are timed out. > It might be possible to do something more exotic, though, that preserves them - even if we simply dequeue them, reset their timeout, and enqueue them back at the end. This solution can result in situation when operations are executed on Redis way past their timeout which kinda breaks the contract with developer who specified the timeout. This can potentially result in consistent data (set by microservice which doesn't have connectivity issues) being overridden by stale data provided by some instance which had connectivity issues. Of course we may argute that such thing can happen regardless but having mechanism that resets the messages timeout definitely increases the risk. I also agree that when using F+F you aim for performance and not guarantees of delivering / success. I agree that re-enqueueing them would have side effects, especially taking into accoun that the timeout set by the dev is already reached so he may have compensating actions, such as read again from the source of truth and cache it, so it will lead to some discrepancy. To not break the contract of the timeout, as soon as requests are timed out as per contract they may be dropped.
2023-03-10T19:09:15Z
0.1
['StackExchange.Redis.Tests.Issues.Issue2392Tests.Execute']
[]
StackExchange/StackExchange.Redis
stackexchange__stackexchangeredis-2480
ae6419a164600b4b54dd7ce8a699efe8e98d8f1c
diff --git a/docs/ReleaseNotes.md b/docs/ReleaseNotes.md index f60adc161..70b49d1b6 100644 --- a/docs/ReleaseNotes.md +++ b/docs/ReleaseNotes.md @@ -8,6 +8,8 @@ Current package versions: ## Unreleased +- Fix [#2479](https://github.com/StackExchange/StackExchange.Redis/issues/2479): Add `RedisChannel.UseImplicitAutoPattern` (global) and `RedisChannel.IsPatternBased` ([#2480 by mgravell](https://github.com/StackExchange/StackExchange.Redis/pull/2480)) +- Fix [#2479](https://github.com/StackExchange/StackExchange.Redis/issues/2479): Mark `RedisChannel` conversion operators as obsolete; add `RedisChannel.Literal` and `RedisChannel.Pattern` helpers ([#2481 by mgravell](https://github.com/StackExchange/StackExchange.Redis/pull/2481)) - Fix [#2449](https://github.com/StackExchange/StackExchange.Redis/issues/2449): Update `Pipelines.Sockets.Unofficial` to `v2.2.8` to support native AOT ([#2456 by eerhardt](https://github.com/StackExchange/StackExchange.Redis/pull/2456)) ## 2.6.111 diff --git a/src/StackExchange.Redis/ConfigurationOptions.cs b/src/StackExchange.Redis/ConfigurationOptions.cs index e9f01264f..da30beb56 100644 --- a/src/StackExchange.Redis/ConfigurationOptions.cs +++ b/src/StackExchange.Redis/ConfigurationOptions.cs @@ -860,7 +860,7 @@ private ConfigurationOptions DoParse(string configuration, bool ignoreUnknown) ClientName = value; break; case OptionKeys.ChannelPrefix: - ChannelPrefix = value; + ChannelPrefix = RedisChannel.Literal(value); break; case OptionKeys.ConfigChannel: ConfigurationChannel = value; diff --git a/src/StackExchange.Redis/ConnectionMultiplexer.Sentinel.cs b/src/StackExchange.Redis/ConnectionMultiplexer.Sentinel.cs index 302bccea9..145826e3c 100644 --- a/src/StackExchange.Redis/ConnectionMultiplexer.Sentinel.cs +++ b/src/StackExchange.Redis/ConnectionMultiplexer.Sentinel.cs @@ -1,11 +1,11 @@ -using System; +using Pipelines.Sockets.Unofficial; +using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; -using Pipelines.Sockets.Unofficial; namespace StackExchange.Redis; @@ -30,9 +30,9 @@ internal void InitializeSentinel(LogProxy? logProxy) // Subscribe to sentinel change events ISubscriber sub = GetSubscriber(); - if (sub.SubscribedEndpoint("+switch-master") == null) + if (sub.SubscribedEndpoint(RedisChannel.Literal("+switch-master")) == null) { - sub.Subscribe("+switch-master", (__, message) => + sub.Subscribe(RedisChannel.Literal("+switch-master"), (__, message) => { string[] messageParts = ((string)message!).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // We don't care about the result of this - we're just trying @@ -68,9 +68,9 @@ internal void InitializeSentinel(LogProxy? logProxy) ReconfigureAsync(first: false, reconfigureAll: true, logProxy, e.EndPoint, "Lost sentinel connection", false).Wait(); // Subscribe to new sentinels being added - if (sub.SubscribedEndpoint("+sentinel") == null) + if (sub.SubscribedEndpoint(RedisChannel.Literal("+sentinel")) == null) { - sub.Subscribe("+sentinel", (_, message) => + sub.Subscribe(RedisChannel.Literal("+sentinel"), (_, message) => { string[] messageParts = ((string)message!).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); UpdateSentinelAddressList(messageParts[0]); diff --git a/src/StackExchange.Redis/ConnectionMultiplexer.cs b/src/StackExchange.Redis/ConnectionMultiplexer.cs index 37d45be09..88c6c37c2 100644 --- a/src/StackExchange.Redis/ConnectionMultiplexer.cs +++ b/src/StackExchange.Redis/ConnectionMultiplexer.cs @@ -2221,7 +2221,7 @@ public long PublishReconfigure(CommandFlags flags = CommandFlags.None) private long PublishReconfigureImpl(CommandFlags flags) => ConfigurationChangedChannel is byte[] channel - ? GetSubscriber().Publish(channel, RedisLiterals.Wildcard, flags) + ? GetSubscriber().Publish(RedisChannel.Literal(channel), RedisLiterals.Wildcard, flags) : 0; /// <summary> @@ -2231,7 +2231,7 @@ ConfigurationChangedChannel is byte[] channel /// <returns>The number of instances known to have received the message (however, the actual number can be higher).</returns> public Task<long> PublishReconfigureAsync(CommandFlags flags = CommandFlags.None) => ConfigurationChangedChannel is byte[] channel - ? GetSubscriber().PublishAsync(channel, RedisLiterals.Wildcard, flags) + ? GetSubscriber().PublishAsync(RedisChannel.Literal(channel), RedisLiterals.Wildcard, flags) : CompletedTask<long>.Default(null); /// <summary> diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs index 290fbed59..3bad77d43 100644 --- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs +++ b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs @@ -841,8 +841,11 @@ protected RedisValue SortGetToInner(RedisValue outer) => } } - protected RedisChannel ToInner(RedisChannel outer) => - RedisKey.ConcatenateBytes(Prefix, null, (byte[]?)outer); + protected RedisChannel ToInner(RedisChannel outer) + { + var combined = RedisKey.ConcatenateBytes(Prefix, null, (byte[]?)outer); + return new RedisChannel(combined, outer.IsPatternBased ? RedisChannel.PatternMode.Pattern : RedisChannel.PatternMode.Literal); + } private Func<RedisKey, RedisKey>? mapFunction; protected Func<RedisKey, RedisKey> GetMapFunction() => diff --git a/src/StackExchange.Redis/Maintenance/AzureMaintenanceEvent.cs b/src/StackExchange.Redis/Maintenance/AzureMaintenanceEvent.cs index c965e1231..330b27683 100644 --- a/src/StackExchange.Redis/Maintenance/AzureMaintenanceEvent.cs +++ b/src/StackExchange.Redis/Maintenance/AzureMaintenanceEvent.cs @@ -130,7 +130,7 @@ internal async static Task AddListenerAsync(ConnectionMultiplexer multiplexer, A return; } - await sub.SubscribeAsync(PubSubChannelName, async (_, message) => + await sub.SubscribeAsync(RedisChannel.Literal(PubSubChannelName), async (_, message) => { var newMessage = new AzureMaintenanceEvent(message!); newMessage.NotifyMultiplexer(multiplexer); diff --git a/src/StackExchange.Redis/PhysicalBridge.cs b/src/StackExchange.Redis/PhysicalBridge.cs index e7af56a69..b42c40a19 100644 --- a/src/StackExchange.Redis/PhysicalBridge.cs +++ b/src/StackExchange.Redis/PhysicalBridge.cs @@ -373,7 +373,7 @@ internal void KeepAlive() else if (commandMap.IsAvailable(RedisCommand.UNSUBSCRIBE)) { msg = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.UNSUBSCRIBE, - (RedisChannel)Multiplexer.UniqueId); + RedisChannel.Literal(Multiplexer.UniqueId)); msg.SetSource(ResultProcessor.TrackSubscriptions, null); } break; diff --git a/src/StackExchange.Redis/PublicAPI/PublicAPI.Shipped.txt b/src/StackExchange.Redis/PublicAPI/PublicAPI.Shipped.txt index ccfb4edb1..464af8023 100644 --- a/src/StackExchange.Redis/PublicAPI/PublicAPI.Shipped.txt +++ b/src/StackExchange.Redis/PublicAPI/PublicAPI.Shipped.txt @@ -1259,6 +1259,7 @@ StackExchange.Redis.Proxy.Twemproxy = 1 -> StackExchange.Redis.Proxy StackExchange.Redis.RedisChannel StackExchange.Redis.RedisChannel.Equals(StackExchange.Redis.RedisChannel other) -> bool StackExchange.Redis.RedisChannel.IsNullOrEmpty.get -> bool +StackExchange.Redis.RedisChannel.IsPatternBased.get -> bool StackExchange.Redis.RedisChannel.PatternMode StackExchange.Redis.RedisChannel.PatternMode.Auto = 0 -> StackExchange.Redis.RedisChannel.PatternMode StackExchange.Redis.RedisChannel.PatternMode.Literal = 1 -> StackExchange.Redis.RedisChannel.PatternMode @@ -1657,6 +1658,8 @@ static StackExchange.Redis.RedisChannel.implicit operator byte[]?(StackExchange. static StackExchange.Redis.RedisChannel.implicit operator StackExchange.Redis.RedisChannel(byte[]? key) -> StackExchange.Redis.RedisChannel static StackExchange.Redis.RedisChannel.implicit operator StackExchange.Redis.RedisChannel(string! key) -> StackExchange.Redis.RedisChannel static StackExchange.Redis.RedisChannel.implicit operator string?(StackExchange.Redis.RedisChannel key) -> string? +static StackExchange.Redis.RedisChannel.Literal(byte[]! value) -> StackExchange.Redis.RedisChannel +static StackExchange.Redis.RedisChannel.Literal(string! value) -> StackExchange.Redis.RedisChannel static StackExchange.Redis.RedisChannel.operator !=(byte[]! x, StackExchange.Redis.RedisChannel y) -> bool static StackExchange.Redis.RedisChannel.operator !=(StackExchange.Redis.RedisChannel x, byte[]! y) -> bool static StackExchange.Redis.RedisChannel.operator !=(StackExchange.Redis.RedisChannel x, StackExchange.Redis.RedisChannel y) -> bool @@ -1667,6 +1670,10 @@ static StackExchange.Redis.RedisChannel.operator ==(StackExchange.Redis.RedisCha static StackExchange.Redis.RedisChannel.operator ==(StackExchange.Redis.RedisChannel x, StackExchange.Redis.RedisChannel y) -> bool static StackExchange.Redis.RedisChannel.operator ==(StackExchange.Redis.RedisChannel x, string! y) -> bool static StackExchange.Redis.RedisChannel.operator ==(string! x, StackExchange.Redis.RedisChannel y) -> bool +static StackExchange.Redis.RedisChannel.Pattern(byte[]! value) -> StackExchange.Redis.RedisChannel +static StackExchange.Redis.RedisChannel.Pattern(string! value) -> StackExchange.Redis.RedisChannel +static StackExchange.Redis.RedisChannel.UseImplicitAutoPattern.get -> bool +static StackExchange.Redis.RedisChannel.UseImplicitAutoPattern.set -> void static StackExchange.Redis.RedisFeatures.operator !=(StackExchange.Redis.RedisFeatures left, StackExchange.Redis.RedisFeatures right) -> bool static StackExchange.Redis.RedisFeatures.operator ==(StackExchange.Redis.RedisFeatures left, StackExchange.Redis.RedisFeatures right) -> bool static StackExchange.Redis.RedisKey.implicit operator byte[]?(StackExchange.Redis.RedisKey key) -> byte[]? diff --git a/src/StackExchange.Redis/RedisChannel.cs b/src/StackExchange.Redis/RedisChannel.cs index ffd56aed4..16d4e7107 100644 --- a/src/StackExchange.Redis/RedisChannel.cs +++ b/src/StackExchange.Redis/RedisChannel.cs @@ -9,33 +9,67 @@ namespace StackExchange.Redis public readonly struct RedisChannel : IEquatable<RedisChannel> { internal readonly byte[]? Value; - internal readonly bool IsPatternBased; + internal readonly bool _isPatternBased; /// <summary> /// Indicates whether the channel-name is either null or a zero-length value. /// </summary> public bool IsNullOrEmpty => Value == null || Value.Length == 0; + /// <summary> + /// Indicates whether this channel represents a wildcard pattern (see <c>PSUBSCRIBE</c>) + /// </summary> + public bool IsPatternBased => _isPatternBased; + internal bool IsNull => Value == null; + + /// <summary> + /// Indicates whether channels should use <see cref="PatternMode.Auto"/> when no <see cref="PatternMode"/> + /// is specified; this is enabled by default, but can be disabled to avoid unexpected wildcard scenarios. + /// </summary> + public static bool UseImplicitAutoPattern + { + get => s_DefaultPatternMode == PatternMode.Auto; + set => s_DefaultPatternMode = value ? PatternMode.Auto : PatternMode.Literal; + } + private static PatternMode s_DefaultPatternMode = PatternMode.Auto; + + /// <summary> + /// Creates a new <see cref="RedisChannel"/> that does not act as a wildcard subscription + /// </summary> + public static RedisChannel Literal(string value) => new RedisChannel(value, PatternMode.Literal); + /// <summary> + /// Creates a new <see cref="RedisChannel"/> that does not act as a wildcard subscription + /// </summary> + public static RedisChannel Literal(byte[] value) => new RedisChannel(value, PatternMode.Literal); + /// <summary> + /// Creates a new <see cref="RedisChannel"/> that acts as a wildcard subscription + /// </summary> + public static RedisChannel Pattern(string value) => new RedisChannel(value, PatternMode.Pattern); + /// <summary> + /// Creates a new <see cref="RedisChannel"/> that acts as a wildcard subscription + /// </summary> + public static RedisChannel Pattern(byte[] value) => new RedisChannel(value, PatternMode.Pattern); + /// <summary> /// Create a new redis channel from a buffer, explicitly controlling the pattern mode. /// </summary> /// <param name="value">The name of the channel to create.</param> /// <param name="mode">The mode for name matching.</param> - public RedisChannel(byte[]? value, PatternMode mode) : this(value, DeterminePatternBased(value, mode)) {} + public RedisChannel(byte[]? value, PatternMode mode) : this(value, DeterminePatternBased(value, mode)) { } /// <summary> /// Create a new redis channel from a string, explicitly controlling the pattern mode. /// </summary> /// <param name="value">The string name of the channel to create.</param> /// <param name="mode">The mode for name matching.</param> - public RedisChannel(string value, PatternMode mode) : this(value == null ? null : Encoding.UTF8.GetBytes(value), mode) {} + public RedisChannel(string value, PatternMode mode) : this(value == null ? null : Encoding.UTF8.GetBytes(value), mode) { } private RedisChannel(byte[]? value, bool isPatternBased) { Value = value; - IsPatternBased = isPatternBased; + _isPatternBased = isPatternBased; } private static bool DeterminePatternBased(byte[]? value, PatternMode mode) => mode switch @@ -87,7 +121,7 @@ private RedisChannel(byte[]? value, bool isPatternBased) /// <param name="x">The first <see cref="RedisChannel"/> to compare.</param> /// <param name="y">The second <see cref="RedisChannel"/> to compare.</param> public static bool operator ==(RedisChannel x, RedisChannel y) => - x.IsPatternBased == y.IsPatternBased && RedisValue.Equals(x.Value, y.Value); + x._isPatternBased == y._isPatternBased && RedisValue.Equals(x.Value, y.Value); /// <summary> /// Indicate whether two channel names are equal. @@ -135,10 +169,10 @@ private RedisChannel(byte[]? value, bool isPatternBased) /// Indicate whether two channel names are equal. /// </summary> /// <param name="other">The <see cref="RedisChannel"/> to compare to.</param> - public bool Equals(RedisChannel other) => IsPatternBased == other.IsPatternBased && RedisValue.Equals(Value, other.Value); + public bool Equals(RedisChannel other) => _isPatternBased == other._isPatternBased && RedisValue.Equals(Value, other.Value); /// <inheritdoc/> - public override int GetHashCode() => RedisValue.GetHashCode(Value) + (IsPatternBased ? 1 : 0); + public override int GetHashCode() => RedisValue.GetHashCode(Value) + (_isPatternBased ? 1 : 0); /// <summary> /// Obtains a string representation of the channel name. @@ -159,7 +193,16 @@ internal void AssertNotNull() if (IsNull) throw new ArgumentException("A null key is not valid in this context"); } - internal RedisChannel Clone() => (byte[]?)Value?.Clone() ?? default; + internal RedisChannel Clone() + { + if (Value is null || Value.Length == 0) + { + // no need to duplicate anything + return this; + } + var copy = (byte[])Value.Clone(); // defensive array copy + return new RedisChannel(copy, _isPatternBased); + } /// <summary> /// The matching pattern for this channel. @@ -184,33 +227,35 @@ public enum PatternMode /// Create a channel name from a <see cref="string"/>. /// </summary> /// <param name="key">The string to get a channel from.</param> + [Obsolete("It is preferable to explicitly specify a " + nameof(PatternMode) + ", or use the " + nameof(Literal) + "/" + nameof(Pattern) + " methods", error: false)] public static implicit operator RedisChannel(string key) { if (key == null) return default; - return new RedisChannel(Encoding.UTF8.GetBytes(key), PatternMode.Auto); + return new RedisChannel(Encoding.UTF8.GetBytes(key), s_DefaultPatternMode); } /// <summary> /// Create a channel name from a <see cref="T:byte[]"/>. /// </summary> /// <param name="key">The byte array to get a channel from.</param> + [Obsolete("It is preferable to explicitly specify a " + nameof(PatternMode) + ", or use the " + nameof(Literal) + "/" + nameof(Pattern) + " methods", error: false)] public static implicit operator RedisChannel(byte[]? key) { if (key == null) return default; - return new RedisChannel(key, PatternMode.Auto); + return new RedisChannel(key, s_DefaultPatternMode); } /// <summary> /// Obtain the channel name as a <see cref="T:byte[]"/>. /// </summary> /// <param name="key">The channel to get a byte[] from.</param> - public static implicit operator byte[]? (RedisChannel key) => key.Value; + public static implicit operator byte[]?(RedisChannel key) => key.Value; /// <summary> /// Obtain the channel name as a <see cref="string"/>. /// </summary> /// <param name="key">The channel to get a string from.</param> - public static implicit operator string? (RedisChannel key) + public static implicit operator string?(RedisChannel key) { var arr = key.Value; if (arr == null) @@ -226,5 +271,15 @@ public static implicit operator RedisChannel(byte[]? key) return BitConverter.ToString(arr); } } + +#if DEBUG + // these exist *purely* to ensure that we never add them later *without* + // giving due consideration to the default pattern mode (UseImplicitAutoPattern) + // (since we don't ship them, we don't need them in release) + [Obsolete("Watch for " + nameof(UseImplicitAutoPattern), error: true)] + private RedisChannel(string value) => throw new NotSupportedException(); + [Obsolete("Watch for " + nameof(UseImplicitAutoPattern), error: true)] + private RedisChannel(byte[]? value) => throw new NotSupportedException(); +#endif } } diff --git a/src/StackExchange.Redis/RedisSubscriber.cs b/src/StackExchange.Redis/RedisSubscriber.cs index d26368c20..39b99bfe2 100644 --- a/src/StackExchange.Redis/RedisSubscriber.cs +++ b/src/StackExchange.Redis/RedisSubscriber.cs @@ -159,7 +159,7 @@ public Subscription(CommandFlags flags) /// </summary> internal Message GetMessage(RedisChannel channel, SubscriptionAction action, CommandFlags flags, bool internalCall) { - var isPattern = channel.IsPatternBased; + var isPattern = channel._isPatternBased; var command = action switch { SubscriptionAction.Subscribe when isPattern => RedisCommand.PSUBSCRIBE, diff --git a/src/StackExchange.Redis/ServerEndPoint.cs b/src/StackExchange.Redis/ServerEndPoint.cs index 36163578d..d3082e35c 100644 --- a/src/StackExchange.Redis/ServerEndPoint.cs +++ b/src/StackExchange.Redis/ServerEndPoint.cs @@ -979,7 +979,7 @@ private async Task HandshakeAsync(PhysicalConnection connection, LogProxy? log) var configChannel = Multiplexer.ConfigurationChangedChannel; if (configChannel != null) { - msg = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.SUBSCRIBE, (RedisChannel)configChannel); + msg = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.SUBSCRIBE, RedisChannel.Literal(configChannel)); // Note: this is NOT internal, we want it to queue in a backlog for sending when ready if necessary await WriteDirectOrQueueFireAndForgetAsync(connection, msg, ResultProcessor.TrackSubscriptions).ForAwait(); }
diff --git a/tests/ConsoleTest/Program.cs b/tests/ConsoleTest/Program.cs index 1d33a968e..0d6fa7e13 100644 --- a/tests/ConsoleTest/Program.cs +++ b/tests/ConsoleTest/Program.cs @@ -110,7 +110,7 @@ static void ParallelRun(int taskId, ConnectionMultiplexer connection) static void MassPublish(ConnectionMultiplexer connection) { var subscriber = connection.GetSubscriber(); - Parallel.For(0, 1000, _ => subscriber.Publish("cache-events:cache-testing", "hey")); + Parallel.For(0, 1000, _ => subscriber.Publish(new RedisChannel("cache-events:cache-testing", RedisChannel.PatternMode.Literal), "hey")); } static string GetLibVersion() diff --git a/tests/StackExchange.Redis.Tests/ChannelTests.cs b/tests/StackExchange.Redis.Tests/ChannelTests.cs new file mode 100644 index 000000000..3f11d2ef1 --- /dev/null +++ b/tests/StackExchange.Redis.Tests/ChannelTests.cs @@ -0,0 +1,153 @@ +using System.Text; +using Xunit; + +namespace StackExchange.Redis.Tests +{ + public class ChannelTests + { + [Fact] + public void UseImplicitAutoPattern_OnByDefault() + { + Assert.True(RedisChannel.UseImplicitAutoPattern); + } + + [Theory] + [InlineData("abc", true, false)] + [InlineData("abc*def", true, true)] + [InlineData("abc", false, false)] + [InlineData("abc*def", false, false)] + public void ValidateAutoPatternModeString(string name, bool useImplicitAutoPattern, bool isPatternBased) + { + bool oldValue = RedisChannel.UseImplicitAutoPattern; + try + { + RedisChannel.UseImplicitAutoPattern = useImplicitAutoPattern; +#pragma warning disable CS0618 // we need to test the operator + RedisChannel channel = name; +#pragma warning restore CS0618 + Assert.Equal(isPatternBased, channel.IsPatternBased); + } + finally + { + RedisChannel.UseImplicitAutoPattern = oldValue; + } + } + + [Theory] + [InlineData("abc", RedisChannel.PatternMode.Auto, true, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Auto, true, true)] + [InlineData("abc", RedisChannel.PatternMode.Literal, true, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Literal, true, false)] + [InlineData("abc", RedisChannel.PatternMode.Pattern, true, true)] + [InlineData("abc*def", RedisChannel.PatternMode.Pattern, true, true)] + [InlineData("abc", RedisChannel.PatternMode.Auto, false, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Auto, false, true)] + [InlineData("abc", RedisChannel.PatternMode.Literal, false, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Literal, false, false)] + [InlineData("abc", RedisChannel.PatternMode.Pattern, false, true)] + [InlineData("abc*def", RedisChannel.PatternMode.Pattern, false, true)] + public void ValidateModeSpecifiedIgnoresGlobalSetting(string name, RedisChannel.PatternMode mode, bool useImplicitAutoPattern, bool isPatternBased) + { + bool oldValue = RedisChannel.UseImplicitAutoPattern; + try + { + RedisChannel.UseImplicitAutoPattern = useImplicitAutoPattern; + RedisChannel channel = new(name, mode); + Assert.Equal(isPatternBased, channel.IsPatternBased); + } + finally + { + RedisChannel.UseImplicitAutoPattern = oldValue; + } + } + + [Theory] + [InlineData("abc", true, false)] + [InlineData("abc*def", true, true)] + [InlineData("abc", false, false)] + [InlineData("abc*def", false, false)] + public void ValidateAutoPatternModeBytes(string name, bool useImplicitAutoPattern, bool isPatternBased) + { + var bytes = Encoding.UTF8.GetBytes(name); + bool oldValue = RedisChannel.UseImplicitAutoPattern; + try + { + RedisChannel.UseImplicitAutoPattern = useImplicitAutoPattern; +#pragma warning disable CS0618 // we need to test the operator + RedisChannel channel = bytes; +#pragma warning restore CS0618 + Assert.Equal(isPatternBased, channel.IsPatternBased); + } + finally + { + RedisChannel.UseImplicitAutoPattern = oldValue; + } + } + + [Theory] + [InlineData("abc", RedisChannel.PatternMode.Auto, true, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Auto, true, true)] + [InlineData("abc", RedisChannel.PatternMode.Literal, true, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Literal, true, false)] + [InlineData("abc", RedisChannel.PatternMode.Pattern, true, true)] + [InlineData("abc*def", RedisChannel.PatternMode.Pattern, true, true)] + [InlineData("abc", RedisChannel.PatternMode.Auto, false, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Auto, false, true)] + [InlineData("abc", RedisChannel.PatternMode.Literal, false, false)] + [InlineData("abc*def", RedisChannel.PatternMode.Literal, false, false)] + [InlineData("abc", RedisChannel.PatternMode.Pattern, false, true)] + [InlineData("abc*def", RedisChannel.PatternMode.Pattern, false, true)] + public void ValidateModeSpecifiedIgnoresGlobalSettingBytes(string name, RedisChannel.PatternMode mode, bool useImplicitAutoPattern, bool isPatternBased) + { + var bytes = Encoding.UTF8.GetBytes(name); + bool oldValue = RedisChannel.UseImplicitAutoPattern; + try + { + RedisChannel.UseImplicitAutoPattern = useImplicitAutoPattern; + RedisChannel channel = new(bytes, mode); + Assert.Equal(isPatternBased, channel.IsPatternBased); + } + finally + { + RedisChannel.UseImplicitAutoPattern = oldValue; + } + } + + [Theory] + [InlineData("abc*def", false)] + [InlineData("abcdef", false)] + [InlineData("abc*def", true)] + [InlineData("abcdef", true)] + public void ValidateLiteralPatternMode(string name, bool useImplicitAutoPattern) + { + bool oldValue = RedisChannel.UseImplicitAutoPattern; + try + { + RedisChannel.UseImplicitAutoPattern = useImplicitAutoPattern; + RedisChannel channel; + + // literal, string + channel = RedisChannel.Literal(name); + Assert.False(channel.IsPatternBased); + + // pattern, string + channel = RedisChannel.Pattern(name); + Assert.True(channel.IsPatternBased); + + var bytes = Encoding.UTF8.GetBytes(name); + + // literal, byte[] + channel = RedisChannel.Literal(bytes); + Assert.False(channel.IsPatternBased); + + // pattern, byte[] + channel = RedisChannel.Pattern(bytes); + Assert.True(channel.IsPatternBased); + } + finally + { + RedisChannel.UseImplicitAutoPattern = oldValue; + } + } + } +} diff --git a/tests/StackExchange.Redis.Tests/ConfigTests.cs b/tests/StackExchange.Redis.Tests/ConfigTests.cs index c07b32c8a..b11c968cf 100644 --- a/tests/StackExchange.Redis.Tests/ConfigTests.cs +++ b/tests/StackExchange.Redis.Tests/ConfigTests.cs @@ -276,7 +276,7 @@ public void ConnectWithSubscribeDisabled() Assert.True(servers[0].IsConnected); Assert.False(servers[0].IsSubscriberConnected); - var ex = Assert.Throws<RedisCommandException>(() => conn.GetSubscriber().Subscribe(Me(), (_, _) => GC.KeepAlive(this))); + var ex = Assert.Throws<RedisCommandException>(() => conn.GetSubscriber().Subscribe(RedisChannel.Literal(Me()), (_, _) => GC.KeepAlive(this))); Assert.Equal("This operation has been disabled in the command-map and cannot be used: SUBSCRIBE", ex.Message); } diff --git a/tests/StackExchange.Redis.Tests/Issues/Issue1101Tests.cs b/tests/StackExchange.Redis.Tests/Issues/Issue1101Tests.cs index 440d18a8e..3f248b480 100644 --- a/tests/StackExchange.Redis.Tests/Issues/Issue1101Tests.cs +++ b/tests/StackExchange.Redis.Tests/Issues/Issue1101Tests.cs @@ -28,7 +28,7 @@ public async Task ExecuteWithUnsubscribeViaChannel() { using var conn = Create(log: Writer); - RedisChannel name = Me(); + RedisChannel name = RedisChannel.Literal(Me()); var pubsub = conn.GetSubscriber(); AssertCounts(pubsub, name, false, 0, 0); @@ -93,7 +93,7 @@ public async Task ExecuteWithUnsubscribeViaSubscriber() { using var conn = Create(shared: false, log: Writer); - RedisChannel name = Me(); + RedisChannel name = RedisChannel.Literal(Me()); var pubsub = conn.GetSubscriber(); AssertCounts(pubsub, name, false, 0, 0); @@ -144,7 +144,7 @@ public async Task ExecuteWithUnsubscribeViaClearAll() { using var conn = Create(log: Writer); - RedisChannel name = Me(); + RedisChannel name = RedisChannel.Literal(Me()); var pubsub = conn.GetSubscriber(); AssertCounts(pubsub, name, false, 0, 0); diff --git a/tests/StackExchange.Redis.Tests/KeyPrefixedDatabaseTests.cs b/tests/StackExchange.Redis.Tests/KeyPrefixedDatabaseTests.cs index 96f7d4c85..b4eff605a 100644 --- a/tests/StackExchange.Redis.Tests/KeyPrefixedDatabaseTests.cs +++ b/tests/StackExchange.Redis.Tests/KeyPrefixedDatabaseTests.cs @@ -568,8 +568,10 @@ public void LockTake() [Fact] public void Publish() { +#pragma warning disable CS0618 prefixed.Publish("channel", "message", CommandFlags.None); mock.Verify(_ => _.Publish("prefix:channel", "message", CommandFlags.None)); +#pragma warning restore CS0618 } [Fact] diff --git a/tests/StackExchange.Redis.Tests/KeyPrefixedTests.cs b/tests/StackExchange.Redis.Tests/KeyPrefixedTests.cs index d5fea204c..2d6b53390 100644 --- a/tests/StackExchange.Redis.Tests/KeyPrefixedTests.cs +++ b/tests/StackExchange.Redis.Tests/KeyPrefixedTests.cs @@ -528,8 +528,8 @@ public void LockTakeAsync() [Fact] public void PublishAsync() { - prefixed.PublishAsync("channel", "message", CommandFlags.None); - mock.Verify(_ => _.PublishAsync("prefix:channel", "message", CommandFlags.None)); + prefixed.PublishAsync(RedisChannel.Literal("channel"), "message", CommandFlags.None); + mock.Verify(_ => _.PublishAsync(RedisChannel.Literal("prefix:channel"), "message", CommandFlags.None)); } [Fact] diff --git a/tests/StackExchange.Redis.Tests/PreserveOrderTests.cs b/tests/StackExchange.Redis.Tests/PreserveOrderTests.cs index b0f7df995..f11cda5c5 100644 --- a/tests/StackExchange.Redis.Tests/PreserveOrderTests.cs +++ b/tests/StackExchange.Redis.Tests/PreserveOrderTests.cs @@ -22,7 +22,7 @@ public void Execute() var received = new List<int>(); Log("Subscribing..."); const int COUNT = 500; - sub.Subscribe(channel, (_, message) => + sub.Subscribe(RedisChannel.Literal(channel), (_, message) => { lock (received) { @@ -42,7 +42,7 @@ public void Execute() // it all goes to the server and back for (int i = 0; i < COUNT; i++) { - sub.Publish(channel, i, CommandFlags.FireAndForget); + sub.Publish(RedisChannel.Literal(channel), i, CommandFlags.FireAndForget); } Log("Allowing time for delivery etc..."); diff --git a/tests/StackExchange.Redis.Tests/PubSubCommandTests.cs b/tests/StackExchange.Redis.Tests/PubSubCommandTests.cs index 809a9968e..dd77dc106 100644 --- a/tests/StackExchange.Redis.Tests/PubSubCommandTests.cs +++ b/tests/StackExchange.Redis.Tests/PubSubCommandTests.cs @@ -17,10 +17,12 @@ public void SubscriberCount() { using var conn = Create(); +#pragma warning disable CS0618 RedisChannel channel = Me() + Guid.NewGuid(); var server = conn.GetServer(conn.GetEndPoints()[0]); var channels = server.SubscriptionChannels(Me() + "*"); +#pragma warning restore CS0618 Assert.DoesNotContain(channel, channels); _ = server.SubscriptionPatternCount(); @@ -30,7 +32,9 @@ public void SubscriberCount() count = server.SubscriptionSubscriberCount(channel); Assert.Equal(1, count); +#pragma warning disable CS0618 channels = server.SubscriptionChannels(Me() + "*"); +#pragma warning restore CS0618 Assert.Contains(channel, channels); } @@ -39,10 +43,14 @@ public async Task SubscriberCountAsync() { using var conn = Create(); +#pragma warning disable CS0618 RedisChannel channel = Me() + Guid.NewGuid(); +#pragma warning restore CS0618 var server = conn.GetServer(conn.GetEndPoints()[0]); +#pragma warning disable CS0618 var channels = await server.SubscriptionChannelsAsync(Me() + "*").WithTimeout(2000); +#pragma warning restore CS0618 Assert.DoesNotContain(channel, channels); _ = await server.SubscriptionPatternCountAsync().WithTimeout(2000); @@ -52,7 +60,9 @@ public async Task SubscriberCountAsync() count = await server.SubscriptionSubscriberCountAsync(channel).WithTimeout(2000); Assert.Equal(1, count); +#pragma warning disable CS0618 channels = await server.SubscriptionChannelsAsync(Me() + "*").WithTimeout(2000); +#pragma warning restore CS0618 Assert.Contains(channel, channels); } } diff --git a/tests/StackExchange.Redis.Tests/PubSubMultiserverTests.cs b/tests/StackExchange.Redis.Tests/PubSubMultiserverTests.cs index d3e634a47..dcf706e76 100644 --- a/tests/StackExchange.Redis.Tests/PubSubMultiserverTests.cs +++ b/tests/StackExchange.Redis.Tests/PubSubMultiserverTests.cs @@ -18,8 +18,8 @@ public void ChannelSharding() using var conn = (Create(channelPrefix: Me()) as ConnectionMultiplexer)!; var defaultSlot = conn.ServerSelectionStrategy.HashSlot(default(RedisChannel)); - var slot1 = conn.ServerSelectionStrategy.HashSlot((RedisChannel)"hey"); - var slot2 = conn.ServerSelectionStrategy.HashSlot((RedisChannel)"hey2"); + var slot1 = conn.ServerSelectionStrategy.HashSlot(RedisChannel.Literal("hey")); + var slot2 = conn.ServerSelectionStrategy.HashSlot(RedisChannel.Literal("hey2")); Assert.NotEqual(defaultSlot, slot1); Assert.NotEqual(ServerSelectionStrategy.NoSlot, slot1); @@ -34,7 +34,7 @@ public async Task ClusterNodeSubscriptionFailover() using var conn = (Create(allowAdmin: true) as ConnectionMultiplexer)!; var sub = conn.GetSubscriber(); - var channel = (RedisChannel)Me(); + var channel = RedisChannel.Literal(Me()); var count = 0; Log("Subscribing..."); @@ -108,7 +108,7 @@ public async Task PrimaryReplicaSubscriptionFailover(CommandFlags flags, bool ex using var conn = (Create(configuration: config, shared: false, allowAdmin: true) as ConnectionMultiplexer)!; var sub = conn.GetSubscriber(); - var channel = (RedisChannel)(Me() + flags.ToString()); // Individual channel per case to not overlap publishers + var channel = RedisChannel.Literal(Me() + flags.ToString()); // Individual channel per case to not overlap publishers var count = 0; Log("Subscribing..."); diff --git a/tests/StackExchange.Redis.Tests/PubSubTests.cs b/tests/StackExchange.Redis.Tests/PubSubTests.cs index 8fd23ffdd..833d888e9 100644 --- a/tests/StackExchange.Redis.Tests/PubSubTests.cs +++ b/tests/StackExchange.Redis.Tests/PubSubTests.cs @@ -27,9 +27,11 @@ public async Task ExplicitPublishMode() pub.Subscribe(new RedisChannel("*bcd", RedisChannel.PatternMode.Literal), (x, y) => Interlocked.Increment(ref a)); pub.Subscribe(new RedisChannel("a*cd", RedisChannel.PatternMode.Pattern), (x, y) => Interlocked.Increment(ref b)); pub.Subscribe(new RedisChannel("ab*d", RedisChannel.PatternMode.Auto), (x, y) => Interlocked.Increment(ref c)); +#pragma warning disable CS0618 pub.Subscribe("abc*", (x, y) => Interlocked.Increment(ref d)); pub.Publish("abcd", "efg"); +#pragma warning restore CS0618 await UntilConditionAsync(TimeSpan.FromSeconds(10), () => Thread.VolatileRead(ref b) == 1 && Thread.VolatileRead(ref c) == 1 @@ -39,7 +41,9 @@ await UntilConditionAsync(TimeSpan.FromSeconds(10), Assert.Equal(1, Thread.VolatileRead(ref c)); Assert.Equal(1, Thread.VolatileRead(ref d)); +#pragma warning disable CS0618 pub.Publish("*bcd", "efg"); +#pragma warning restore CS0618 await UntilConditionAsync(TimeSpan.FromSeconds(10), () => Thread.VolatileRead(ref a) == 1); Assert.Equal(1, Thread.VolatileRead(ref a)); } @@ -77,15 +81,19 @@ public async Task TestBasicPubSub(string channelPrefix, bool wildCard, string br } } , handler2 = (_, __) => Interlocked.Increment(ref secondHandler); +#pragma warning disable CS0618 sub.Subscribe(subChannel, handler1); sub.Subscribe(subChannel, handler2); +#pragma warning restore CS0618 lock (received) { Assert.Empty(received); } Assert.Equal(0, Thread.VolatileRead(ref secondHandler)); +#pragma warning disable CS0618 var count = sub.Publish(pubChannel, "def"); +#pragma warning restore CS0618 await PingAsync(pub, sub, 3).ForAwait(); @@ -99,8 +107,10 @@ public async Task TestBasicPubSub(string channelPrefix, bool wildCard, string br Assert.Equal(1, Thread.VolatileRead(ref secondHandler)); // unsubscribe from first; should still see second +#pragma warning disable CS0618 sub.Unsubscribe(subChannel, handler1); count = sub.Publish(pubChannel, "ghi"); +#pragma warning restore CS0618 await PingAsync(pub, sub).ForAwait(); lock (received) { @@ -115,8 +125,10 @@ public async Task TestBasicPubSub(string channelPrefix, bool wildCard, string br Assert.Equal(1, count); // unsubscribe from second; should see nothing this time +#pragma warning disable CS0618 sub.Unsubscribe(subChannel, handler2); count = sub.Publish(pubChannel, "ghi"); +#pragma warning restore CS0618 await PingAsync(pub, sub).ForAwait(); lock (received) { @@ -137,7 +149,7 @@ public async Task TestBasicPubSubFireAndForget() var pub = GetAnyPrimary(conn); var sub = conn.GetSubscriber(); - RedisChannel key = Me() + Guid.NewGuid(); + RedisChannel key = RedisChannel.Literal(Me() + Guid.NewGuid()); HashSet<string?> received = new(); int secondHandler = 0; await PingAsync(pub, sub).ForAwait(); @@ -210,7 +222,9 @@ public async Task TestPatternPubSub() HashSet<string?> received = new(); int secondHandler = 0; +#pragma warning disable CS0618 sub.Subscribe("a*c", (channel, payload) => +#pragma warning restore CS0618 { lock (received) { @@ -221,7 +235,9 @@ public async Task TestPatternPubSub() } }); +#pragma warning disable CS0618 sub.Subscribe("a*c", (_, __) => Interlocked.Increment(ref secondHandler)); +#pragma warning restore CS0618 lock (received) { Assert.Empty(received); @@ -229,7 +245,7 @@ public async Task TestPatternPubSub() Assert.Equal(0, Thread.VolatileRead(ref secondHandler)); await PingAsync(pub, sub).ForAwait(); - var count = sub.Publish("abc", "def"); + var count = sub.Publish(RedisChannel.Literal("abc"), "def"); await PingAsync(pub, sub).ForAwait(); await UntilConditionAsync(TimeSpan.FromSeconds(5), () => received.Count == 1); @@ -242,8 +258,10 @@ public async Task TestPatternPubSub() await UntilConditionAsync(TimeSpan.FromSeconds(2), () => Thread.VolatileRead(ref secondHandler) == 1); Assert.Equal(1, Thread.VolatileRead(ref secondHandler)); +#pragma warning disable CS0618 sub.Unsubscribe("a*c"); count = sub.Publish("abc", "ghi"); +#pragma warning restore CS0618 await PingAsync(pub, sub).ForAwait(); @@ -259,7 +277,9 @@ public void TestPublishWithNoSubscribers() using var conn = Create(); var sub = conn.GetSubscriber(); +#pragma warning disable CS0618 Assert.Equal(0, sub.Publish(Me() + "channel", "message")); +#pragma warning restore CS0618 } [FactLongRunning] @@ -289,14 +309,18 @@ private void TestMassivePublish(ISubscriber sub, string channel, string caption) var withFAF = Stopwatch.StartNew(); for (int i = 0; i < loop; i++) { +#pragma warning disable CS0618 sub.Publish(channel, "bar", CommandFlags.FireAndForget); +#pragma warning restore CS0618 } withFAF.Stop(); var withAsync = Stopwatch.StartNew(); for (int i = 0; i < loop; i++) { +#pragma warning disable CS0618 tasks[i] = sub.PublishAsync(channel, "bar"); +#pragma warning restore CS0618 } sub.WaitAll(tasks); withAsync.Stop(); @@ -314,7 +338,7 @@ public async Task SubscribeAsyncEnumerable() using var conn = Create(syncTimeout: 20000, shared: false, log: Writer); var sub = conn.GetSubscriber(); - RedisChannel channel = Me(); + RedisChannel channel = RedisChannel.Literal(Me()); const int TO_SEND = 5; var gotall = new TaskCompletionSource<int>(); @@ -348,7 +372,7 @@ public async Task PubSubGetAllAnyOrder() using var sonn = Create(syncTimeout: 20000, shared: false, log: Writer); var sub = sonn.GetSubscriber(); - RedisChannel channel = Me(); + RedisChannel channel = RedisChannel.Literal(Me()); const int count = 1000; var syncLock = new object(); @@ -396,7 +420,7 @@ public async Task PubSubGetAllCorrectOrder() using (var conn = Create(configuration: TestConfig.Current.RemoteServerAndPort, syncTimeout: 20000, log: Writer)) { var sub = conn.GetSubscriber(); - RedisChannel channel = Me(); + RedisChannel channel = RedisChannel.Literal(Me()); const int count = 250; var syncLock = new object(); @@ -469,7 +493,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Sync() using (var conn = Create(configuration: TestConfig.Current.RemoteServerAndPort, syncTimeout: 20000, log: Writer)) { var sub = conn.GetSubscriber(); - RedisChannel channel = Me(); + RedisChannel channel = RedisChannel.Literal(Me()); const int count = 1000; var syncLock = new object(); @@ -538,7 +562,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Async() using (var conn = Create(configuration: TestConfig.Current.RemoteServerAndPort, syncTimeout: 20000, log: Writer)) { var sub = conn.GetSubscriber(); - RedisChannel channel = Me(); + RedisChannel channel = RedisChannel.Literal(Me()); const int count = 1000; var syncLock = new object(); @@ -616,8 +640,10 @@ public async Task TestPublishWithSubscribers() var channel = Me(); var listenA = connA.GetSubscriber(); var listenB = connB.GetSubscriber(); +#pragma warning disable CS0618 var t1 = listenA.SubscribeAsync(channel, delegate { }); var t2 = listenB.SubscribeAsync(channel, delegate { }); +#pragma warning restore CS0618 await Task.WhenAll(t1, t2).ForAwait(); @@ -625,7 +651,9 @@ public async Task TestPublishWithSubscribers() await listenA.PingAsync(); await listenB.PingAsync(); +#pragma warning disable CS0618 var pub = connPub.GetSubscriber().PublishAsync(channel, "message"); +#pragma warning restore CS0618 Assert.Equal(2, await pub); // delivery count } @@ -636,7 +664,7 @@ public async Task TestMultipleSubscribersGetMessage() using var connB = Create(shared: false, log: Writer); using var connPub = Create(); - var channel = Me(); + var channel = RedisChannel.Literal(Me()); var listenA = connA.GetSubscriber(); var listenB = connB.GetSubscriber(); connPub.GetDatabase().Ping(); @@ -668,16 +696,20 @@ public async Task Issue38() int count = 0; var prefix = Me(); void handler(RedisChannel _, RedisValue __) => Interlocked.Increment(ref count); +#pragma warning disable CS0618 var a0 = sub.SubscribeAsync(prefix + "foo", handler); var a1 = sub.SubscribeAsync(prefix + "bar", handler); var b0 = sub.SubscribeAsync(prefix + "f*o", handler); var b1 = sub.SubscribeAsync(prefix + "b*r", handler); +#pragma warning restore CS0618 await Task.WhenAll(a0, a1, b0, b1).ForAwait(); +#pragma warning disable CS0618 var c = sub.PublishAsync(prefix + "foo", "foo"); var d = sub.PublishAsync(prefix + "f@o", "f@o"); var e = sub.PublishAsync(prefix + "bar", "bar"); var f = sub.PublishAsync(prefix + "b@r", "b@r"); +#pragma warning restore CS0618 await Task.WhenAll(c, d, e, f).ForAwait(); long total = c.Result + d.Result + e.Result + f.Result; @@ -702,18 +734,22 @@ public async Task TestPartialSubscriberGetMessage() var listenB = connB.GetSubscriber(); var pub = connPub.GetSubscriber(); var prefix = Me(); +#pragma warning disable CS0618 var tA = listenA.SubscribeAsync(prefix + "channel", (s, msg) => { if (s == prefix + "channel" && msg == "message") Interlocked.Increment(ref gotA); }); var tB = listenB.SubscribeAsync(prefix + "chann*", (s, msg) => { if (s == prefix + "channel" && msg == "message") Interlocked.Increment(ref gotB); }); await Task.WhenAll(tA, tB).ForAwait(); Assert.Equal(2, pub.Publish(prefix + "channel", "message")); +#pragma warning restore CS0618 await AllowReasonableTimeToPublishAndProcess().ForAwait(); Assert.Equal(1, Interlocked.CompareExchange(ref gotA, 0, 0)); Assert.Equal(1, Interlocked.CompareExchange(ref gotB, 0, 0)); // and unsubscibe... +#pragma warning disable CS0618 tB = listenB.UnsubscribeAsync(prefix + "chann*", null); await tB; Assert.Equal(1, pub.Publish(prefix + "channel", "message")); +#pragma warning restore CS0618 await AllowReasonableTimeToPublishAndProcess().ForAwait(); Assert.Equal(2, Interlocked.CompareExchange(ref gotA, 0, 0)); Assert.Equal(1, Interlocked.CompareExchange(ref gotB, 0, 0)); @@ -729,6 +765,7 @@ public async Task TestSubscribeUnsubscribeAndSubscribeAgain() var pub = connPub.GetSubscriber(); var sub = connSub.GetSubscriber(); int x = 0, y = 0; +#pragma warning disable CS0618 var t1 = sub.SubscribeAsync(prefix + "abc", delegate { Interlocked.Increment(ref x); }); var t2 = sub.SubscribeAsync(prefix + "ab*", delegate { Interlocked.Increment(ref y); }); await Task.WhenAll(t1, t2).ForAwait(); @@ -746,6 +783,7 @@ public async Task TestSubscribeUnsubscribeAndSubscribeAgain() t2 = sub.SubscribeAsync(prefix + "ab*", delegate { Interlocked.Increment(ref y); }); await Task.WhenAll(t1, t2).ForAwait(); pub.Publish(prefix + "abc", ""); +#pragma warning restore CS0618 await AllowReasonableTimeToPublishAndProcess().ForAwait(); Assert.Equal(2, Volatile.Read(ref x)); Assert.Equal(2, Volatile.Read(ref y)); @@ -776,7 +814,7 @@ public async Task AzureRedisEventsAutomaticSubscribe() }; var pubSub = connection.GetSubscriber(); - await pubSub.PublishAsync("AzureRedisEvents", "HI"); + await pubSub.PublishAsync(RedisChannel.Literal("AzureRedisEvents"), "HI"); await Task.Delay(100); Assert.True(didUpdate); diff --git a/tests/StackExchange.Redis.Tests/SentinelFailoverTests.cs b/tests/StackExchange.Redis.Tests/SentinelFailoverTests.cs index 0afdf03ec..1e4d8c28e 100644 --- a/tests/StackExchange.Redis.Tests/SentinelFailoverTests.cs +++ b/tests/StackExchange.Redis.Tests/SentinelFailoverTests.cs @@ -21,7 +21,9 @@ public async Task ManagedPrimaryConnectionEndToEndWithFailoverTest() conn.ConfigurationChanged += (s, e) => Log($"Configuration changed: {e.EndPoint}"); var sub = conn.GetSubscriber(); +#pragma warning disable CS0618 sub.Subscribe("*", (channel, message) => Log($"Sub: {channel}, message:{message}")); +#pragma warning restore CS0618 var db = conn.GetDatabase(); await db.PingAsync(); diff --git a/tests/StackExchange.Redis.Tests/TestBase.cs b/tests/StackExchange.Redis.Tests/TestBase.cs index 6738bf490..4ba21d4f5 100644 --- a/tests/StackExchange.Redis.Tests/TestBase.cs +++ b/tests/StackExchange.Redis.Tests/TestBase.cs @@ -377,7 +377,7 @@ public static ConnectionMultiplexer CreateDefault( syncTimeout = int.MaxValue; } - if (channelPrefix != null) config.ChannelPrefix = channelPrefix; + if (channelPrefix != null) config.ChannelPrefix = RedisChannel.Literal(channelPrefix); if (tieBreaker != null) config.TieBreaker = tieBreaker; if (password != null) config.Password = string.IsNullOrEmpty(password) ? null : password; if (clientName != null) config.ClientName = clientName;
Suggested analyzer re channel subscribe scenario; application takes user-supplied channels, and they were using subscribe; they expected discreet channels, but a user-entered channel used a wildcard, and SE.Redis dutifully does a `PSUBSCRIBE` via the default / implicit behaviour ; bad things and possible infosec I don't think we can change the behaviour at this point without breaking lots of things, however I see a few possible routes forward: ## option 1 a global `public static bool UseImplicitAutoPattern {get;set;} = true;` - if set to true, then the conversion operators and any constructors that do **not** take a `PatternMode` would use `PatternMode.Literal` rather than `PatternMode.Auto`; example: ``` diff - return new RedisChannel(whatever, PatternMode.Auto); + return new RedisChannel(whatever, DefaultPatternMode); + + public static bool UseImplicitAutoPattern { + get => DefaultPatternMode == PatternMode.Auto; + set => DefaultPatternMode = value ? PatternMode.Auto : PatternMode.Literal; + } + // keep this simple, since accessed more frequently + private static PatternMode DefaultPatternMode {get;set;} = PatternMode.Auto; ``` simple and quick, but not very nuanced - global setting, etc; anyone explicitly using `PatternMode.Auto` would not be impacted; we could also add some helper creation methods ## option 2 we write an analyzer that spots and of the same constructors / operators, **excluding** any scenarios where the input is a literal that does *not* contain a glob-like pattern (so: only non-constant expressions, or literals that are glob-like), that adds an info-level analyzer output saying "hey, you might want to specify whether this is meant to be literal or pattern based" examples: ``` c# foo.Subscribe("abc", ...); // no analyzer output; literal and not glob-like RedisChannel x = "abc"); // no analyzer output; literal and not glob-like foo.Subscribe("abc*", ...); // add output RedisChannel x = "abc*"; // add output foo.Subscribe(someStringChannel, ...); // add output RedisChannel x = someStringChannel; // add output foo.Subscribe(some + expression, ...); // add output RedisChannel x = some + expression; // add output foo.Publish(literallyAnythingHere, ...); // no analyzer output: publish is never pattern-based var x = new RedisChannel(literallyAnythingHere, anyPatternModeHere); // they made a choice ``` ## option 3 we do option 1 as a quick fix, and follow up with option 2 in due course ## option 4 in combination with option 1, we mark the implicit conversion operators as ``` c# [Obsolete("You might want to specify a " + nameof(PatternMode), error: false)] ``` and then later un-obsolete them when/if we ship the same via an analyzer (so: "all of the above") Thoughts... --- Also included in this topic: expose the "is pattern based" flag via an instance accessor
null
2023-06-13T13:24:46Z
0.1
['StackExchange.Redis.Tests.ChannelTests.ValidateAutoPatternModeString', 'StackExchange.Redis.Tests.ChannelTests.ValidateLiteralPatternMode', 'StackExchange.Redis.Tests.ChannelTests.ValidateModeSpecifiedIgnoresGlobalSetting', 'StackExchange.Redis.Tests.ChannelTests.UseImplicitAutoPattern_OnByDefault', 'StackExchange.Redis.Tests.ChannelTests.ValidateAutoPatternModeBytes', 'StackExchange.Redis.Tests.ChannelTests.ValidateModeSpecifiedIgnoresGlobalSettingBytes']
[]
StackExchange/StackExchange.Redis
stackexchange__stackexchangeredis-2654
e4cdd905480d21cd3d7ee1a65017d4aac5b6a7f5
diff --git a/docs/ReleaseNotes.md b/docs/ReleaseNotes.md index 4a4b1c3fc..2098349e2 100644 --- a/docs/ReleaseNotes.md +++ b/docs/ReleaseNotes.md @@ -7,7 +7,8 @@ Current package versions: | [![StackExchange.Redis](https://img.shields.io/nuget/v/StackExchange.Redis.svg)](https://www.nuget.org/packages/StackExchange.Redis/) | [![StackExchange.Redis](https://img.shields.io/nuget/vpre/StackExchange.Redis.svg)](https://www.nuget.org/packages/StackExchange.Redis/) | [![StackExchange.Redis MyGet](https://img.shields.io/myget/stackoverflow/vpre/StackExchange.Redis.svg)](https://www.myget.org/feed/stackoverflow/package/nuget/StackExchange.Redis) | ## Unreleased -No pending unreleased changes. + +- Fix [#2653](https://github.com/StackExchange/StackExchange.Redis/issues/2653): Client library metadata should validate contents ([#2654](https://github.com/StackExchange/StackExchange.Redis/pull/2654) by mgravell) ## 2.7.20 diff --git a/src/StackExchange.Redis/ServerEndPoint.cs b/src/StackExchange.Redis/ServerEndPoint.cs index 97230f85f..a5471b5d5 100644 --- a/src/StackExchange.Redis/ServerEndPoint.cs +++ b/src/StackExchange.Redis/ServerEndPoint.cs @@ -26,7 +26,7 @@ internal sealed partial class ServerEndPoint : IDisposable { internal volatile ServerEndPoint? Primary; internal volatile ServerEndPoint[] Replicas = Array.Empty<ServerEndPoint>(); - private static readonly Regex nameSanitizer = new Regex("[^!-~]", RegexOptions.Compiled); + private static readonly Regex nameSanitizer = new Regex("[^!-~]+", RegexOptions.Compiled); private readonly Hashtable knownScripts = new Hashtable(StringComparer.Ordinal); @@ -1024,6 +1024,8 @@ private async Task HandshakeAsync(PhysicalConnection connection, ILogger? log) // it, they should set SetClientLibrary to false, not set the name to empty string) libName = config.Defaults.LibraryName; } + + libName = ClientInfoSanitize(libName); if (!string.IsNullOrWhiteSpace(libName)) { msg = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.CLIENT, @@ -1032,7 +1034,7 @@ private async Task HandshakeAsync(PhysicalConnection connection, ILogger? log) await WriteDirectOrQueueFireAndForgetAsync(connection, msg, ResultProcessor.DemandOK).ForAwait(); } - var version = Utils.GetLibVersion(); + var version = ClientInfoSanitize(Utils.GetLibVersion()); if (!string.IsNullOrWhiteSpace(version)) { msg = Message.Create(-1, CommandFlags.FireAndForget, RedisCommand.CLIENT, @@ -1091,6 +1093,8 @@ private void SetConfig<T>(ref T field, T value, [CallerMemberName] string? calle Multiplexer?.ReconfigureIfNeeded(EndPoint, false, caller!); } } + internal static string ClientInfoSanitize(string? value) + => string.IsNullOrWhiteSpace(value) ? "" : nameSanitizer.Replace(value!.Trim(), "-"); private void ClearMemoized() {
diff --git a/tests/StackExchange.Redis.Tests/Issues/Issue2653.cs b/tests/StackExchange.Redis.Tests/Issues/Issue2653.cs new file mode 100644 index 000000000..973a01da5 --- /dev/null +++ b/tests/StackExchange.Redis.Tests/Issues/Issue2653.cs @@ -0,0 +1,16 @@ +using Xunit; + +namespace StackExchange.Redis.Tests.Issues; + +public class Issue2653 +{ + [Theory] + [InlineData(null, "")] + [InlineData("", "")] + [InlineData("abcdef", "abcdef")] + [InlineData("abc.def", "abc.def")] + [InlineData("abc d \t ef", "abc-d-ef")] + [InlineData(" abc\r\ndef\n", "abc-def")] + public void CheckLibraySanitization(string input, string expected) + => Assert.Equal(expected, ServerEndPoint.ClientInfoSanitize(input)); +}
client library metadata should validate contents The `client setinfo lib-name` and `client setinfo lib-ver` sub-commands are picky: ``` txt 127.0.0.1:6379> client setinfo lib-name "a b" (error) ERR lib-name cannot contain spaces, newlines or special characters. 127.0.0.1:6379> client setinfo lib-name "a-b" OK ``` and ``` txt 127.0.0.1:6379> client setinfo lib-ver "a b" (error) ERR lib-ver cannot contain spaces, newlines or special characters. 127.0.0.1:6379> client setinfo lib-ver "a-b" OK ``` This causes the library metadata to *not be set at all*; suggestion: fix this at the library level. We already perform `client setname` validation, removing invalid characters; however, I propose to replace any groups of invalid characters with a single `-` instead, to retain semantic grouping. I *do not* currently propose to change how `client setname` sanitizes anything, although that could also be considered.
null
2024-02-23T16:34:39Z
0.1
['StackExchange.Redis.Tests.Issues.Issue2653.CheckLibraySanitization']
[]
SixLabors/ImageSharp
sixlabors__imagesharp-2618
ad1b0e6dadba957fa924d500900a7213bee717d3
diff --git a/src/ImageSharp/Formats/Png/Filters/PaethFilter.cs b/src/ImageSharp/Formats/Png/Filters/PaethFilter.cs index b8324a0809..59c903c1dd 100644 --- a/src/ImageSharp/Formats/Png/Filters/PaethFilter.cs +++ b/src/ImageSharp/Formats/Png/Filters/PaethFilter.cs @@ -35,9 +35,9 @@ public static void Decode(Span<byte> scanline, Span<byte> previousScanline, int // row: a d // The Paeth function predicts d to be whichever of a, b, or c is nearest to // p = a + b - c. - if (Sse2.IsSupported && bytesPerPixel is 4) + if (Ssse3.IsSupported && bytesPerPixel is 4) { - DecodeSse3(scanline, previousScanline); + DecodeSsse3(scanline, previousScanline); } else if (AdvSimd.Arm64.IsSupported && bytesPerPixel is 4) { @@ -50,7 +50,7 @@ public static void Decode(Span<byte> scanline, Span<byte> previousScanline, int } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void DecodeSse3(Span<byte> scanline, Span<byte> previousScanline) + private static void DecodeSsse3(Span<byte> scanline, Span<byte> previousScanline) { ref byte scanBaseRef = ref MemoryMarshal.GetReference(scanline); ref byte prevBaseRef = ref MemoryMarshal.GetReference(previousScanline);
diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderFilterTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderFilterTests.cs index ec6de0dfab..f5c42c734b 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderFilterTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderFilterTests.cs @@ -170,6 +170,9 @@ private static void RunPaethFilterTest() [Fact] public void PaethFilter_WithHardwareIntrinsics_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunPaethFilterTest, HwIntrinsics.AllowAll); + [Fact] + public void PaethFilter_WithoutSsse3_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunPaethFilterTest, HwIntrinsics.DisableSSSE3); + [Fact] public void PaethFilter_WithoutHardwareIntrinsics_Works() => FeatureTestRunner.RunWithHwIntrinsicsFeature(RunPaethFilterTest, HwIntrinsics.DisableHWIntrinsic); }
PlatformNotSupportedException from Image.Load on server ### Prerequisites - [X] I have written a descriptive issue title - [X] I have verified that I am running the latest version of ImageSharp - [X] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [X] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### ImageSharp version 3.1.1 and 3.1.0 ### Other ImageSharp packages and versions None ### Environment (Operating system, version and so on) Windows Server 2016 Datacenter, Intel Xeon Gold 6134, 64-bit ### .NET Framework version .NET 8 ### Description When loading data using `Image.Load` on a server with ImageSharp >= 3.1.0, I get the exception below. It works fine in my local computer, and it works fine on the server with ImageSharp 3.0.2. Only from 3.1.0 and above does it fail on the server. ``` Unhandled exception. System.PlatformNotSupportedException: Operation is not supported on this platform. at System.Runtime.Intrinsics.X86.Ssse3.Abs(Vector128`1 value) at SixLabors.ImageSharp.Formats.Png.PngDecoderCore.DecodePixelData[TPixel](FrameControl frameControl, DeflateStream compressedStream, ImageFrame`1 imageFrame, PngMetadata pngMetadata, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.Png.PngDecoderCore.ReadScanlines[TPixel](Int32 chunkLength, ImageFrame`1 image, PngMetadata pngMetadata, Func`1 getData, FrameControl& frameControl, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.Png.PngDecoderCore.Decode[TPixel](BufferedReadStream stream, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.ImageDecoderUtilities.Decode[TPixel](IImageDecoderInternals decoder, Configuration configuration, Stream stream, Func`3 largeImageExceptionFactory, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.ImageDecoderUtilities.Decode[TPixel](IImageDecoderInternals decoder, Configuration configuration, Stream stream, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.Png.PngDecoder.Decode[TPixel](PngDecoderOptions options, Stream stream, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.Png.PngDecoder.Decode(PngDecoderOptions options, Stream stream, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.SpecializedImageDecoder`1.Decode(DecoderOptions options, Stream stream, CancellationToken cancellationToken) at SixLabors.ImageSharp.Formats.ImageDecoder.<>c__DisplayClass1_0.<Decode>b__0(Stream s) at SixLabors.ImageSharp.Formats.ImageDecoder.<WithSeekableStream>g__PeformActionAndResetPosition|11_0[T](Stream s, Int64 position, <>c__DisplayClass11_0`1&) at SixLabors.ImageSharp.Formats.ImageDecoder.WithSeekableStream[T](DecoderOptions options, Stream stream, Func`2 action) at SixLabors.ImageSharp.Formats.ImageDecoder.Decode(DecoderOptions options, Stream stream) at SixLabors.ImageSharp.Image.Decode(DecoderOptions options, Stream stream) at SixLabors.ImageSharp.Image.<>c__DisplayClass80_0.<Load>b__0(Stream s) at SixLabors.ImageSharp.Image.WithSeekableStream[T](DecoderOptions options, Stream stream, Func`2 action) at SixLabors.ImageSharp.Image.Load(DecoderOptions options, Stream stream) at SixLabors.ImageSharp.Image.Load(DecoderOptions options, ReadOnlySpan`1 buffer) at SixLabors.ImageSharp.Image.Load(ReadOnlySpan`1 buffer) at <StartupCode$ImageSharpTest>.$Foo.main@() in C:\Users\cmeer\Source\Repos\ImageSharpTest\ImageSharpTest\Program.fs:line 7 ``` ### Steps to Reproduce Please see the attached repro solution. I am publishing it using this command: ``` dotnet publish ImageSharpTest -c Release -r win-x64 --self-contained -o out ``` [ImageSharpTest.zip](https://github.com/SixLabors/ImageSharp/files/13645770/ImageSharpTest.zip) For reference, the repro solution contains a trivial/minimal project file and this `Program.fs` file: ```f# open System open SixLabors.ImageSharp let data = "..." // 56665 characters omitted here data |> Convert.FromBase64String |> Image.Load |> ignore<Image> printfn "OK" ``` ### Images _No response_
I don’t think this is a regression. There have been no changes to the scan line decoding code across those versions. As mentioned, using the trivial repro, it works when referencing 3.0.2 and does not work when referencing 3.1.0 or 3.1.1. Isn't that the definition of a regression? Actually, you're correct. I broke it 7 months ago. https://github.com/SixLabors/ImageSharp/blob/12da625cbb95a7005dbc78a82b9602f3a90022de/src/ImageSharp/Formats/Png/Filters/PaethFilter.cs
2023-12-12T12:57:28Z
0.1
['SixLabors.ImageSharp.Tests.Formats.Png.PngDecoderFilterTests.PaethFilter_WithoutSsse3_Works']
[]
SixLabors/ImageSharp
sixlabors__imagesharp-2543
8bd273f3932f44eb664b2a217fd92f7a8e84d392
diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.Rational.cs b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.Rational.cs index 96603b182a..e4fe13fe57 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.Rational.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.Rational.cs @@ -165,4 +165,9 @@ public abstract partial class ExifTag /// Gets the GPSDestDistance exif tag. /// </summary> public static ExifTag<Rational> GPSDestDistance { get; } = new ExifTag<Rational>(ExifTagValue.GPSDestDistance); + + /// <summary> + /// Gets the GPSHPositioningError exif tag. + /// </summary> + public static ExifTag<Rational> GPSHPositioningError { get; } = new ExifTag<Rational>(ExifTagValue.GPSHPositioningError); } diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTagValue.cs b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTagValue.cs index 3788a1296f..56e8a3ffd1 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTagValue.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTagValue.cs @@ -1691,6 +1691,11 @@ internal enum ExifTagValue /// </summary> GPSDifferential = 0x001E, + /// <summary> + /// GPSHPositioningError + /// </summary> + GPSHPositioningError = 0x001F, + /// <summary> /// Used in the Oce scanning process. /// Identifies the scanticket used in the scanning process. diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs index a4217fe026..93f67d46ad 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs @@ -241,6 +241,8 @@ internal static partial class ExifValues return new ExifRational(ExifTag.GPSDestBearing); case ExifTagValue.GPSDestDistance: return new ExifRational(ExifTag.GPSDestDistance); + case ExifTagValue.GPSHPositioningError: + return new ExifRational(ExifTag.GPSHPositioningError); case ExifTagValue.WhitePoint: return new ExifRationalArray(ExifTag.WhitePoint);
diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs index bf1ef1a9b0..99cafa8960 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs @@ -128,6 +128,7 @@ public class ExifValuesTests { ExifTag.GPSImgDirection }, { ExifTag.GPSDestBearing }, { ExifTag.GPSDestDistance }, + { ExifTag.GPSHPositioningError }, }; public static TheoryData<ExifTag> RationalArrayTags => new TheoryData<ExifTag>
Support for GPSHPositioningError tag? ### Prerequisites - [X] I have written a descriptive issue title - [X] I have verified that I am running the latest version of ImageSharp - [X] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [X] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### ImageSharp version 3.0.2 ### Other ImageSharp packages and versions None ### Environment (Operating system, version and so on) windows, android, ios ### .NET Framework version 7 ### Description Is Support for GPSHPositioningError tag present? if not, can we include that. ### Steps to Reproduce Read exif image which has GPSHPositioningError. unable to read or write the tag. ### Images _No response_
Hi @prabhavmehra Just a heads up, feature requests should be made via Discussion channels not raised as issues. You're more than welcome to submit a PR if you feel like adding the missing tag. The relevant information about the tags backing structure is here. https://exiftool.org/TagNames/GPS.html I can have a look at adding this one, is it just this one tag that is missing or are there more GPS related tags that should be included? EDIT: Seems like they are all there except for this one.
2023-10-05T07:04:34Z
0.1
[]
['SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifLongArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedShortArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUndefinedTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedRationalTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifShortArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUndefinedArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifNumberTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifRationalArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedRationalArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifEncodedStringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifRationalTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifStringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifNumberArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifLongTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifByteArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.NumberTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUcs2StringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifShortTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifByteTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifDoubleArrayTests']
SixLabors/ImageSharp
sixlabors__imagesharp-2541
e905b0a330b4ff69ea2eb7adffa46aa676a11b7d
diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.LongArray.cs b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.LongArray.cs index 741df50f2d..4767ca852e 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.LongArray.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.LongArray.cs @@ -56,11 +56,6 @@ public abstract partial class ExifTag /// </summary> public static ExifTag<uint[]> IntergraphRegisters { get; } = new ExifTag<uint[]>(ExifTagValue.IntergraphRegisters); - /// <summary> - /// Gets the TimeZoneOffset exif tag. - /// </summary> - public static ExifTag<uint[]> TimeZoneOffset { get; } = new ExifTag<uint[]>(ExifTagValue.TimeZoneOffset); - /// <summary> /// Gets the offset to child IFDs exif tag. /// </summary> diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.SignedShortArray.cs b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.SignedShortArray.cs new file mode 100644 index 0000000000..d6a9205143 --- /dev/null +++ b/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.SignedShortArray.cs @@ -0,0 +1,13 @@ +// Copyright (c) Six Labors. +// Licensed under the Six Labors Split License. + +namespace SixLabors.ImageSharp.Metadata.Profiles.Exif; + +/// <content/> +public abstract partial class ExifTag +{ + /// <summary> + /// Gets the TimeZoneOffset exif tag. + /// </summary> + public static ExifTag<short[]> TimeZoneOffset { get; } = new ExifTag<short[]>(ExifTagValue.TimeZoneOffset); +} diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifSignedShortArray.cs b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifSignedShortArray.cs index 8023fb8bca..206417f667 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifSignedShortArray.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifSignedShortArray.cs @@ -5,6 +5,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif; internal sealed class ExifSignedShortArray : ExifArrayValue<short> { + public ExifSignedShortArray(ExifTag<short[]> tag) + : base(tag) + { + } + public ExifSignedShortArray(ExifTagValue tag) : base(tag) { diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs index 8aa54c3a40..a4217fe026 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Values/ExifValues.cs @@ -144,8 +144,6 @@ internal static partial class ExifValues return new ExifLongArray(ExifTag.StripRowCounts); case ExifTagValue.IntergraphRegisters: return new ExifLongArray(ExifTag.IntergraphRegisters); - case ExifTagValue.TimeZoneOffset: - return new ExifLongArray(ExifTag.TimeZoneOffset); case ExifTagValue.SubIFDs: return new ExifLongArray(ExifTag.SubIFDs); @@ -417,6 +415,9 @@ internal static partial class ExifValues case ExifTagValue.Decode: return new ExifSignedRationalArray(ExifTag.Decode); + case ExifTagValue.TimeZoneOffset: + return new ExifSignedShortArray(ExifTag.TimeZoneOffset); + case ExifTagValue.ImageDescription: return new ExifString(ExifTag.ImageDescription); case ExifTagValue.Make:
diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs index 1adb7bd556..bf1ef1a9b0 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs @@ -70,8 +70,7 @@ public class ExifValuesTests { ExifTag.JPEGDCTables }, { ExifTag.JPEGACTables }, { ExifTag.StripRowCounts }, - { ExifTag.IntergraphRegisters }, - { ExifTag.TimeZoneOffset } + { ExifTag.IntergraphRegisters } }; public static TheoryData<ExifTag> NumberTags => new TheoryData<ExifTag> @@ -235,6 +234,11 @@ public class ExifValuesTests { ExifTag.Decode } }; + public static TheoryData<ExifTag> SignedShortArrayTags => new TheoryData<ExifTag> + { + { ExifTag.TimeZoneOffset } + }; + public static TheoryData<ExifTag> StringTags => new TheoryData<ExifTag> { { ExifTag.ImageDescription }, @@ -559,6 +563,21 @@ public void ExifSignedRationalArrayTests(ExifTag tag) Assert.Equal(expected, typed.Value); } + + [Theory] + [MemberData(nameof(SignedShortArrayTags))] + public void ExifSignedShortArrayTests(ExifTag tag) + { + short[] expected = new short[] { 21, 42 }; + ExifValue value = ExifValues.Create(tag); + + Assert.False(value.TrySetValue(expected.ToString())); + Assert.True(value.TrySetValue(expected)); + + var typed = (ExifSignedShortArray)value; + Assert.Equal(expected, typed.Value); + } + [Theory] [MemberData(nameof(StringTags))] public void ExifStringTests(ExifTag tag)
ExifTag.TimeZoneOffset is defined as uint[], but the TIFF spec defines it as signed short ### Prerequisites - [X] I have written a descriptive issue title - [X] I have verified that I am running the latest version of ImageSharp - [X] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [X] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### ImageSharp version 3.0.1 ### Other ImageSharp packages and versions ? ### Environment (Operating system, version and so on) Windows 10 x64 ### .NET Framework version .NET 7 ### Description The TimeZoneOffset Exif tag is defined in the code as a uint[] (https://github.com/SixLabors/ImageSharp/blob/a49862a755fb24804043390f391839416bf4547a/src/ImageSharp/Metadata/Profiles/Exif/Tags/ExifTag.LongArray.cs#L62) However, the specifications for TIFF/EP which defines that tag seem to require a signed short (optionally two signed shorts). See Page 19 and 40 of the TIFF/EP spec : https://web.archive.org/web/20060212163025/http://www.map.tu.chiba-u.ac.jp/IEC/100/TA2/recdoc/N4378.pdf This requirement is also encoded in the TIFF verification code in JHove, which then flags the file as non-conformant (https://jhove.openpreservation.org/modules/tiff/tags/ , https://jhove.openpreservation.org/) As a side note, since ExifTag<T> doesn't have a public constructor, I cannot create my own tags to work around this issue (or to add custom tags to the file). ### Steps to Reproduce Set the DateTimeOffsetTag in a tiff file, then save the file ``` var image = Image.Load(sourceTifFile); image.Frames[0].Metadata.ExifProfile = new ExifProfile(); image.Frames[0].Metadata.ExifProfile.SetValue(ExifTag.TimeZoneOffset, new uint[] {1}); image.Save(outputTifFile); ``` Now run the output tiff file through jhove verification ``` robin@ubuntu:~$ jhove -m TIFF-hul Output.tif Jhove (Rel. 1.20.0, 2019-01-19) Date: 2023-04-13 13:33:05 PDT RepresentationInformation: Output.tif ReportingModule: TIFF-hul, Rel. 1.8 (2017-05-11) LastModified: 2023-04-13 13:27:13 PDT Size: 343128 Format: TIFF Status: Not well-formed SignatureMatches: TIFF-hul ErrorMessage: Type mismatch for tag 34858; expecting 8, saw 4 MIMEtype: image/tiff ``` You can install jhove on an ubuntu box with `sudo apt-get install jhove default-jre` Note: I ran the ImageSharp test code on Windows, just used Ubuntu for testing as the jhove install is easier ### Images _No response_
That looks like a mistake indeed but changing this would introduce a breaking change. But I do wonder if anyone is using this since we implemented this incorrectly. Maybe we could patch this in a minor release and make a note about this minor breaking change in the release notes? To avoid a breaking change you could attribute the existing TimeZoneOffset property as [Obsolete] and add a new property with the correct definition. While it affects the public API I don’t consider bug fixes like this to require minor versions. I’d be happy shipping a fix without one. I'm happy for this to be fixed in v3.1
2023-10-03T19:04:25Z
0.1
['SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedShortArrayTests']
['SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifLongArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUndefinedTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedRationalTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifShortArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUndefinedArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifNumberTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifRationalArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifSignedRationalArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifEncodedStringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifRationalTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifStringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifNumberArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifLongTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifByteArrayTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.NumberTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifUcs2StringTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifShortTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifByteTests', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values.ExifValuesTests.ExifDoubleArrayTests']
SixLabors/ImageSharp
sixlabors__imagesharp-2488
2738b3ab5793bddb96f3a5317d46afa0529220ce
diff --git a/src/ImageSharp/IO/IFileSystem.cs b/src/ImageSharp/IO/IFileSystem.cs index 96a9b5ba01..0f5113eff4 100644 --- a/src/ImageSharp/IO/IFileSystem.cs +++ b/src/ImageSharp/IO/IFileSystem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. namespace SixLabors.ImageSharp.IO; @@ -9,16 +9,32 @@ namespace SixLabors.ImageSharp.IO; internal interface IFileSystem { /// <summary> - /// Returns a readable stream as defined by the path. + /// Opens a file as defined by the path and returns it as a readable stream. /// </summary> /// <param name="path">Path to the file to open.</param> - /// <returns>A stream representing the file to open.</returns> + /// <returns>A stream representing the opened file.</returns> Stream OpenRead(string path); /// <summary> - /// Creates or opens a file and returns it as a writable stream as defined by the path. + /// Opens a file as defined by the path and returns it as a readable stream + /// that can be used for asynchronous reading. /// </summary> /// <param name="path">Path to the file to open.</param> - /// <returns>A stream representing the file to open.</returns> + /// <returns>A stream representing the opened file.</returns> + Stream OpenReadAsynchronous(string path); + + /// <summary> + /// Creates or opens a file as defined by the path and returns it as a writable stream. + /// </summary> + /// <param name="path">Path to the file to open.</param> + /// <returns>A stream representing the opened file.</returns> Stream Create(string path); + + /// <summary> + /// Creates or opens a file as defined by the path and returns it as a writable stream + /// that can be used for asynchronous reading and writing. + /// </summary> + /// <param name="path">Path to the file to open.</param> + /// <returns>A stream representing the opened file.</returns> + Stream CreateAsynchronous(string path); } diff --git a/src/ImageSharp/IO/LocalFileSystem.cs b/src/ImageSharp/IO/LocalFileSystem.cs index f4dfa2fe14..d1f619f486 100644 --- a/src/ImageSharp/IO/LocalFileSystem.cs +++ b/src/ImageSharp/IO/LocalFileSystem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. namespace SixLabors.ImageSharp.IO; @@ -11,6 +11,24 @@ internal sealed class LocalFileSystem : IFileSystem /// <inheritdoc/> public Stream OpenRead(string path) => File.OpenRead(path); + /// <inheritdoc/> + public Stream OpenReadAsynchronous(string path) => File.Open(path, new FileStreamOptions + { + Mode = FileMode.Open, + Access = FileAccess.Read, + Share = FileShare.Read, + Options = FileOptions.Asynchronous, + }); + /// <inheritdoc/> public Stream Create(string path) => File.Create(path); + + /// <inheritdoc/> + public Stream CreateAsynchronous(string path) => File.Open(path, new FileStreamOptions + { + Mode = FileMode.Create, + Access = FileAccess.ReadWrite, + Share = FileShare.None, + Options = FileOptions.Asynchronous, + }); } diff --git a/src/ImageSharp/Image.FromFile.cs b/src/ImageSharp/Image.FromFile.cs index 884acf7a40..a20e5d6c58 100644 --- a/src/ImageSharp/Image.FromFile.cs +++ b/src/ImageSharp/Image.FromFile.cs @@ -72,7 +72,7 @@ public static async Task<IImageFormat> DetectFormatAsync( { Guard.NotNull(options, nameof(options)); - using Stream stream = options.Configuration.FileSystem.OpenRead(path); + await using Stream stream = options.Configuration.FileSystem.OpenReadAsynchronous(path); return await DetectFormatAsync(options, stream, cancellationToken).ConfigureAwait(false); } @@ -144,7 +144,7 @@ public static async Task<ImageInfo> IdentifyAsync( CancellationToken cancellationToken = default) { Guard.NotNull(options, nameof(options)); - using Stream stream = options.Configuration.FileSystem.OpenRead(path); + await using Stream stream = options.Configuration.FileSystem.OpenReadAsynchronous(path); return await IdentifyAsync(options, stream, cancellationToken).ConfigureAwait(false); } @@ -214,7 +214,7 @@ public static async Task<Image> LoadAsync( string path, CancellationToken cancellationToken = default) { - using Stream stream = options.Configuration.FileSystem.OpenRead(path); + await using Stream stream = options.Configuration.FileSystem.OpenReadAsynchronous(path); return await LoadAsync(options, stream, cancellationToken).ConfigureAwait(false); } @@ -291,7 +291,7 @@ public static async Task<Image<TPixel>> LoadAsync<TPixel>( Guard.NotNull(options, nameof(options)); Guard.NotNull(path, nameof(path)); - using Stream stream = options.Configuration.FileSystem.OpenRead(path); + await using Stream stream = options.Configuration.FileSystem.OpenReadAsynchronous(path); return await LoadAsync<TPixel>(options, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/ImageSharp/ImageExtensions.cs b/src/ImageSharp/ImageExtensions.cs index cf970b3166..75e4f13257 100644 --- a/src/ImageSharp/ImageExtensions.cs +++ b/src/ImageSharp/ImageExtensions.cs @@ -70,7 +70,7 @@ public static async Task SaveAsync( Guard.NotNull(path, nameof(path)); Guard.NotNull(encoder, nameof(encoder)); - using Stream fs = source.GetConfiguration().FileSystem.Create(path); + await using Stream fs = source.GetConfiguration().FileSystem.CreateAsynchronous(path); await source.SaveAsync(fs, encoder, cancellationToken).ConfigureAwait(false); }
diff --git a/tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs b/tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs index 3d512b7d27..a1eeb25976 100644 --- a/tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs +++ b/tests/ImageSharp.Tests/IO/LocalFileSystemTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using SixLabors.ImageSharp.IO; @@ -11,36 +11,113 @@ public class LocalFileSystemTests public void OpenRead() { string path = Path.GetTempFileName(); - string testData = Guid.NewGuid().ToString(); - File.WriteAllText(path, testData); + try + { + string testData = Guid.NewGuid().ToString(); + File.WriteAllText(path, testData); - var fs = new LocalFileSystem(); + LocalFileSystem fs = new(); - using (var r = new StreamReader(fs.OpenRead(path))) - { - string data = r.ReadToEnd(); + using (FileStream stream = (FileStream)fs.OpenRead(path)) + using (StreamReader reader = new(stream)) + { + Assert.False(stream.IsAsync); + Assert.True(stream.CanRead); + Assert.False(stream.CanWrite); - Assert.Equal(testData, data); + string data = reader.ReadToEnd(); + + Assert.Equal(testData, data); + } } + finally + { + File.Delete(path); + } + } - File.Delete(path); + [Fact] + public async Task OpenReadAsynchronous() + { + string path = Path.GetTempFileName(); + try + { + string testData = Guid.NewGuid().ToString(); + File.WriteAllText(path, testData); + + LocalFileSystem fs = new(); + + await using (FileStream stream = (FileStream)fs.OpenReadAsynchronous(path)) + using (StreamReader reader = new(stream)) + { + Assert.True(stream.IsAsync); + Assert.True(stream.CanRead); + Assert.False(stream.CanWrite); + + string data = await reader.ReadToEndAsync(); + + Assert.Equal(testData, data); + } + } + finally + { + File.Delete(path); + } } [Fact] public void Create() { string path = Path.GetTempFileName(); - string testData = Guid.NewGuid().ToString(); - var fs = new LocalFileSystem(); + try + { + string testData = Guid.NewGuid().ToString(); + LocalFileSystem fs = new(); + + using (FileStream stream = (FileStream)fs.Create(path)) + using (StreamWriter writer = new(stream)) + { + Assert.False(stream.IsAsync); + Assert.True(stream.CanRead); + Assert.True(stream.CanWrite); - using (var r = new StreamWriter(fs.Create(path))) + writer.Write(testData); + } + + string data = File.ReadAllText(path); + Assert.Equal(testData, data); + } + finally { - r.Write(testData); + File.Delete(path); } + } - string data = File.ReadAllText(path); - Assert.Equal(testData, data); + [Fact] + public async Task CreateAsynchronous() + { + string path = Path.GetTempFileName(); + try + { + string testData = Guid.NewGuid().ToString(); + LocalFileSystem fs = new(); + + await using (FileStream stream = (FileStream)fs.CreateAsynchronous(path)) + await using (StreamWriter writer = new(stream)) + { + Assert.True(stream.IsAsync); + Assert.True(stream.CanRead); + Assert.True(stream.CanWrite); + + await writer.WriteAsync(testData); + } - File.Delete(path); + string data = File.ReadAllText(path); + Assert.Equal(testData, data); + } + finally + { + File.Delete(path); + } } } diff --git a/tests/ImageSharp.Tests/Image/ImageSaveTests.cs b/tests/ImageSharp.Tests/Image/ImageSaveTests.cs index a3f03bed5a..f9c01ab564 100644 --- a/tests/ImageSharp.Tests/Image/ImageSaveTests.cs +++ b/tests/ImageSharp.Tests/Image/ImageSaveTests.cs @@ -44,7 +44,7 @@ public ImageSaveTests() [Fact] public void SavePath() { - var stream = new MemoryStream(); + using MemoryStream stream = new(); this.fileSystem.Setup(x => x.Create("path.png")).Returns(stream); this.image.Save("path.png"); @@ -54,7 +54,7 @@ public void SavePath() [Fact] public void SavePathWithEncoder() { - var stream = new MemoryStream(); + using MemoryStream stream = new(); this.fileSystem.Setup(x => x.Create("path.jpg")).Returns(stream); this.image.Save("path.jpg", this.encoderNotInFormat.Object); @@ -73,7 +73,7 @@ public void ToBase64String() [Fact] public void SaveStreamWithMime() { - var stream = new MemoryStream(); + using MemoryStream stream = new(); this.image.Save(stream, this.localImageFormat.Object); this.encoder.Verify(x => x.Encode(this.image, stream)); @@ -82,7 +82,7 @@ public void SaveStreamWithMime() [Fact] public void SaveStreamWithEncoder() { - var stream = new MemoryStream(); + using MemoryStream stream = new(); this.image.Save(stream, this.encoderNotInFormat.Object); diff --git a/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs b/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs index a8f9981b44..996310d8c3 100644 --- a/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs +++ b/tests/ImageSharp.Tests/Image/ImageTests.ImageLoadTestBase.cs @@ -122,6 +122,7 @@ protected ImageLoadTestBase() Stream StreamFactory() => this.DataStream; this.LocalFileSystemMock.Setup(x => x.OpenRead(this.MockFilePath)).Returns(StreamFactory); + this.LocalFileSystemMock.Setup(x => x.OpenReadAsynchronous(this.MockFilePath)).Returns(StreamFactory); this.topLevelFileSystem.AddFile(this.MockFilePath, StreamFactory); this.LocalConfiguration.FileSystem = this.LocalFileSystemMock.Object; this.TopLevelConfiguration.FileSystem = this.topLevelFileSystem; @@ -132,6 +133,11 @@ public void Dispose() // Clean up the global object; this.localStreamReturnImageRgba32?.Dispose(); this.localStreamReturnImageAgnostic?.Dispose(); + + if (this.dataStreamLazy.IsValueCreated) + { + this.dataStreamLazy.Value.Dispose(); + } } protected virtual Stream CreateStream() => this.TestFormat.CreateStream(this.Marker); diff --git a/tests/ImageSharp.Tests/TestFileSystem.cs b/tests/ImageSharp.Tests/TestFileSystem.cs index 8aefbe320e..9013d15530 100644 --- a/tests/ImageSharp.Tests/TestFileSystem.cs +++ b/tests/ImageSharp.Tests/TestFileSystem.cs @@ -1,6 +1,8 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +#nullable enable + namespace SixLabors.ImageSharp.Tests; /// <summary> @@ -8,7 +10,7 @@ namespace SixLabors.ImageSharp.Tests; /// </summary> public class TestFileSystem : ImageSharp.IO.IFileSystem { - private readonly Dictionary<string, Func<Stream>> fileSystem = new Dictionary<string, Func<Stream>>(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, Func<Stream>> fileSystem = new(StringComparer.OrdinalIgnoreCase); public void AddFile(string path, Func<Stream> data) { @@ -18,35 +20,39 @@ public void AddFile(string path, Func<Stream> data) } } - public Stream Create(string path) + public Stream Create(string path) => this.GetStream(path) ?? File.Create(path); + + public Stream CreateAsynchronous(string path) => this.GetStream(path) ?? File.Open(path, new FileStreamOptions { - // if we have injected a fake file use it instead - lock (this.fileSystem) - { - if (this.fileSystem.ContainsKey(path)) - { - Stream stream = this.fileSystem[path](); - stream.Position = 0; - return stream; - } - } + Mode = FileMode.Create, + Access = FileAccess.ReadWrite, + Share = FileShare.None, + Options = FileOptions.Asynchronous, + }); - return File.Create(path); - } + public Stream OpenRead(string path) => this.GetStream(path) ?? File.OpenRead(path); + + public Stream OpenReadAsynchronous(string path) => this.GetStream(path) ?? File.Open(path, new FileStreamOptions + { + Mode = FileMode.Open, + Access = FileAccess.Read, + Share = FileShare.Read, + Options = FileOptions.Asynchronous, + }); - public Stream OpenRead(string path) + private Stream? GetStream(string path) { // if we have injected a fake file use it instead lock (this.fileSystem) { - if (this.fileSystem.ContainsKey(path)) + if (this.fileSystem.TryGetValue(path, out Func<Stream>? streamFactory)) { - Stream stream = this.fileSystem[path](); + Stream stream = streamFactory(); stream.Position = 0; return stream; } } - return File.OpenRead(path); + return null; } } diff --git a/tests/ImageSharp.Tests/TestUtilities/SingleStreamFileSystem.cs b/tests/ImageSharp.Tests/TestUtilities/SingleStreamFileSystem.cs index 732948b8e0..7b519531ab 100644 --- a/tests/ImageSharp.Tests/TestUtilities/SingleStreamFileSystem.cs +++ b/tests/ImageSharp.Tests/TestUtilities/SingleStreamFileSystem.cs @@ -13,5 +13,9 @@ internal class SingleStreamFileSystem : IFileSystem Stream IFileSystem.Create(string path) => this.stream; + Stream IFileSystem.CreateAsynchronous(string path) => this.stream; + Stream IFileSystem.OpenRead(string path) => this.stream; + + Stream IFileSystem.OpenReadAsynchronous(string path) => this.stream; }
Async IO methods should use `FileOptions.Asynchronous` ### Prerequisites - [X] I have written a descriptive issue title - [X] I have verified that I am running the latest version of ImageSharp - [X] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [X] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### ImageSharp version 3.0.1 ### Environment (Operating system, version and so on) Windows 11 Version 22H2 ### .NET Framework version .NET 7.0.304 ### Description Async methods that read/write from the file system, such as `Image.LoadAsync` and `Image.SaveAsync`, use async methods on `FileStream` but don't instantiate the `FileStream` with `FileOptions.Asynchronous`, as should be done when using async operations. This means that the implementation isn't actually truly async and instead uses synchronous IO on a new thread, needlessly using more resources. There is a simple workaround for this by creating the `FileStream` manually and giving ImageSharp the stream as opposed to the file path, e.g.: ```c# await using (var fileStream = new FileStream(path, new FileStreamOptions { Mode = FileMode.Open, Access = FileAccess.Read, Share = FileShare.Read, Options = FileOptions.Asynchronous, })) using (var image = await Image.LoadAsync(fileStream)) { // ... } ``` but I feel like this is a bug and should be fixed in ImageSharp itself. The method is misleading, suggesting that it uses async IO while actually doesn't.
This makes sense, here is what BCL is doing for `File.ReadAllTextAsync`: https://github.com/dotnet/runtime/blob/2f208128f257b2390a8edefa0a19e0eaad6bd419/src/libraries/System.Private.CoreLib/src/System/IO/File.cs#L853-L856 I guess `SequentialScan` would make things worse in our case, because `BufferedReadStream` does `Seek` a lot. @Neme12 interested creating a PR? Sure, I can give it a try.
2023-06-30T11:19:28Z
0.1
['SixLabors.ImageSharp.Tests.IO.LocalFileSystemTests.CreateAsynchronous', 'SixLabors.ImageSharp.Tests.IO.LocalFileSystemTests.OpenReadAsynchronous']
['SixLabors.ImageSharp.Tests.IO.LocalFileSystemTests.Create', 'SixLabors.ImageSharp.Tests.IO.LocalFileSystemTests.OpenRead']
SixLabors/ImageSharp
sixlabors__imagesharp-2322
df13097b46b2389d29e0af92802045a38ab7fe1c
diff --git a/src/ImageSharp/Processing/Extensions/Drawing/DrawImageExtensions.cs b/src/ImageSharp/Processing/Extensions/Drawing/DrawImageExtensions.cs index 2cb8dc3211..ad93d6f167 100644 --- a/src/ImageSharp/Processing/Extensions/Drawing/DrawImageExtensions.cs +++ b/src/ImageSharp/Processing/Extensions/Drawing/DrawImageExtensions.cs @@ -12,168 +12,280 @@ namespace SixLabors.ImageSharp.Processing; public static class DrawImageExtensions { /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, float opacity) { - var options = source.GetGraphicsOptions(); - return source.ApplyProcessor( - new DrawImageProcessor( - image, - Point.Empty, - options.ColorBlendingMode, - options.AlphaCompositionMode, - opacity)); + GraphicsOptions options = source.GetGraphicsOptions(); + return DrawImage(source, image, options.ColorBlendingMode, options.AlphaCompositionMode, opacity); } /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="colorBlending">The blending mode.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Rectangle rectangle, + float opacity) + { + GraphicsOptions options = source.GetGraphicsOptions(); + return DrawImage(source, image, rectangle, options.ColorBlendingMode, options.AlphaCompositionMode, opacity); + } + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="colorBlending">The color blending mode.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, PixelColorBlendingMode colorBlending, - float opacity) => - source.ApplyProcessor( - new DrawImageProcessor( - image, - Point.Empty, - colorBlending, - source.GetGraphicsOptions().AlphaCompositionMode, - opacity)); + float opacity) + => DrawImage(source, image, Point.Empty, colorBlending, opacity); /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="colorBlending">The color blending mode.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Rectangle rectangle, + PixelColorBlendingMode colorBlending, + float opacity) + => DrawImage(source, image, rectangle, colorBlending, source.GetGraphicsOptions().AlphaCompositionMode, opacity); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> /// <param name="colorBlending">The color blending mode.</param> /// <param name="alphaComposition">The alpha composition mode.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, PixelColorBlendingMode colorBlending, PixelAlphaCompositionMode alphaComposition, - float opacity) => - source.ApplyProcessor(new DrawImageProcessor(image, Point.Empty, colorBlending, alphaComposition, opacity)); + float opacity) + => DrawImage(source, image, Point.Empty, colorBlending, alphaComposition, opacity); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="colorBlending">The color blending mode.</param> + /// <param name="alphaComposition">The alpha composition mode.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Rectangle rectangle, + PixelColorBlendingMode colorBlending, + PixelAlphaCompositionMode alphaComposition, + float opacity) + => DrawImage(source, image, Point.Empty, rectangle, colorBlending, alphaComposition, opacity); /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> /// <param name="options">The options, including the blending type and blending amount.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, - GraphicsOptions options) => - source.ApplyProcessor( - new DrawImageProcessor( - image, - Point.Empty, - options.ColorBlendingMode, - options.AlphaCompositionMode, - options.BlendPercentage)); + GraphicsOptions options) + => DrawImage(source, image, Point.Empty, options); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="options">The options, including the blending type and blending amount.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Rectangle rectangle, + GraphicsOptions options) + => DrawImage(source, image, Point.Empty, rectangle, options); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Point location, + float opacity) + { + GraphicsOptions options = source.GetGraphicsOptions(); + return DrawImage(source, image, location, options.ColorBlendingMode, options.AlphaCompositionMode, opacity); + } /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="location">The location to draw the blended image.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, Point location, + Rectangle rectangle, float opacity) { - var options = source.GetGraphicsOptions(); - return source.ApplyProcessor( - new DrawImageProcessor( - image, - location, - options.ColorBlendingMode, - options.AlphaCompositionMode, - opacity)); + GraphicsOptions options = source.GetGraphicsOptions(); + return DrawImage(source, image, location, rectangle, options.ColorBlendingMode, options.AlphaCompositionMode, opacity); } /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="location">The location to draw the blended image.</param> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> /// <param name="colorBlending">The color blending to apply.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, Point location, PixelColorBlendingMode colorBlending, - float opacity) => - source.ApplyProcessor( - new DrawImageProcessor( - image, - location, - colorBlending, - source.GetGraphicsOptions().AlphaCompositionMode, - opacity)); + float opacity) + => DrawImage(source, image, location, colorBlending, source.GetGraphicsOptions().AlphaCompositionMode, opacity); /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="location">The location to draw the blended image.</param> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="colorBlending">The color blending to apply.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Point location, + Rectangle rectangle, + PixelColorBlendingMode colorBlending, + float opacity) + => DrawImage(source, image, location, rectangle, colorBlending, source.GetGraphicsOptions().AlphaCompositionMode, opacity); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="options">The options containing the blend mode and opacity.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Point location, + GraphicsOptions options) + => DrawImage(source, image, location, options.ColorBlendingMode, options.AlphaCompositionMode, options.BlendPercentage); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="options">The options containing the blend mode and opacity.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> + public static IImageProcessingContext DrawImage( + this IImageProcessingContext source, + Image image, + Point location, + Rectangle rectangle, + GraphicsOptions options) + => DrawImage(source, image, location, rectangle, options.ColorBlendingMode, options.AlphaCompositionMode, options.BlendPercentage); + + /// <summary> + /// Draws the given image together with the currently processing image by blending their pixels. + /// </summary> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> /// <param name="colorBlending">The color blending to apply.</param> /// <param name="alphaComposition">The alpha composition mode.</param> - /// <param name="opacity">The opacity of the image to blend. Must be between 0 and 1.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, Point location, PixelColorBlendingMode colorBlending, PixelAlphaCompositionMode alphaComposition, - float opacity) => - source.ApplyProcessor(new DrawImageProcessor(image, location, colorBlending, alphaComposition, opacity)); + float opacity) + => source.ApplyProcessor(new DrawImageProcessor(image, location, colorBlending, alphaComposition, opacity)); /// <summary> - /// Draws the given image together with the current one by blending their pixels. + /// Draws the given image together with the currently processing image by blending their pixels. /// </summary> - /// <param name="source">The image this method extends.</param> - /// <param name="image">The image to blend with the currently processing image.</param> - /// <param name="location">The location to draw the blended image.</param> - /// <param name="options">The options containing the blend mode and opacity.</param> - /// <returns>The <see cref="Image{TPixelDst}"/>.</returns> + /// <param name="source">The current image processing context.</param> + /// <param name="image">The image to draw on the currently processing image.</param> + /// <param name="location">The location on the currenty processing image at which to draw.</param> + /// <param name="rectangle">The rectangle structure that specifies the portion of the image to draw.</param> + /// <param name="colorBlending">The color blending to apply.</param> + /// <param name="alphaComposition">The alpha composition mode.</param> + /// <param name="opacity">The opacity of the image to draw. Must be between 0 and 1.</param> + /// <returns>The <see cref="IImageProcessingContext"/>.</returns> public static IImageProcessingContext DrawImage( this IImageProcessingContext source, Image image, Point location, - GraphicsOptions options) => + Rectangle rectangle, + PixelColorBlendingMode colorBlending, + PixelAlphaCompositionMode alphaComposition, + float opacity) => source.ApplyProcessor( - new DrawImageProcessor( - image, - location, - options.ColorBlendingMode, - options.AlphaCompositionMode, - options.BlendPercentage)); + new DrawImageProcessor(image, location, colorBlending, alphaComposition, opacity), + rectangle); } diff --git a/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor.cs b/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor.cs index b7d5b42f8a..9de4f862b8 100644 --- a/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor.cs +++ b/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor.cs @@ -63,7 +63,7 @@ public DrawImageProcessor( public IImageProcessor<TPixelBg> CreatePixelSpecificProcessor<TPixelBg>(Configuration configuration, Image<TPixelBg> source, Rectangle sourceRectangle) where TPixelBg : unmanaged, IPixel<TPixelBg> { - var visitor = new ProcessorFactoryVisitor<TPixelBg>(configuration, this, source, sourceRectangle); + ProcessorFactoryVisitor<TPixelBg> visitor = new(configuration, this, source, sourceRectangle); this.Image.AcceptVisitor(visitor); return visitor.Result; } @@ -88,8 +88,7 @@ public ProcessorFactoryVisitor(Configuration configuration, DrawImageProcessor d public void Visit<TPixelFg>(Image<TPixelFg> image) where TPixelFg : unmanaged, IPixel<TPixelFg> - { - this.Result = new DrawImageProcessor<TPixelBg, TPixelFg>( + => this.Result = new DrawImageProcessor<TPixelBg, TPixelFg>( this.configuration, image, this.source, @@ -98,6 +97,5 @@ public void Visit<TPixelFg>(Image<TPixelFg> image) this.definition.ColorBlendingMode, this.definition.AlphaCompositionMode, this.definition.Opacity); - } } } diff --git a/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor{TPixelBg,TPixelFg}.cs b/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor{TPixelBg,TPixelFg}.cs index 82e639f1bd..436a447972 100644 --- a/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor{TPixelBg,TPixelFg}.cs +++ b/src/ImageSharp/Processing/Processors/Drawing/DrawImageProcessor{TPixelBg,TPixelFg}.cs @@ -89,7 +89,7 @@ protected override void OnFrameApply(ImageFrame<TPixelBg> source) int width = maxX - minX; - var workingRect = Rectangle.FromLTRB(minX, minY, maxX, maxY); + Rectangle workingRect = Rectangle.FromLTRB(minX, minY, maxX, maxY); // Not a valid operation because rectangle does not overlap with this image. if (workingRect.Width <= 0 || workingRect.Height <= 0) @@ -98,7 +98,7 @@ protected override void OnFrameApply(ImageFrame<TPixelBg> source) "Cannot draw image because the source image does not overlap the target image."); } - var operation = new RowOperation(source.PixelBuffer, targetImage.Frames.RootFrame.PixelBuffer, blender, configuration, minX, width, locationY, targetX, this.Opacity); + DrawImageProcessor<TPixelBg, TPixelFg>.RowOperation operation = new(source.PixelBuffer, targetImage.Frames.RootFrame.PixelBuffer, blender, configuration, minX, width, locationY, targetX, this.Opacity); ParallelRowIterator.IterateRows( configuration, workingRect,
diff --git a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs index 0dcb961f84..d017e5ad42 100644 --- a/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/DrawImageTests.cs @@ -119,9 +119,7 @@ public void DrawImageOfDifferentPixelType<TPixel>(TestImageProvider<TPixel> prov public void WorksWithDifferentLocations(TestImageProvider<Rgba32> provider, int x, int y) { using Image<Rgba32> background = provider.GetImage(); - using Image<Rgba32> overlay = new(50, 50); - Assert.True(overlay.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> overlayMem)); - overlayMem.Span.Fill(Color.Black); + using Image<Rgba32> overlay = new(50, 50, Color.Black.ToRgba32()); background.Mutate(c => c.DrawImage(overlay, new Point(x, y), PixelColorBlendingMode.Normal, 1F)); @@ -138,6 +136,31 @@ public void WorksWithDifferentLocations(TestImageProvider<Rgba32> provider, int appendSourceFileOrDescription: false); } + [Theory] + [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 10, 10)] + [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 50, 25)] + [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 25, 50)] + [WithSolidFilledImages(100, 100, "White", PixelTypes.Rgba32, 50, 50)] + public void WorksWithDifferentBounds(TestImageProvider<Rgba32> provider, int width, int height) + { + using Image<Rgba32> background = provider.GetImage(); + using Image<Rgba32> overlay = new(50, 50, Color.Black.ToRgba32()); + + background.Mutate(c => c.DrawImage(overlay, new Rectangle(0, 0, width, height), PixelColorBlendingMode.Normal, 1F)); + + background.DebugSave( + provider, + testOutputDetails: $"{width}_{height}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + + background.CompareToReferenceOutput( + provider, + testOutputDetails: $"{width}_{height}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); + } + [Theory] [WithFile(TestImages.Png.Splash, PixelTypes.Rgba32)] public void DrawTransformed<TPixel>(TestImageProvider<TPixel> provider) @@ -158,12 +181,12 @@ public void DrawTransformed<TPixel>(TestImageProvider<TPixel> provider) Point position = new((image.Width - blend.Width) / 2, (image.Height - blend.Height) / 2); image.Mutate(x => x.DrawImage(blend, position, .75F)); - image.DebugSave(provider, appendSourceFileOrDescription: false, appendPixelTypeToFileName: false); + image.DebugSave(provider, appendPixelTypeToFileName: false, appendSourceFileOrDescription: false); image.CompareToReferenceOutput( ImageComparer.TolerantPercentage(0.002f), provider, - appendSourceFileOrDescription: false, - appendPixelTypeToFileName: false); + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: false); } [Theory] @@ -179,9 +202,6 @@ public void NonOverlappingImageThrows(TestImageProvider<Rgba32> provider, int x, Assert.Contains("does not overlap", ex.ToString()); - void Test() - { - background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); - } + void Test() => background.Mutate(context => context.DrawImage(overlay, new Point(x, y), new GraphicsOptions())); } } diff --git a/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_10_10.png b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_10_10.png new file mode 100644 index 0000000000..64ce14d509 --- /dev/null +++ b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_10_10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f353ee06664a6ff27c533af63cffb9eac4917103ba0b7fff9084fb4d2d42fed7 +size 155 diff --git a/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_25_50.png b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_25_50.png new file mode 100644 index 0000000000..7e0466186a --- /dev/null +++ b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_25_50.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af198da8f611eb97f3e4e358cb097cd292771d52e991de76495f073c1f1b9338 +size 154 diff --git a/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_25.png b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_25.png new file mode 100644 index 0000000000..6b93e597eb --- /dev/null +++ b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_25.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35bda87f28e03c5ed0d45412e367fae9b04b7684f5242dc20e7709e8ed71cd86 +size 156 diff --git a/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_50.png b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_50.png new file mode 100644 index 0000000000..540082dfdf --- /dev/null +++ b/tests/Images/External/ReferenceOutput/Drawing/DrawImageTests/WorksWithDifferentBounds_50_50.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8b9ff745592bb0e0a365cb0985a5519bf567fc73a09211c88bcda51356f9202 +size 155
Add DrawImage(Image, Point, Rectangle) method to the DrawImage processor Shouldn't be hard to implement and would have better performance than `Clone -> Crop -> Draw` path. From discussion by @TheBoneJarmer in https://github.com/SixLabors/ImageSharp/discussions/2102
null
2023-01-22T12:35:44Z
0.1
[]
['SixLabors.ImageSharp.Tests.Drawing.DrawImageTests.NonOverlappingImageThrows']
SixLabors/ImageSharp
sixlabors__imagesharp-2298
4a618a04e7287c0fbbe92fc8f6d8267e58478240
diff --git a/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs b/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs index 2013377ed6..94c2253d18 100644 --- a/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs +++ b/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs @@ -244,6 +244,12 @@ private long WriteFrame<TPixel>( entriesCollector.ProcessFrameInfo(frame, imageMetadata); entriesCollector.ProcessImageFormat(this); + if (writer.Position % 2 != 0) + { + // Write padding byte, because the tiff spec requires ifd offset to begin on a word boundary. + writer.Write(0); + } + this.frameMarkers.Add((ifdOffset, (uint)writer.Position)); return this.WriteIfd(writer, entriesCollector.Entries); diff --git a/src/ImageSharp/Formats/Tiff/TiffEncoderEntriesCollector.cs b/src/ImageSharp/Formats/Tiff/TiffEncoderEntriesCollector.cs index 64b300cd60..a84b8aed52 100644 --- a/src/ImageSharp/Formats/Tiff/TiffEncoderEntriesCollector.cs +++ b/src/ImageSharp/Formats/Tiff/TiffEncoderEntriesCollector.cs @@ -178,7 +178,7 @@ private void ProcessProfiles(ImageMetadata imageMetadata, bool skipMetadata, Exi Value = imageMetadata.IptcProfile.Data }; - this.Collector.Add(iptc); + this.Collector.AddOrReplace(iptc); } else { @@ -192,7 +192,7 @@ private void ProcessProfiles(ImageMetadata imageMetadata, bool skipMetadata, Exi Value = imageMetadata.IccProfile.ToByteArray() }; - this.Collector.Add(icc); + this.Collector.AddOrReplace(icc); } else { @@ -206,7 +206,7 @@ private void ProcessProfiles(ImageMetadata imageMetadata, bool skipMetadata, Exi Value = xmpProfile.Data }; - this.Collector.Add(xmp); + this.Collector.AddOrReplace(xmp); } else { @@ -278,7 +278,7 @@ public void Process(TiffEncoderCore encoder) Value = (ushort)TiffPlanarConfiguration.Chunky }; - ExifLong samplesPerPixel = new(ExifTagValue.SamplesPerPixel) + ExifShort samplesPerPixel = new(ExifTagValue.SamplesPerPixel) { Value = GetSamplesPerPixel(encoder) }; @@ -317,7 +317,7 @@ TiffPhotometricInterpretation.PaletteColor or } } - private static uint GetSamplesPerPixel(TiffEncoderCore encoder) + private static ushort GetSamplesPerPixel(TiffEncoderCore encoder) => encoder.PhotometricInterpretation switch { TiffPhotometricInterpretation.PaletteColor or
diff --git a/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderTests.cs index 7b55c1c5d0..2c30cc3d05 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderTests.cs @@ -246,6 +246,25 @@ public void TiffEncoder_PreservesPredictor<TPixel>(TestImageProvider<TPixel> pro Assert.Equal(expectedPredictor, frameMetadata.Predictor); } + // https://github.com/SixLabors/ImageSharp/issues/2297 + [Fact] + public void TiffEncoder_WritesIfdOffsetAtWordBoundary() + { + // arrange + var tiffEncoder = new TiffEncoder(); + using var memStream = new MemoryStream(); + using Image<Rgba32> image = new(1, 1); + byte[] expectedIfdOffsetBytes = { 12, 0 }; + + // act + image.Save(memStream, tiffEncoder); + + // assert + byte[] imageBytes = memStream.ToArray(); + Assert.Equal(imageBytes[4], expectedIfdOffsetBytes[0]); + Assert.Equal(imageBytes[5], expectedIfdOffsetBytes[1]); + } + [Theory] [WithFile(RgbUncompressed, PixelTypes.Rgba32, TiffCompression.CcittGroup3Fax, TiffCompression.CcittGroup3Fax)] [WithFile(RgbUncompressed, PixelTypes.Rgba32, TiffCompression.CcittGroup4Fax, TiffCompression.CcittGroup4Fax)] diff --git a/tests/ImageSharp.Tests/Formats/Tiff/TiffMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/TiffMetadataTests.cs index 8f4345b2e8..ffe4c573b3 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/TiffMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/TiffMetadataTests.cs @@ -71,7 +71,6 @@ private static void VerifyExpectedTiffFrameMetaDataIsPresent(TiffFrameMetadata f Assert.Equal(TiffBitsPerPixel.Bit4, frameMetaData.BitsPerPixel); Assert.Equal(TiffCompression.Lzw, frameMetaData.Compression); Assert.Equal(TiffPhotometricInterpretation.PaletteColor, frameMetaData.PhotometricInterpretation); - Assert.Equal(TiffPredictor.None, frameMetaData.Predictor); } [Theory] @@ -129,7 +128,7 @@ public void MetadataProfiles<TPixel>(TestImageProvider<TPixel> provider, bool ig Assert.NotNull(rootFrameMetaData.XmpProfile); Assert.NotNull(rootFrameMetaData.ExifProfile); Assert.Equal(2599, rootFrameMetaData.XmpProfile.Data.Length); - Assert.Equal(26, rootFrameMetaData.ExifProfile.Values.Count); + Assert.Equal(25, rootFrameMetaData.ExifProfile.Values.Count); } } @@ -163,38 +162,33 @@ public void BaselineTags<TPixel>(TestImageProvider<TPixel> provider) TiffFrameMetadata tiffFrameMetadata = rootFrame.Metadata.GetTiffMetadata(); Assert.NotNull(exifProfile); - // The original exifProfile has 30 values, but 4 of those values will be stored in the TiffFrameMetaData - // and removed from the profile on decode. - Assert.Equal(26, exifProfile.Values.Count); + Assert.Equal(25, exifProfile.Values.Count); Assert.Equal(TiffBitsPerPixel.Bit4, tiffFrameMetadata.BitsPerPixel); Assert.Equal(TiffCompression.Lzw, tiffFrameMetadata.Compression); - Assert.Equal("This is Название", exifProfile.GetValue(ExifTag.ImageDescription).Value); - Assert.Equal("This is Изготовитель камеры", exifProfile.GetValue(ExifTag.Make).Value); - Assert.Equal("This is Модель камеры", exifProfile.GetValue(ExifTag.Model).Value); - Assert.Equal("IrfanView", exifProfile.GetValue(ExifTag.Software).Value); + Assert.Equal("ImageDescription", exifProfile.GetValue(ExifTag.ImageDescription).Value); + Assert.Equal("Make", exifProfile.GetValue(ExifTag.Make).Value); + Assert.Equal("Model", exifProfile.GetValue(ExifTag.Model).Value); + Assert.Equal("ImageSharp", exifProfile.GetValue(ExifTag.Software).Value); Assert.Null(exifProfile.GetValue(ExifTag.DateTime)?.Value); - Assert.Equal("This is author1;Author2", exifProfile.GetValue(ExifTag.Artist).Value); + Assert.Equal("Artist", exifProfile.GetValue(ExifTag.Artist).Value); Assert.Null(exifProfile.GetValue(ExifTag.HostComputer)?.Value); - Assert.Equal("This is Авторские права", exifProfile.GetValue(ExifTag.Copyright).Value); + Assert.Equal("Copyright", exifProfile.GetValue(ExifTag.Copyright).Value); Assert.Equal(4, exifProfile.GetValue(ExifTag.Rating).Value); Assert.Equal(75, exifProfile.GetValue(ExifTag.RatingPercent).Value); - var expectedResolution = new Rational(10000, 1000, simplify: false); + var expectedResolution = new Rational(10, 1, simplify: false); Assert.Equal(expectedResolution, exifProfile.GetValue(ExifTag.XResolution).Value); Assert.Equal(expectedResolution, exifProfile.GetValue(ExifTag.YResolution).Value); Assert.Equal(new Number[] { 8u }, exifProfile.GetValue(ExifTag.StripOffsets)?.Value, new NumberComparer()); - Assert.Equal(new Number[] { 297u }, exifProfile.GetValue(ExifTag.StripByteCounts)?.Value, new NumberComparer()); + Assert.Equal(new Number[] { 285u }, exifProfile.GetValue(ExifTag.StripByteCounts)?.Value, new NumberComparer()); Assert.Null(exifProfile.GetValue(ExifTag.ExtraSamples)?.Value); Assert.Equal(32u, exifProfile.GetValue(ExifTag.RowsPerStrip).Value); Assert.Null(exifProfile.GetValue(ExifTag.SampleFormat)); - Assert.Equal(TiffPredictor.None, tiffFrameMetadata.Predictor); Assert.Equal(PixelResolutionUnit.PixelsPerInch, UnitConverter.ExifProfileToResolutionUnit(exifProfile)); ushort[] colorMap = exifProfile.GetValue(ExifTag.ColorMap)?.Value; Assert.NotNull(colorMap); Assert.Equal(48, colorMap.Length); - Assert.Equal(10537, colorMap[0]); - Assert.Equal(14392, colorMap[1]); - Assert.Equal(58596, colorMap[46]); - Assert.Equal(3855, colorMap[47]); + Assert.Equal(4369, colorMap[0]); + Assert.Equal(8738, colorMap[1]); Assert.Equal(TiffPhotometricInterpretation.PaletteColor, tiffFrameMetadata.PhotometricInterpretation); Assert.Equal(1u, exifProfile.GetValue(ExifTag.SamplesPerPixel).Value); @@ -238,7 +232,7 @@ public void Encode_PreservesMetadata<TPixel>(TestImageProvider<TPixel> provider) { // Load Tiff image DecoderOptions options = new() { SkipMetadata = false }; - using Image<TPixel> image = provider.GetImage(new TiffDecoder(), options); + using Image<TPixel> image = provider.GetImage(TiffDecoder, options); ImageMetadata inputMetaData = image.Metadata; ImageFrame<TPixel> rootFrameInput = image.Frames.RootFrame; @@ -284,17 +278,15 @@ public void Encode_PreservesMetadata<TPixel>(TestImageProvider<TPixel> provider) Assert.NotNull(encodedImageXmpProfile); Assert.Equal(xmpProfileInput.Data, encodedImageXmpProfile.Data); - Assert.Equal("IrfanView", exifProfileInput.GetValue(ExifTag.Software).Value); - Assert.Equal("This is Название", exifProfileInput.GetValue(ExifTag.ImageDescription).Value); - Assert.Equal("This is Изготовитель камеры", exifProfileInput.GetValue(ExifTag.Make).Value); - Assert.Equal("This is Авторские права", exifProfileInput.GetValue(ExifTag.Copyright).Value); - + Assert.Equal(exifProfileInput.GetValue(ExifTag.Software).Value, encodedImageExifProfile.GetValue(ExifTag.Software).Value); Assert.Equal(exifProfileInput.GetValue(ExifTag.ImageDescription).Value, encodedImageExifProfile.GetValue(ExifTag.ImageDescription).Value); Assert.Equal(exifProfileInput.GetValue(ExifTag.Make).Value, encodedImageExifProfile.GetValue(ExifTag.Make).Value); Assert.Equal(exifProfileInput.GetValue(ExifTag.Copyright).Value, encodedImageExifProfile.GetValue(ExifTag.Copyright).Value); + Assert.Equal(exifProfileInput.GetValue(ExifTag.Artist).Value, encodedImageExifProfile.GetValue(ExifTag.Artist).Value); + Assert.Equal(exifProfileInput.GetValue(ExifTag.Orientation).Value, encodedImageExifProfile.GetValue(ExifTag.Orientation).Value); + Assert.Equal(exifProfileInput.GetValue(ExifTag.Model).Value, encodedImageExifProfile.GetValue(ExifTag.Model).Value); - // Note that the encoded profile has PlanarConfiguration explicitly set, which is missing in the original image profile. Assert.Equal((ushort)TiffPlanarConfiguration.Chunky, encodedImageExifProfile.GetValue(ExifTag.PlanarConfiguration)?.Value); - Assert.Equal(exifProfileInput.Values.Count + 1, encodedImageExifProfile.Values.Count); + Assert.Equal(exifProfileInput.Values.Count, encodedImageExifProfile.Values.Count); } } diff --git a/tests/Images/Input/Tiff/metadata_sample.tiff b/tests/Images/Input/Tiff/metadata_sample.tiff index d767352688..9c0671ee7c 100644 --- a/tests/Images/Input/Tiff/metadata_sample.tiff +++ b/tests/Images/Input/Tiff/metadata_sample.tiff @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:72a1c8022d699e0e7248940f0734d01d6ab9bf4a71022e8b5626b64d66a5f39d -size 8107 +oid sha256:c2f20e3ebb51b743b635377b93e78a6dc91c07ca97be38f500c4d6d3c465d9c1 +size 3472
created/overwritten/copied TIFF images are invalid for Adobe Premiere Pro ### Prerequisites - [X] I have written a descriptive issue title - [X] I have verified that I am running the latest version of ImageSharp - [X] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [X] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### ImageSharp version 2.1.3 ### Other ImageSharp packages and versions SixLabors.ImageSharp 2.1.3, SixLabors.ImageSharp.Drawing 1.0.0-beta14, SixLabors.Fonts 1.0.0-beta17 ### Environment (Operating system, version and so on) Windows Server 2019 Standard 1809 ### .NET Framework version .Net 6.0, .Net Framework 4.8 ### Description Tiff files created by ImageSharp are not recognized by Adobe Premiere Pro on any try of import. If you try to import a tiff file an error will pop up: "The file cannot be opened because of a header error" If you take a tiff file created by ImageSharp, open it with Paint or Adobe Photoshop and save it without any changes, choosing TIFF format, Importing files to Premiere Pro becomes possible. It seems there is an issue, when encoding the tiff image by ImageSharp since other software can save the image in format properly. I could not find any differences in metadata that would indicate which parameter is invalid. ### Steps to Reproduce `using Image<Rgba32> image = new(1920, 1080);` `using MemoryStream stream = new();` `image.SaveAsTiff(output);` ### Images ![Premiere Pro error](https://user-images.githubusercontent.com/77407760/202243562-ef7ccfb3-580e-426d-814c-be6606d5eddf.png)
What is the memory stream used for in your repro? Seems unnecessary. The following should be enough: ``` using Image<Rgba32> image = new(1920, 1080); image.SaveAsTiff("output.tiff"); ``` I kind of doubt that there is an issue with "the file header" of ImageSharp tiff's. `tiffinfo` from `libtiff` does not report any errors. ImageMagick with `imagemagick identify -verbose` does not report any error. Also I can open ImageSharp Tiff images with any viewer I have: - gimp - pant.net - xnview - imagemagick - irfanview - paint None of those complains. I do not have access to Adobe Premiere Pro. Hi, Thank you for a prompt reply. The memory stream was my bad, I forgot to delete it after simplifying my example. I have to agree with you about the header, I took the stream of the file to decode the header into hexdec string, and read about tiff format headers. It all seems fine. I also read on various blogs that Premiere Pro "header error" is an unhandled exception for any issues when importing files. I have spent several hours with their support trying to get them to tell me what exactly makes the file crash but no luck, "file is no good" is the best I got out of them. I conducted multiple tests, creating files in all possible ways using ImageSharp. I don't have this problem with png or jpeg. I created a file in Photoshop to ensure that it works fine in Premiere pro, it's the same FullHD Black background (valid.tif attached). I thought if I load it via ImageSharp and just Save a copy of it without any changes (Copy.tif attached), the file should be identical, therefore be acceptable for Premiere Pro. using Image image = Image.Load(fileToCopy, out IImageFormat format); using MemoryStream stream = new(); image.SaveAsTiff(stream); File.WriteAllBytes(outputPath, stream.ToArray()); The output Copy.tiff file throws the same error when importing with PremierePro. Again, if I open it in Photoshop or Paint, save as Tiff, it will work just fine. I tried comparing 2 files, MediaInfo shows identical metadata, and the decoded header indicates Tiff properly. The only thing out of order is different file sizes. If I copy the files using File Explorer, the created copy has the same file size. From those two facts I presume there must be some differences between those files, and whatever it is it causes Premiere to crash. [Attachments.zip](https://github.com/SixLabors/ImageSharp/files/10030359/Attachments.zip) Maybe try a 1x1 pixel image. Save a 1x1 black pixel image with ImageSharp and again with another program you know is working with PremierePro. Then compare those binary and see what the difference is. Maybe it's as simple as the file extension is not as expected? Tiff instead of Tif? A quick google search shows that this indeed can cause this issue. Other then that, I am not sure what we can do about it. If `libtiff` does not complain, I am pretty sure the tiff is valid. I really think the PremierePro supports needs to tell why this error is happening. I created 2 1px files: -1pxPaint.tif -1pxImageSharp.tif 1pxImageSharp was created like so: ``` using Image<Rgba32> image = new(1, 1); TiffEncoder tiffEncoder = new() { BitsPerPixel = TiffBitsPerPixel.Bit24, PhotometricInterpretation = SixLabors.ImageSharp.Formats.Tiff.Constants.TiffPhotometricInterpretation.Rgb, Compression = SixLabors.ImageSharp.Formats.Tiff.Constants.TiffCompression.Lzw }; image.SaveAsTiff(@"\\plpns01\pl-sdi\TEMP\m_szulborski\Test\DubcardGenerator\1pxImageSharp.tif", tiffEncoder); ``` Encoder was needed because Paint creates Tiff with LZW Compression by default, and I wanted files to be identical. Comparing 2 files I can see: - Different file size: ImageSharp 221KB, Paint 222KB - Difference in **header** and the entire byte array (I read that header is first 8 bytes) 1pxPaint: **49492A000E000000**8000205010000F00FE00040001000000000000000001040001000000010000000101040001000000010000000201030003000000C80000000301030001000000050000000601030001000000020000001101040001000000080000001501030001000000030000001601040001000000010000001701040001000000050000001A01050001000000CE0000001B01050001000000D60000001C01030001000000010000002801030001000000020000003D01030001000000020000000000000008000800080000770100E803000000770100E8030000 1pxImageSharp: **49492A000D000000**80002050100E000001040001000000010000000101040001000000010000000201030003000000BB0000000301030001000000050000000601030001000000020000001101040001000000080000001501040001000000030000001601040001000000010000001701040001000000050000001A01050001000000C10000001B01050001000000C90000001C0103000100000001000000280103000100000002000000310102000B000000D10000000000000008000800080060000000010000006000000001000000496D61676553686172700000 [1pxImages.zip](https://github.com/SixLabors/ImageSharp/files/10033099/1pxImages.zip) > I created 2 1px files: -1pxPaint.tif -1pxImageSharp.tif > > 1pxImageSharp was created like so: > paint: 4949 byteorder 2A00 magick byte 0E00 FirstIfdOffset imagesharp: 4949 byteorder 2A00 magick byte 0D00 FirstIfdOffset The difference is that imagesharp ifd offset starts at offset 13 and paint starts at 14. After double checking the spec, this could be indeed a violation of the spec: "The directory may be at any location in the file after the header but must begin on a word boundary."
2022-11-19T15:36:50Z
0.1
['SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.TiffEncoder_WritesIfdOffsetAtWordBoundary']
['SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.EncoderOptions_SetBitPerPixel_Works', 'SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.EncoderOptions_SetPhotometricInterpretationAndCompression_Works', 'SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.EncoderOptions_UnsupportedBitPerPixel_DefaultTo24Bits', 'SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.TiffEncoder_PreservesBitsPerPixel_WhenInputIsL8', 'SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.EncoderOptions_SetPhotometricInterpretation_Works', 'SixLabors.ImageSharp.Tests.Formats.Tiff.TiffEncoderTests.EncoderOptions_WithInvalidCompressionAndPixelTypeCombination_DefaultsToRgb']
SixLabors/ImageSharp
sixlabors__imagesharp-2066
2bedf205277887b1d411597244cf4b0ea0d864b5
diff --git a/src/ImageSharp/Metadata/Profiles/Exif/ExifProfile.cs b/src/ImageSharp/Metadata/Profiles/Exif/ExifProfile.cs index e0ab8ecf95..665e4753a7 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/ExifProfile.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/ExifProfile.cs @@ -121,6 +121,14 @@ public IReadOnlyList<IExifValue> Values } } + /// <summary> + /// Returns the thumbnail in the EXIF profile when available. + /// </summary> + /// <returns> + /// The <see cref="Image"/>. + /// </returns> + public Image CreateThumbnail() => this.CreateThumbnail<Rgba32>(); + /// <summary> /// Returns the thumbnail in the EXIF profile when available. /// </summary>
diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs index a859852279..1668b7a125 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/Exif/ExifProfileTests.cs @@ -354,10 +354,15 @@ public void Values() TestProfile(profile); - using Image<Rgba32> thumbnail = profile.CreateThumbnail<Rgba32>(); + using Image thumbnail = profile.CreateThumbnail(); Assert.NotNull(thumbnail); Assert.Equal(256, thumbnail.Width); Assert.Equal(170, thumbnail.Height); + + using Image<Rgba32> genericThumbnail = profile.CreateThumbnail<Rgba32>(); + Assert.NotNull(genericThumbnail); + Assert.Equal(256, genericThumbnail.Width); + Assert.Equal(170, genericThumbnail.Height); } [Fact]
Missing API : `ExifProfile.CreateThumbnail<TPixel>()` ### ImageSharp version 2.0.0 ### Other ImageSharp packages and versions na ### Environment (Operating system, version and so on) na ### .NET Framework version na ### Description `ExifProfile.CreateThumbnail<TPixel>()` is missing its non-generic overload forcing people to know/understand pixel formats See this stack overflow question demonstrating that it can cause confusion when pixel formats are unknown to them https://stackoverflow.com/questions/71095559/how-do-i-extract-a-jpegs-exif-thumbnail-using-imagesharp/71095796 ### Steps to Reproduce na ### Images _No response_
null
2022-03-16T00:11:05Z
0.1
[]
['SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.Syncs', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.ReadWriteLargeProfileJpg', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.IfdStructure', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.WritingImagePreservesExifProfile', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.ConstructorEmpty', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.ProfileToByteArray', 'SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.ExifProfileTests.EmptyWriter']
SixLabors/ImageSharp
sixlabors__imagesharp-1234
7a538d454e535a52e2101554f11fd61f267d78c1
diff --git a/src/ImageSharp/Configuration.cs b/src/ImageSharp/Configuration.cs index 03e59d34b2..067257132f 100644 --- a/src/ImageSharp/Configuration.cs +++ b/src/ImageSharp/Configuration.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.Http; using SixLabors.ImageSharp.Formats; @@ -78,7 +79,7 @@ public int MaxDegreeOfParallelism /// Gets a set of properties for the Congiguration. /// </summary> /// <remarks>This can be used for storing global settings and defaults to be accessable to processors.</remarks> - public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>(); + public IDictionary<object, object> Properties { get; } = new ConcurrentDictionary<object, object>(); /// <summary> /// Gets the currently registered <see cref="IImageFormat"/>s. diff --git a/src/ImageSharp/GraphicOptionsDefaultsExtensions.cs b/src/ImageSharp/GraphicOptionsDefaultsExtensions.cs index d1581a00eb..80cdfd153e 100644 --- a/src/ImageSharp/GraphicOptionsDefaultsExtensions.cs +++ b/src/ImageSharp/GraphicOptionsDefaultsExtensions.cs @@ -71,11 +71,9 @@ public static GraphicsOptions GetGraphicsOptions(this IImageProcessingContext co return go; } - var configOptions = context.Configuration.GetGraphicsOptions(); - // do not cache the fall back to config into the the processing context // in case someone want to change the value on the config and expects it re trflow thru - return configOptions; + return context.Configuration.GetGraphicsOptions(); } /// <summary> diff --git a/src/ImageSharp/Processing/DefaultImageProcessorContext{TPixel}.cs b/src/ImageSharp/Processing/DefaultImageProcessorContext{TPixel}.cs index 4f47545fa3..7ed73d5176 100644 --- a/src/ImageSharp/Processing/DefaultImageProcessorContext{TPixel}.cs +++ b/src/ImageSharp/Processing/DefaultImageProcessorContext{TPixel}.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. +using System.Collections.Concurrent; using System.Collections.Generic; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -41,7 +42,7 @@ public DefaultImageProcessorContext(Configuration configuration, Image<TPixel> s public Configuration Configuration { get; } /// <inheritdoc/> - public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>(); + public IDictionary<object, object> Properties { get; } = new ConcurrentDictionary<object, object>(); /// <inheritdoc/> public Image<TPixel> GetResultImage()
diff --git a/tests/ImageSharp.Tests/GraphicOptionsDefaultsExtensionsTests.cs b/tests/ImageSharp.Tests/GraphicOptionsDefaultsExtensionsTests.cs index 72ec355385..21f26cd01c 100644 --- a/tests/ImageSharp.Tests/GraphicOptionsDefaultsExtensionsTests.cs +++ b/tests/ImageSharp.Tests/GraphicOptionsDefaultsExtensionsTests.cs @@ -1,7 +1,9 @@ // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. +using System.Threading.Tasks; using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Tests.Processing; using SixLabors.ImageSharp.Tests.TestUtilities; using Xunit; @@ -168,5 +170,18 @@ public void GetDefaultOptionsFromProcessingContext_IgnoreIncorectlyTypesDictionE Assert.NotNull(options); Assert.IsType<GraphicsOptions>(options); } + + [Theory] + [WithBlankImages(100, 100, PixelTypes.Rgba32)] + public void CanGetGraphicsOptionsMultiThreaded<TPixel>(TestImageProvider<TPixel> provider) + where TPixel : unmanaged, IPixel<TPixel> + { + // Could not get fake operations to trigger #1230 so using a real image. + Parallel.For(0, 10, _ => + { + using Image<TPixel> image = provider.GetImage(); + image.Mutate(x => x.BackgroundColor(Color.White)); + }); + } } } diff --git a/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs b/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs index 5f673b9d29..03fa6dfc2e 100644 --- a/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs +++ b/tests/ImageSharp.Tests/Processing/FakeImageOperationsProvider.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using SixLabors.ImageSharp.PixelFormats; @@ -56,7 +57,7 @@ public FakeImageOperations(Configuration configuration, Image<TPixel> source, bo public Configuration Configuration { get; } - public IDictionary<object, object> Properties { get; } = new Dictionary<object, object>(); + public IDictionary<object, object> Properties { get; } = new ConcurrentDictionary<object, object>(); public Image<TPixel> GetResultImage() {
context.BackgroundColor throws Object reference not set to an instance of an object. ### Prerequisites - [x] I have written a descriptive issue title - [x] I have verified that I am running the latest version of ImageSharp - [x] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode - [x] I have searched [open](https://github.com/SixLabors/ImageSharp/issues) and [closed](https://github.com/SixLabors/ImageSharp/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported ### Description ``` Object reference not set to an instance of an object. at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value) at SixLabors.ImageSharp.GraphicOptionsDefaultsExtensions.GetGraphicsOptions(Configuration configuration) at SixLabors.ImageSharp.GraphicOptionsDefaultsExtensions.GetGraphicsOptions(IImageProcessingContext context) at SixLabors.ImageSharp.Processing.BackgroundColorExtensions.BackgroundColor(IImageProcessingContext source, Color color) at Dropmaker.Program.<RunOnce>b__12_0(IImageProcessingContext ctx) in C:\Users\misir\source\repos\Dropmarker\src\Program.cs:line 280 at SixLabors.ImageSharp.Processing.ProcessingExtensions.ProcessingVisitor.Visit[TPixel](Image`1 image) at SixLabors.ImageSharp.Image`1.Accept(IImageVisitor visitor) at SixLabors.ImageSharp.Advanced.AdvancedImageExtensions.AcceptVisitor(Image source, IImageVisitor visitor) at SixLabors.ImageSharp.Processing.ProcessingExtensions.Mutate(Image source, Configuration configuration, Action`1 operation) at SixLabors.ImageSharp.Processing.ProcessingExtensions.Mutate(Image source, Action`1 operation) at Dropmaker.Program.RunOnce(State state) in C:\Users\misir\source\repos\Dropmarker\src\Program.cs:line 278 ``` ### Steps to Reproduce It happens sometimes when I compile & run this code. ```csharp var image = Image.Load("image.jpg"); image.Mutate(ctx => { ctx.BackgroundColor(Color.White); }); ``` ### System Configuration <!-- Tell us about the environment where you are experiencing the bug --> - ImageSharp version: SixLabors.ImageSharp@1.0.0-rc0002 - Environment (Operating system, version and so on): Windows 10 x64 - .NET Framework version: .NET Core 3.1 <!-- Thanks for reporting the issue to ImageSharp! -->
> It happens sometimes when I compile & run this code. What do you mean by this, Is the issue intermittent? What environmental factors trigger a difference in result. Are you running this in multiple threads?
2020-06-16T21:09:47Z
0.1
['SixLabors.ImageSharp.Tests.GraphicOptionsDefaultsExtensionsTests.CanGetGraphicsOptionsMultiThreaded']
[]
devlooped/moq
devlooped__moq-1081
5077cec3ff2a493fe8713541dd925f751bffdb2e
diff --git a/CHANGELOG.md b/CHANGELOG.md index eb4b92aad..129245883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1 #### Fixed * `SetupProperty` fails if property getter and setter are not both defined in mocked type (@stakx, #1017) +* Expression tree argument not matched when it contains a captured variable &ndash; evaluate all captures to their current values when comparing two expression trees (@QTom01, #1054) ## 4.14.7 (2020-10-14) diff --git a/src/Moq/ExpressionComparer.cs b/src/Moq/ExpressionComparer.cs index 693feafd2..a86e68574 100644 --- a/src/Moq/ExpressionComparer.cs +++ b/src/Moq/ExpressionComparer.cs @@ -31,6 +31,19 @@ public bool Equals(Expression x, Expression y) return false; } + // Before actually comparing two nodes, make sure that captures variables have been + // evaluated to their current values (as we don't want to compare their identities): + + if (x is MemberExpression) + { + x = x.Apply(EvaluateCaptures.Rewriter); + } + + if (y is MemberExpression) + { + y = y.Apply(EvaluateCaptures.Rewriter); + } + if (x.NodeType == y.NodeType) { switch (x.NodeType) @@ -200,21 +213,7 @@ private bool EqualsMemberBinding(MemberBinding x, MemberBinding y) private bool EqualsMember(MemberExpression x, MemberExpression y) { - // If any of the two nodes represents an access to a captured variable, - // we want to compare its value, not its identity. (`EvaluateCaptures` is - // a no-op in all other cases, so it is safe to apply "just in case".) - var rx = x.Apply(EvaluateCaptures.Rewriter); - var ry = y.Apply(EvaluateCaptures.Rewriter); - - if (rx == x && ry == y) - { - return x.Member == y.Member && this.Equals(x.Expression, y.Expression); - } - else - { - // Rewriting occurred, we might no longer have two `MemberExpression`s: - return this.Equals(rx, ry); - } + return x.Member == y.Member && this.Equals(x.Expression, y.Expression); } private bool EqualsMemberInit(MemberInitExpression x, MemberInitExpression y)
diff --git a/tests/Moq.Tests/Regressions/IssueReportsFixture.cs b/tests/Moq.Tests/Regressions/IssueReportsFixture.cs index 0416c4bad..337376404 100644 --- a/tests/Moq.Tests/Regressions/IssueReportsFixture.cs +++ b/tests/Moq.Tests/Regressions/IssueReportsFixture.cs @@ -3451,6 +3451,52 @@ public class DatabaseOptions #endregion + #region 1054 + + public class Issue1054 + { + // These tests assert that Moq compares the values of captured variables + // (as opposed to their identities). + + [Fact] + public void String_constant() + { + var s1 = "example"; + const string s2 = "example"; + + var mock = new Mock<IMockObject>(); + mock.Setup(x => x.Method(y => y.Id == s1)).Returns("mockResult"); + var result = mock.Object.Method(x => x.Id == s2); + + Assert.Equal("mockResult", result); + } + + [Fact] + public void String_variable() + { + var s1 = "example"; + var s2 = "example"; + + var mock = new Mock<IMockObject>(); + mock.Setup(x => x.Method(y => y.Id == s1)).Returns("mockResult"); + var result = mock.Object.Method(x => x.Id == s2); + + Assert.Equal("mockResult", result); + } + + public class MyObject + { + public string Id { get; set; } + } + + public interface IMockObject + { + public string Method(Expression<Func<MyObject, bool>> expression); + } + } + + #endregion + #region 1071 public class Issue1071
Issue comparing Expressions when one value is a constant I have discovered an issue when using Expressions in a Setup on a mock object. It seems using a simple comparison Expression fails to match properly when comparing to a string constant. The below code should reproduce it: ``` [Test] public async Task ExpressionTest() { var s1 = "example"; // Does not work const string s2 = "example"; // Works //var s2 = "example"; var mock = new Mock<IMockObject>(); mock.Setup(x => x.Method(y => y.Id == s1)) .ReturnsAsync("mockResult"); var result = await mock.Object.Method(x => x.Id == s2); // Exprect result to be "mockResult", instead it is null Assert.AreEqual(result, "mockResult"); } public class MyObject { public string Id { get; set; } } public interface IMockObject { public Task<string> Method(Expression<Func<MyObject, bool>> expression); } ``` The two strings s1 and s2 are the same, however when one of them is a constant then it fails to match the two expressions. I would expect it should work the same when the string is a constant? This is on a .NET Core 3.1 test project using Moq 4.14.5 and NUnit 3.12.
For now I can work around by simply assigning a local variable in the test from the constant and using that instead. Referencing a constant vs. a variable results in slightly different LINQ expression trees: in the former case, the string value gets embedded as a constant, while in the latter case, the variable gets captured in the form of a reference to an anonymous object's field. We've had a few similar issues in the past, and the approach followed most recently was that captured variables should be evaluated down to a constant value at the time when two LINQ expression trees get compared. If we applied this rule here, this present issue would be resolved. However, at present I am not sure whether this rule *should* apply in this case. The added complication here is that we have a setup LINQ expression tree that embeds another LINQ expression tree (the argument passed to `Method`)... and we need to know whether we're allowed to "touch" (here: partially reduce) embedded expression trees or whether we should treat them as constants and always leave them unmodified. This is probably related to the two principal ways how expression trees can reference other expression trees: [`Expression.Constant` and `Expression.Quote`](https://stackoverflow.com/q/3716492). I'm not positively certain that Moq makes this distinction correctly in all situations. TL;DR: I'll look into it, but this will take some thought and time.
2020-10-26T21:46:00Z
0.1
['Moq.Tests.Regressions.IssueReportsFixture+Issue1054.String_constant', 'Moq.Tests.Regressions.IssueReportsFixture+Issue1054.String_variable']
[]
devlooped/moq
devlooped__moq-1079
53231362ec8e8d70af4fc63de2eacfa97cd9b6a3
diff --git a/CHANGELOG.md b/CHANGELOG.md index f6cbe09c3..eb4b92aad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1 * New method overloads for `It.Is`, `It.IsIn`, and `It.IsNotIn` that compare values using a custom `IEqualityComparer<T>` (@weitzhandler, #1064) * New properties `ReturnValue` and `Exception` on `IInvocation` to query recorded invocations return values or exceptions (@MaStr11, #921, #1077) +#### Fixed + +* `SetupProperty` fails if property getter and setter are not both defined in mocked type (@stakx, #1017) + ## 4.14.7 (2020-10-14) diff --git a/src/Moq/ExpressionExtensions.cs b/src/Moq/ExpressionExtensions.cs index 276e282df..105187efa 100644 --- a/src/Moq/ExpressionExtensions.cs +++ b/src/Moq/ExpressionExtensions.cs @@ -244,9 +244,21 @@ void Split(Expression e, out Expression r /* remainder */, out InvocationShape p var parameter = Expression.Parameter(r.Type, r is ParameterExpression ope ? ope.Name : ParameterName); var indexer = indexExpression.Indexer; var arguments = indexExpression.Arguments; - var method = !assignment && indexer.CanRead(out var getter) ? getter - : indexer.CanWrite(out var setter) ? setter - : null; + MethodInfo method; + if (!assignment && indexer.CanRead(out var getter, out var getterIndexer)) + { + method = getter; + indexer = getterIndexer; + } + else if (indexer.CanWrite(out var setter, out var setterIndexer)) + { + method = setter; + indexer = setterIndexer; + } + else // This should be unreachable. + { + method = null; + } p = new InvocationShape( expression: Expression.Lambda( Expression.MakeIndex(parameter, indexer, arguments), @@ -281,9 +293,21 @@ void Split(Expression e, out Expression r /* remainder */, out InvocationShape p r = memberAccessExpression.Expression; var parameter = Expression.Parameter(r.Type, r is ParameterExpression ope ? ope.Name : ParameterName); var property = memberAccessExpression.GetReboundProperty(); - var method = !assignment && property.CanRead(out var getter) ? getter - : property.CanWrite(out var setter) ? setter - : null; + MethodInfo method; + if (!assignment && property.CanRead(out var getter, out var getterProperty)) + { + method = getter; + property = getterProperty; + } + else if (property.CanWrite(out var setter, out var setterProperty)) + { + method = setter; + property = setterProperty; + } + else // This should be unreachable. + { + method = null; + } p = new InvocationShape( expression: Expression.Lambda( Expression.MakeMemberAccess(parameter, property), diff --git a/src/Moq/Extensions.cs b/src/Moq/Extensions.cs index e9080614f..81d70294f 100644 --- a/src/Moq/Extensions.cs +++ b/src/Moq/Extensions.cs @@ -20,11 +20,17 @@ public static bool CanCreateInstance(this Type type) } public static bool CanRead(this PropertyInfo property, out MethodInfo getter) + { + return property.CanRead(out getter, out _); + } + + public static bool CanRead(this PropertyInfo property, out MethodInfo getter, out PropertyInfo getterProperty) { if (property.CanRead) { // The given `PropertyInfo` should be able to provide a getter: getter = property.GetGetMethod(nonPublic: true); + getterProperty = property; Debug.Assert(getter != null); return true; } @@ -47,20 +53,27 @@ public static bool CanRead(this PropertyInfo property, out MethodInfo getter) .GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Cast<PropertyInfo>() .First(p => p.GetSetMethod(nonPublic: true) == baseSetter); - return baseProperty.CanRead(out getter); + return baseProperty.CanRead(out getter, out getterProperty); } } getter = null; + getterProperty = null; return false; } public static bool CanWrite(this PropertyInfo property, out MethodInfo setter) + { + return property.CanWrite(out setter, out _); + } + + public static bool CanWrite(this PropertyInfo property, out MethodInfo setter, out PropertyInfo setterProperty) { if (property.CanWrite) { // The given `PropertyInfo` should be able to provide a setter: setter = property.GetSetMethod(nonPublic: true); + setterProperty = property; Debug.Assert(setter != null); return true; } @@ -83,11 +96,12 @@ public static bool CanWrite(this PropertyInfo property, out MethodInfo setter) .GetMember(property.Name, MemberTypes.Property, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Cast<PropertyInfo>() .First(p => p.GetGetMethod(nonPublic: true) == baseGetter); - return baseProperty.CanWrite(out setter); + return baseProperty.CanWrite(out setter, out setterProperty); } } setter = null; + setterProperty = null; return false; }
diff --git a/tests/Moq.Tests/StubExtensionsFixture.cs b/tests/Moq.Tests/StubExtensionsFixture.cs index 7e109a5b5..982dbc207 100644 --- a/tests/Moq.Tests/StubExtensionsFixture.cs +++ b/tests/Moq.Tests/StubExtensionsFixture.cs @@ -276,6 +276,15 @@ public void SetupProperty_retains_value_of_derived_read_write_property_that_over Assert.Equal("value", mock.Object.Property); } + [Fact] + public void SetupProperty_retains_value_of_derived_read_write_property_that_overrides_only_getter() + { + var mock = new Mock<OverridesOnlyGetter>(); + mock.SetupProperty(m => m.Property); + mock.Object.Property = "value"; + Assert.Equal("value", mock.Object.Property); + } + private object GetValue() { return new object(); } public interface IFoo @@ -326,5 +335,10 @@ public class OverridesOnlySetter : WithAutoProperty { public override object Property { set => base.Property = value; } } + + public class OverridesOnlyGetter : WithAutoProperty + { + public override object Property { get => base.Property; } + } } }
`SetupProperty` fails if property getter and setter are not both defined in mocked type This is basically #886 again, which was fixed for `SetupAllProperties` but not for `SetupProperty`. ### Reproduction code: ```csharp public class Base { public virtual object P { get; set; } } public class Derived : Base { public override object P { get => base.P; } } var mock = new Mock<Derived>(); mock.SetupProperty(m => m.P); ``` ### Actual behavior: The call to `SetupProperty` throws this exception: ``` System.ArgumentException: Expression must be writeable Parameter name: left at System.Linq.Expressions.Expression.RequiresCanWrite(Expression expression, String paramName) at System.Linq.Expressions.Expression.Assign(Expression left, Expression right) at System.Linq.Expressions.Expression.MakeBinary(ExpressionType binaryType, Expression left, Expression right, Boolean liftToNull, MethodInfo method, LambdaExpression conversion) at System.Linq.Expressions.Expression.MakeBinary(ExpressionType binaryType, Expression left, Expression right) at Moq.ExpressionExtensions.<Split>g__Split|5_0(Expression e, Expression& r, InvocationShape& p) in …\src\Moq\ExpressionExtensions.cs:line 195 at Moq.ExpressionExtensions.Split(LambdaExpression expression) in …\src\Moq\ExpressionExtensions.cs:line 148 at Moq.Mock.SetupRecursive[TSetup](Mock mock, LambdaExpression expression, Func`4 setupLast) in …\src\Moq\Mock.cs:line 593 at Moq.Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) in …\src\Moq\Mock.cs:line 529 at Moq.Mock.SetupSet(Mock mock, LambdaExpression expression, Condition condition) in …\src\Moq\Mock.cs:line 555 at Moq.Mock`1.SetupProperty[TProperty](Expression`1 property, TProperty initialValue) in …\src\Moq\Mock.Generic.cs:line 660 at Moq.Mock`1.SetupProperty[TProperty](Expression`1 property) in …\src\Moq\Mock.Generic.cs:line 616 ``` ### Expected behavior: The call to `SetupProperty` should succeed because `Derived.P` is both readable and writable. ### Moq version used: 4.14.1
null
2020-10-22T20:20:34Z
0.1
['Moq.Tests.StubExtensionsFixture.SetupProperty_retains_value_of_derived_read_write_property_that_overrides_only_getter']
[]
devlooped/moq
devlooped__moq-1077
531974cb32f71af38a48559fc912ab42ec0b80c2
diff --git a/CHANGELOG.md b/CHANGELOG.md index d50a10327..f6cbe09c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1 #### Added * New method overloads for `It.Is`, `It.IsIn`, and `It.IsNotIn` that compare values using a custom `IEqualityComparer<T>` (@weitzhandler, #1064) -* New property `IInvocation.ReturnValue` to query recorded invocations return values (@MaStr11, #921) +* New properties `ReturnValue` and `Exception` on `IInvocation` to query recorded invocations return values or exceptions (@MaStr11, #921, #1077) ## 4.14.7 (2020-10-14) diff --git a/src/Moq/IInvocation.cs b/src/Moq/IInvocation.cs index 8324365b6..cd9e6a21b 100644 --- a/src/Moq/IInvocation.cs +++ b/src/Moq/IInvocation.cs @@ -1,6 +1,7 @@ // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. +using System; using System.Collections.Generic; using System.Reflection; @@ -32,8 +33,13 @@ public interface IInvocation bool IsVerified { get; } /// <summary> - /// Gets the return value of the invocation. + /// The value being returned for a non-void method if no exception was thrown. /// </summary> object ReturnValue { get; } + + /// <summary> + /// Optional exception if the method invocation results in an exception being thrown. + /// </summary> + Exception Exception { get; } } } \ No newline at end of file diff --git a/src/Moq/Invocation.cs b/src/Moq/Invocation.cs index db641e315..cbb08e0ec 100644 --- a/src/Moq/Invocation.cs +++ b/src/Moq/Invocation.cs @@ -71,7 +71,9 @@ public MethodInfo MethodImplementation public object ReturnValue { - get => this.returnValue; + get => this.returnValue is InvocationExceptionWrapper + ? null + : this.returnValue; set { Debug.Assert(this.returnValue == null); @@ -79,6 +81,11 @@ public object ReturnValue } } + public Exception Exception + => this.returnValue is InvocationExceptionWrapper wrapper + ? wrapper.Exception + : null; + public bool IsVerified => this.verified; /// <summary> diff --git a/src/Moq/InvocationExceptionWrapper.cs b/src/Moq/InvocationExceptionWrapper.cs new file mode 100644 index 000000000..213c44e13 --- /dev/null +++ b/src/Moq/InvocationExceptionWrapper.cs @@ -0,0 +1,22 @@ +// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. +// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. + +using System; + +namespace Moq +{ + /// <summary> + /// Internal type to mark invocation results as "exception occurred during execution". The type just + /// wraps the Exception so a thrown exception can be distinguished from an <see cref="System.Exception"/> + /// return by the invocation. + /// </summary> + internal readonly struct InvocationExceptionWrapper + { + public InvocationExceptionWrapper(Exception exception) + { + Exception = exception; + } + + public Exception Exception { get; } + } +} diff --git a/src/Moq/ProxyFactories/CastleProxyFactory.cs b/src/Moq/ProxyFactories/CastleProxyFactory.cs index e99e9e57d..26d9775ec 100644 --- a/src/Moq/ProxyFactories/CastleProxyFactory.cs +++ b/src/Moq/ProxyFactories/CastleProxyFactory.cs @@ -101,6 +101,11 @@ public void Intercept(Castle.DynamicProxy.IInvocation underlying) this.interceptor.Intercept(invocation); underlying.ReturnValue = invocation.ReturnValue; } + catch (Exception ex) + { + invocation.ReturnValue = new InvocationExceptionWrapper(ex); + throw; + } finally { invocation.DetachFromUnderlying();
diff --git a/tests/Moq.Tests/InvocationsFixture.cs b/tests/Moq.Tests/InvocationsFixture.cs index d67258d30..8e4558a4f 100644 --- a/tests/Moq.Tests/InvocationsFixture.cs +++ b/tests/Moq.Tests/InvocationsFixture.cs @@ -2,6 +2,8 @@ // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; +using System.Collections; +using System.Collections.Generic; using System.Linq; using Xunit; @@ -45,11 +47,116 @@ public void MockInvocationsIncludeArguments() var invocation = mock.Invocations[0]; - var expectedArguments = new[] {obj}; + var expectedArguments = new[] { obj }; Assert.Equal(expectedArguments, invocation.Arguments); } + [Fact] + public void MockInvocationsIncludeReturnValue_NoSetup() + { + var mock = new Mock<IComparable>(); + + var obj = new object(); + + mock.Object.CompareTo(obj); + + var invocation = mock.Invocations[0]; + + Assert.Equal(0, invocation.ReturnValue); + Assert.Null(invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeReturnValue_Setup() + { + var mock = new Mock<IComparable>(); + var obj = new object(); + mock.Setup(c => c.CompareTo(obj)).Returns(42); + + mock.Object.CompareTo(obj); + + var invocation = mock.Invocations[0]; + + Assert.Equal(42, invocation.ReturnValue); + Assert.Null(invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeReturnValue_BaseCall() + { + var mock = new Mock<Random>(1) // seed: 1 + { + CallBase = true, + }; + + mock.Object.Next(); + + var invocation = mock.Invocations[0]; + + Assert.Equal(new Random(Seed: 1).Next(), invocation.ReturnValue); + Assert.Null(invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeReturnValue_ReturnsException() + { + var mock = new Mock<ICloneable>(); + var returnValue = new Exception(); + mock.Setup(c => c.Clone()).Returns(returnValue); + + mock.Object.Clone(); + + var invocation = mock.Invocations[0]; + + Assert.Equal(returnValue, invocation.ReturnValue); + Assert.Null(invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeException_Setup() + { + var mock = new Mock<IComparable>(); + var exception = new Exception("Message"); + mock.Setup(c => c.CompareTo(It.IsAny<object>())).Throws(exception); + + var thrown = Assert.Throws<Exception>(() => mock.Object.CompareTo(null)); + + Assert.Equal(exception.Message, thrown.Message); + + var invocation = mock.Invocations[0]; + Assert.Same(thrown, invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeException_BaseCall_Virtual() + { + var mock = new Mock<Test>() + { + CallBase = true, + }; + + var thrown = Assert.Throws<InvalidOperationException>(() => mock.Object.ThrowingVirtualMethod()); + + Assert.Equal("Message", thrown.Message); + + var invocation = mock.Invocations[0]; + Assert.Same(thrown, invocation.Exception); + } + + [Fact] + public void MockInvocationsIncludeException_MockException() + { + var mock = new Mock<ICloneable>(MockBehavior.Strict); + + var thrown = Assert.Throws<MockException>(() => mock.Object.Clone()); + + Assert.Equal(MockExceptionReasons.NoSetup, thrown.Reasons); + + var invocation = mock.Invocations[0]; + Assert.Same(thrown, invocation.Exception); + } + [Fact] public void MockInvocationsCanBeEnumerated() { @@ -269,5 +376,10 @@ public FlagInitiallySetToTrue() public virtual bool Flag { get; set; } } + + public class Test + { + public virtual int ThrowingVirtualMethod() => throw new InvalidOperationException("Message"); + } } }
`IInvocation` should expose `Exception` along with `ReturnValue` #921 which just got merged added a `ReturnValue` property to `IInvocation`, which allows user code to find out what got returned from a mocked invocation. The author of that PR (@MaStr11) suggested that an `Exception` property also be added for similar reasons; if an invocation throws, user code might want to find out what it threw. I think we ought to add `Exception Exception { get; }` to `IInvocation` for completeness. Incidentally, we'd then reach [parity with Moq 5](https://github.com/moq/moq/blob/a76c3cea64a4d9be4934d048c19d9c041ef487d5/src/Stunts/Stunts/IMethodReturn.cs#L16-L20) in this particular regard. #### Some implementation notes * I [mentioned in that PR](https://github.com/moq/moq4/pull/921#issuecomment-706759795) that the addition of an `Exception` property wouldn't make `Invocation` heavier (by adding a corresponding field). The existing field `Invocation.returnValue` could serve double duty (holding either a return value, or an exception). We'd need to ensure that methods returning an exception as a regular return value should not report that via the new `Exception` property. * Also [mentioned in the PR] is the likely Moq [code location](https://github.com/moq/moq4/blob/947c6a0aa1bbf265b5555ad0a84beb5bfc53b4e2/src/Moq/ProxyFactories/CastleProxyFactory.cs#L99-L107) where `Exception` would be set.
> P.S. @MaStr11: In case you were wondering where we stand regarding thrown exceptions, I didn't forget about it, but thought it would be cleaner to do that in a separate PR, to keep this one as straightforward as it was. > If you would like to submit a PR that adds an Exception Exception { get; } property to IInvocation (as you described in (1) above), please feel free to do so, and I'll merge that, too. > It shouldn't be too hard to do, setting the Invocation.Exception property would likely happen in a catch block being added there. (Ideally, we would make this addition without adding a new field to Invocation—to keep it as lightweight as possible–but that's not essential, it'd be more of an optimization. The existing returnValue field could serve double duty since an invocation cannot both return a value and throw. We'd only have to make sure that returned Exception objects won't leak out through the Exception property; this could be done by wrapping thrown exceptions in an internal type that only we can check for.) From https://github.com/moq/moq4/pull/921#issuecomment-706759795 @stakx I will give it a try.
2020-10-14T16:22:53Z
0.1
['Moq.Tests.InvocationsFixture.MockInvocationsIncludeReturnValue_NoSetup', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeReturnValue_Setup', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeReturnValue_BaseCall', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeReturnValue_ReturnsException', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeException_Setup', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeException_BaseCall_Virtual', 'Moq.Tests.InvocationsFixture.MockInvocationsIncludeException_MockException']
[]
devlooped/moq
devlooped__moq-1076
5b8fbc477a67fc36415e3114cb4a4a4492a91e4c
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a29c291e..e5124dc4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1 * Setup not triggered due to VB.NET transparently inserting superfluous type conversions into a setup expression (@InteXX, #1067) * Nested mocks created by `Mock.Of<T>()` no longer have their properties stubbed since version 4.14.0 (@vruss, @1071) * `Verify` fails for recursive setups not explicitly marked as `Verifiable` (@killergege, #1073) +* `Mock.Of<>` fails for COM interop types that are annotated with a `[CompilerGenerated]` custom attribute (@killergege, #1072) ## 4.14.6 (2020-09-30) diff --git a/src/Moq/Linq/MockSetupsBuilder.cs b/src/Moq/Linq/MockSetupsBuilder.cs index bf02c5bf3..328c5010f 100644 --- a/src/Moq/Linq/MockSetupsBuilder.cs +++ b/src/Moq/Linq/MockSetupsBuilder.cs @@ -151,7 +151,7 @@ private sealed class ReplaceMockObjectWithParameter : ExpressionVisitor protected override Expression VisitMember(MemberExpression node) { - if (node.Expression is ParameterExpression pe && pe.Type.IsDefined(typeof(CompilerGeneratedAttribute))) + if (node.Expression is ParameterExpression pe && pe.Type.IsDefined(typeof(CompilerGeneratedAttribute)) && pe.Type.Name.Contains("f__AnonymousType")) { // In LINQ query expressions with more than one `from` clause such as: //
diff --git a/tests/Moq.Tests/ComCompatibilityFixture.cs b/tests/Moq.Tests/ComCompatibilityFixture.cs index a6f07a6b7..43234ccc0 100644 --- a/tests/Moq.Tests/ComCompatibilityFixture.cs +++ b/tests/Moq.Tests/ComCompatibilityFixture.cs @@ -1,6 +1,9 @@ // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + using Moq.Tests.ComTypes; using Xunit; @@ -100,5 +103,50 @@ public void COM_interop_type_indexer_setter_is_recognized_as_such() var setter = indexer.GetSetMethod(true); Assert.True(setter.IsSetAccessor() && setter.IsIndexerAccessor()); } + + [Fact] + public void Can_create_mock_of_Excel_Workbook_using_Mock_Of_1() + { + _ = Mock.Of<GoodWorkbook>(workbook => workbook.FullName == ""); + } + + [Fact] + public void Can_create_mock_of_Excel_Workbook_using_Mock_Of_2() + { + _ = Mock.Of<BadWorkbook>(workbook => workbook.FullName == ""); + } + + // The following two interfaces are simplified versions of the `_Workbook` interface from + // two different versions of the `Microsoft.Office.Excel.Interop` interop assemblies. + // Note how they differ only in one `[CompilerGenerated]` attribute. + + [ComImport] + [Guid("000208DA-0000-0000-C000-000000000046")] + public interface GoodWorkbook + { + [DispId(289)] + string FullName + { + [DispId(289)] + [LCIDConversion(0)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + } + + [ComImport] + [CompilerGenerated] + [Guid("000208DA-0000-0000-C000-000000000046")] + public interface BadWorkbook + { + [DispId(289)] + string FullName + { + [DispId(289)] + [LCIDConversion(0)] + [return: MarshalAs(UnmanagedType.BStr)] + get; + } + } } }
Mock.Of of Excel interop classes fails to initialize I have a project that has a lot of tests on Excel interop classes. Those were working fine with my current test project (net452, Moq 4.8, Microsoft.Office.Interop.Excel v12.0.4518.1014, NUnit v3.12...) But after upgrading to Moq 4.14 & Microsoft.Office.Interop.Excel v15.0.4795.1000, all the Mock.Of on interop classes fail to initialize. I had other setup issues following interop upgrade (because they stated to use `dynamic` in some places, instead of `object`) but it seems that this is a different problem. ``` [Test] public void Test_Works() { var worksheet = new Mock<Worksheet>(); var parent = new Mock<Workbook>(); parent.Setup(x => x.FullName).Returns(string.Empty); worksheet.Setup(x => x.Parent).Returns(parent.Object); } [Test] public void Test_Fails() { var worksheet = new Mock<Worksheet>(); var v = Mock.Of<Workbook>(x => x.FullName == string.Empty); worksheet.Setup(x => x.Parent).Returns(v); } ``` The error is different based on the Moq version, but they all fail : Moq v4.13.1 ``` Message: System.ArgumentException : Method 'Moq.Language.Flow.IReturnsResult`1[Microsoft.Office.Interop.Excel.Workbook] Returns(System.String)' declared on type 'Moq.Language.IReturns`2[Microsoft.Office.Interop.Excel.Workbook,System.String]' cannot be called with instance of type 'Moq.Mock`1[System.String]' Stack Trace: Expression.ValidateCallInstanceType(Type instanceType, MethodInfo method) Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method) Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments) MockSetupsBuilder.ConvertToSetup(Expression targetObject, Expression left, Expression right) MockSetupsBuilder.ConvertToSetupProperty(Expression targetObject, Expression left, Expression right) MockSetupsBuilder.ConvertToSetup(Expression left, Expression right) MockSetupsBuilder.VisitBinary(BinaryExpression node) BinaryExpression.Accept(ExpressionVisitor visitor) ExpressionVisitor.Visit(Expression node) ExpressionVisitor.VisitLambda[T](Expression`1 node) Expression`1.Accept(ExpressionVisitor visitor) ExpressionVisitor.Visit(Expression node) ExpressionVisitor.VisitUnary(UnaryExpression node) MockSetupsBuilder.VisitUnary(UnaryExpression node) UnaryExpression.Accept(ExpressionVisitor visitor) ExpressionVisitor.Visit(Expression node) ExpressionVisitor.VisitArguments(IArgumentProvider nodes) ExpressionVisitor.VisitMethodCall(MethodCallExpression node) MockSetupsBuilder.VisitMethodCall(MethodCallExpression node) MethodCallExpression.Accept(ExpressionVisitor visitor) ExpressionVisitor.Visit(Expression node) MockQueryable`1.Execute[TResult](Expression expression) Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate) Mock.Of[T](Expression`1 predicate, MockBehavior behavior) Mock.Of[T](Expression`1 predicate) UnitTest1.Test_Fails() line 22 ``` Moq v4.14.6 ``` Message: System.ArgumentException : Object instance was not created by Moq. Parameter name: mocked Stack Trace: Mock.Get[T](T mocked) lambda_method(Closure , Workbook ) Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate) lambda_method(Closure ) EnumerableExecutor`1.Execute() IQueryProvider.Execute[S](Expression expression) Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate) lambda_method(Closure ) MockQueryable`1.Execute[TResult](Expression expression) Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate) Mock.Of[T](Expression`1 predicate, MockBehavior behavior) Mock.Of[T](Expression`1 predicate) UnitTest1.Test_Fails() line 22 ``` Is it expected? Do you have a workaround ? Replacing all the `Mock.Of<>()` by `new Mock<>() + setup` is a lot of work and adds a lot of "useless" rows...
> But after upgrading to Moq 4.14 & Microsoft.Office.Interop.Excel v15.0.4795.1000 @killergege, ~~can you tell which of the two updates causes the issue?~~ That must be due to the interop update, because I can reproduce the problem you're seeing with all versions of Moq, going all the way back to 4.0.0. I cannot currently offer a workaround other than the one you're already aware of&mdash;using `new Mock<T>` instead&mdash;but let's keep that around as something we should fix. Unfortunately I don't have a copy of the Excel v12 type library available. Could you possibly provide an assembly containing the above two tests, compiled against the old versions where everything passed? If you could ensure that the COM interfaces get embedded in the assembly, that would allow me to investigate what changes in the type libraries make Moq fail. We are using the nuget package to get the interop objects : https://www.nuget.org/packages/microsoft.office.interop.excel/ Our build server don't have Excel so I guess this is enough. If not I'll try to get you what you asked but in my corporate network this is not easy to send files outside :). Ah, excellent! I wasn't aware of that NuGet package. Thank you for pointing me towards it... that should indeed be sufficient. @killergege, I've compared the Excel COM interop libraries. They appear to differ in (among other things) the presence or absence of `[CompilerGenerated]` custom attributes on the `Workbook` and related types, and it appears to be the presence of that attribute that causes stuff inside Moq to go wrong: Moq queries for this attribute in some places to recognize captured variables and anonymous types (those can show up in LINQ queries that use query comprehension syntax). In the current version, Moq erroneously enters into [this "then" clause](https://github.com/moq/moq4/blob/5b8fbc477a67fc36415e3114cb4a4a4492a91e4c/src/Moq/Linq/MockSetupsBuilder.cs#L155) when it shouldn't... and that's what makes your code fail. Not yet sure how to fix this properly, but at least a fix is possible. A very crude fix would consist of adding an `&& !pe.Type.IsImport` check in the line of code referenced above... but that would be hardly pretty. I'll try to come up with something better.
2020-10-13T21:40:02Z
0.1
['Moq.Tests.ComCompatibilityFixture.Can_create_mock_of_Excel_Workbook_using_Mock_Of_1', 'Moq.Tests.ComCompatibilityFixture.Can_create_mock_of_Excel_Workbook_using_Mock_Of_2']
[]
ThreeMammals/Ocelot
threemammals__ocelot-1790
d3a623ee7ae6de00b939fd847cc7cef6d4c89276
diff --git a/.circleci/config.yml b/.circleci/config.yml index 4a5f1d936..09178e49c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,13 +4,13 @@ orbs: jobs: build: docker: - - image: mijitt0m/ocelot-build:0.0.9 + - image: ocelot2/circleci-build:8.21.0 steps: - checkout - run: dotnet tool restore && dotnet cake release: docker: - - image: mijitt0m/ocelot-build:0.0.9 + - image: ocelot2/circleci-build:8.21.0 steps: - checkout - run: dotnet tool restore && dotnet cake --target=Release @@ -19,7 +19,7 @@ workflows: main: jobs: - queue/block_workflow: - time: "20" + time: '20' only-on-branch: main - release: requires: @@ -38,6 +38,6 @@ workflows: - build: filters: branches: - ignore: + ignore: - main - develop diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index ce3369c2e..d9c539fb0 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "cake.tool": { - "version": "3.0.0", + "version": "4.0.0", "commands": [ "dotnet-cake" ] @@ -15,4 +15,4 @@ ] } } -} \ No newline at end of file +} diff --git a/.editorconfig b/.editorconfig index 6aa3d30f4..e4e769b52 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,7 +4,12 @@ root = true end_of_line = lf insert_final_newline = true -[*.cs] +[*.cs] end_of_line = lf indent_style = space indent_size = 4 + +# XML files +[*.xml] +indent_style = space +indent_size = 2 diff --git a/.gitignore b/.gitignore index 220172830..1c30928ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,21 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files +*.rsuser *.suo *.user *.userosscache *.sln.docstates -*.DS_Store + # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# Mono auto generated files +mono_crash.* + # Build results [Dd]ebug/ [Dd]ebugPublic/ @@ -17,44 +23,62 @@ [Rr]eleases/ x64/ x86/ -build/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ -results/ +[Ll]og/ +[Ll]ogs/ -# Visual Studio 2015 cache/options directory +# Visual Studio 2015/2017 cache/options directory .vs/ -.vscode/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ -site/wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* -# NUNIT +# NUnit *.VisualState.xml TestResult.xml +nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c -# DNX +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core project.lock.json +project.fragment.lock.json artifacts/ +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio *_i.c *_p.c -*_i.h +*_h.h *.ilk *.meta *.obj +*.iobj *.pch *.pdb +*.ipdb *.pgc *.pgd *.rsp @@ -64,7 +88,9 @@ artifacts/ *.tlh *.tmp *.tmp_proj +*_wpftmp.csproj *.log +*.tlog *.vspscc *.vssscc .builds @@ -83,6 +109,8 @@ ipch/ *.opensdf *.sdf *.cachefile +*.VC.db +*.VC.VC.opendb # Visual Studio profiler *.psess @@ -90,6 +118,9 @@ ipch/ *.vspx *.sap +# Visual Studio Trace Files +*.e2e + # TFS 2012 Local Workspace $tf/ @@ -101,15 +132,25 @@ _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user -# JustCode is a .NET coding add-in -.JustCode - # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + # NCrunch _NCrunch_* .*crunch*.local.xml @@ -141,19 +182,29 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings +# Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + # NuGet Packages *.nupkg +# NuGet Symbol Packages +*.snupkg # The packages folder can be ignored because of Package Restore -**/packages/* +**/[Pp]ackages/* # except build/, which is used as an MSBuild target. -!**/packages/build/ +!**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets # Microsoft Azure Build Output csx/ @@ -163,18 +214,20 @@ csx/ ecf/ rcf/ -# Microsoft Azure ApplicationInsights config file -ApplicationInsights.config - -# Windows Store app package directory +# Windows Store app package directories and files AppPackages/ BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache -!*.[Cc]ache/ +!?*.[Cc]ache/ # Others ClientBin/ @@ -182,12 +235,19 @@ ClientBin/ *~ *.dbmdl *.dbproj.schemaview +*.jfm *.pfx -!mycert.pfx *.publishsettings -node_modules/ orleans.codegen.cs +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + # RIA/Silverlight projects Generated_Code/ @@ -198,15 +258,22 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak # SQL Server files *.mdf *.ldf +*.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ @@ -216,6 +283,7 @@ FakesAssemblies/ # Node.js Tools for Visual Studio .ntvs_analysis.dat +node_modules/ # Visual Studio 6 build log *.plg @@ -223,6 +291,20 @@ FakesAssemblies/ # Visual Studio 6 workspace options file *.opt +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts @@ -233,25 +315,107 @@ _Pvt_Extensions # Paket dependency manager .paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +# Visual Studio Test Results +# Quick Facts: https://file.org/extension/trx#visualstudiotestresults +# Running automated tests from the command line: https://learn.microsoft.com/en-us/previous-versions/ms182486(v=vs.140) +# Run unit tests with Test Explorer: https://learn.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer +*.trx + +# OCELOT # FAKE - F# Make .fake/ !tools/packages.config tools/ -# MacOS -.DS_Store - # Ocelot acceptance test config test/Ocelot.AcceptanceTests/ocelot.json -# Read the docstates +# Read the Docs +# https://ocelot.readthedocs.io _build/ _static/ _templates/ - -# JetBrains Rider -.idea/ - -# Test Results -*.trx diff --git a/LICENSE.md b/LICENSE.md index d47ecafdf..f81511d45 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,8 +1,8 @@ The MIT License (MIT) -Copyright (c) 2016 Tom Pallister +Copyright (c) 2023 Tom Pallister, Ocelot Core team at ThreeMammals, and GitHub Ocelot community. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Ocelot.sln b/Ocelot.sln index c4abd99a9..1215130de 100644 --- a/Ocelot.sln +++ b/Ocelot.sln @@ -1,7 +1,7 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 -VisualStudioVersion = 17.6.33723.286 +VisualStudioVersion = 17.8.34309.116 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5CFB79B7-C9DC-45A4-9A75-625D92471702}" EndProject diff --git a/README.md b/README.md index 02385e021..c4d879464 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,8 @@ A quick list of Ocelot's capabilities, for more information see the [Documentati ## Install -Ocelot is designed to work with ASP.NET Core and it targets `net7.0` framework. +Ocelot is designed to work with ASP.NET Core and it targets `net6.0`, `net7.0` and `net8.0` frameworks. [^4] + Install [Ocelot package](https://www.nuget.org/packages/Ocelot) and its dependencies using NuGet Package Manager: ```powershell Install-Package Ocelot @@ -78,7 +79,7 @@ We can also give advice on the easiest way to do things :octocat: Finally, we mark all existing issues as [![label: help wanted][~helpwanted]](https://github.com/ThreeMammals/Ocelot/labels/help%20wanted) [![label: small effort][~smalleffort]](https://github.com/ThreeMammals/Ocelot/labels/small%20effort) [![label: medium effort][~mediumeffort]](https://github.com/ThreeMammals/Ocelot/labels/medium%20effort) -[![label: large effort][~largeeffort]](https://github.com/ThreeMammals/Ocelot/labels/large%20effort) [^4]. +[![label: large effort][~largeeffort]](https://github.com/ThreeMammals/Ocelot/labels/large%20effort). [^5] <br/>If you want to contribute for the first time, we suggest looking at a [![label: help wanted][~helpwanted]](https://github.com/ThreeMammals/Ocelot/labels/help%20wanted) [![label: small effort][~smalleffort]](https://github.com/ThreeMammals/Ocelot/labels/small%20effort) [![label: good first issue][~goodfirstissue]](https://github.com/ThreeMammals/Ocelot/labels/good%20first%20issue) :octocat: @@ -93,4 +94,5 @@ Finally, we mark all existing issues as [![label: help wanted][~helpwanted]](htt [^1]: Ocelot doesn’t directly support [GraphQL](https://graphql.org/). Developers can easily integrate the [GraphQL for .NET](/graphql-dotnet/graphql-dotnet) library. [^2]: Ocelot does support [Consul](https://www.consul.io/), [Netflix Eureka](https://www.nuget.org/packages/Steeltoe.Discovery.Eureka), [Service Fabric](https://azure.microsoft.com/en-us/products/service-fabric/) service discovery providers, and special modes like [Dynamic Routing](/ThreeMammals/Ocelot/blob/main/docs/features/servicediscovery.rst#dynamic-routing) and [Custom Providers](/ThreeMammals/Ocelot/blob/main/docs/features/servicediscovery.rst#custom-providers). [^3]: Retry policies only via [Polly](/App-vNext/Polly) library. -[^4]: See all [labels](https://github.com/ThreeMammals/Ocelot/issues/labels) of the repository. +[^4]: Starting with [v21.0](https://github.com/ThreeMammals/Ocelot/releases/tag/21.0.0), the solution's code base supports [Multitargeting](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-multitargeting-overview) as SDK-style projects. It should be easier for teams to move between (migrate to) .NET 6, 7 and 8 frameworks. Also, new features will be available for all .NET SDKs which we support via multitargeting. Find out more here: [Target frameworks in SDK-style projects](https://learn.microsoft.com/en-us/dotnet/standard/frameworks) +[^5]: See all [labels](https://github.com/ThreeMammals/Ocelot/issues/labels) of the repository. diff --git a/ReleaseNotes.md b/ReleaseNotes.md index af4e302ad..1193d5db1 100644 --- a/ReleaseNotes.md +++ b/ReleaseNotes.md @@ -1,2 +1,17 @@ -## Documentation release {0} for [Polish Apple](https://www.google.com/search?q=Polish+Apple), v{1} -Special thanks to @ggnaegi! +## Upgrade to .NET 8 (version {0}) aka [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) release +> Read article: [Announcing .NET 8](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/) by Gaurav Seth, on November 14th, 2023 + +### About +We are pleased to announce to you that we can now offer the support of [.NET 8](https://dotnet.microsoft.com/en-us/download). +But that is not all, in this release, we are adopting support of several versions of the .NET framework through [multitargeting](https://learn.microsoft.com/en-us/dotnet/standard/frameworks). +The Ocelot distribution is now compatible with .NET **6**, **7** and **8**. :tada: + +In the future, we will try to ensure the support of the [.NET SDKs](https://dotnet.microsoft.com/en-us/download/dotnet) that are still actively maintained by the .NET team and community. +Current .NET versions in support are the following: [6, 7, 8](https://dotnet.microsoft.com/en-us/download/dotnet). + +### Technical info +As an ASP.NET Core app, now Ocelot targets `net6.0`, `net7.0` and `net8.0` frameworks. + +Starting with **v{0}**, the solution's code base supports [Multitargeting](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-multitargeting-overview) as SDK-style projects. +It should be easier for teams to move between (migrate to) .NET 6, 7 and 8 frameworks. Also, new features will be available for all .NET SDKs which we support via multitargeting. +Find out more here: [Target frameworks in SDK-style projects](https://learn.microsoft.com/en-us/dotnet/standard/frameworks) diff --git a/build.cake b/build.cake index ad510b0ac..75f30a755 100644 --- a/build.cake +++ b/build.cake @@ -2,7 +2,7 @@ #tool "dotnet:?package=coveralls.net&version=4.0.1" #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 -#tool "nuget:?package=ReportGenerator&version=5.1.19" +#tool "nuget:?package=ReportGenerator&version=5.2.0" #addin Cake.Coveralls&version=1.1.0 #r "Spectre.Console" @@ -42,8 +42,9 @@ var benchmarkTestAssemblies = @"./test/Ocelot.Benchmarks"; // packaging var packagesDir = artifactsDir + Directory("Packages"); -var releaseNotesFile = packagesDir + File("ReleaseNotes.md"); var artifactsFile = packagesDir + File("artifacts.txt"); +var releaseNotesFile = packagesDir + File("ReleaseNotes.md"); +var releaseNotes = new List<string>(); // stable releases var tagsUrl = "https://api.github.com/repos/ThreeMammals/ocelot/releases/tags/"; @@ -85,8 +86,8 @@ Task("Release") .IsDependentOn("Build") .IsDependentOn("CreateReleaseNotes") .IsDependentOn("CreateArtifacts") - .IsDependentOn("PublishGitHubRelease"); - // .IsDependentOn("PublishToNuget"); + .IsDependentOn("PublishGitHubRelease") + .IsDependentOn("PublishToNuget"); Task("Compile") .IsDependentOn("Clean") @@ -135,7 +136,7 @@ Task("Version") Task("CreateReleaseNotes") .IsDependentOn("Version") .Does(() => - { + { Information($"Generating release notes at {releaseNotesFile}"); // local helper function @@ -158,7 +159,7 @@ Task("CreateReleaseNotes") var releaseVersion = versioning.NuGetVersion; // Read main header from Git file, substitute version in header, and add content further... var releaseHeader = string.Format(System.IO.File.ReadAllText("./ReleaseNotes.md"), releaseVersion, lastRelease); - var releaseNotes = new List<string> { releaseHeader }; + releaseNotes = new List<string> { releaseHeader }; var shortlogSummary = GitHelper($"shortlog --no-merges --numbered --summary {lastRelease}..HEAD"); var re = new Regex(@"^[\s\t]*(?'commits'\d+)[\s\t]+(?'author'.*)$"); @@ -296,9 +297,9 @@ Task("CreateReleaseNotes") } } } // END of Top 3 - //releaseNotes.Add("### Honoring :medal_sports: aka Top Contributors :clap:"); - //releaseNotes.AddRange(topContributors); - //releaseNotes.Add(""); + releaseNotes.Add("### Honoring :medal_sports: aka Top Contributors :clap:"); + releaseNotes.AddRange(topContributors); + releaseNotes.Add(""); releaseNotes.Add("### Starring :star: aka Release Influencers :bowtie:"); releaseNotes.AddRange(starring); releaseNotes.Add(""); @@ -306,17 +307,26 @@ Task("CreateReleaseNotes") var commitsHistory = GitHelper($"log --no-merges --date=format:\"%A, %B %d at %H:%M\" --pretty=format:\"<sub>%h by **%aN** on %ad &rarr;</sub>%n%s\" {lastRelease}..HEAD"); releaseNotes.AddRange(commitsHistory); - EnsureDirectoryExists(packagesDir); - System.IO.File.WriteAllLines(releaseNotesFile, releaseNotes); + WriteReleaseNotes(); + }); + +private void WriteReleaseNotes() +{ + Information($"RUN {nameof(WriteReleaseNotes)} ..."); - if (string.IsNullOrEmpty(System.IO.File.ReadAllText(releaseNotesFile))) - { - System.IO.File.WriteAllText(releaseNotesFile, "No commits since last release"); - } + EnsureDirectoryExists(packagesDir); + System.IO.File.WriteAllLines(releaseNotesFile, releaseNotes); + + var content = System.IO.File.ReadAllText(releaseNotesFile); + if (string.IsNullOrEmpty(content)) + { + System.IO.File.WriteAllText(releaseNotesFile, "No commits since last release"); + } + + Information($"Release notes are >>>\n{content}<<<"); + Information($"EXITED {nameof(WriteReleaseNotes)}"); +} - Information("Release notes are >>>" + Environment.NewLine + System.IO.File.ReadAllText(releaseNotesFile) + "<<<"); - }); - Task("RunUnitTests") .IsDependentOn("Compile") .Does(() => @@ -407,25 +417,24 @@ Task("CreateArtifacts") .IsDependentOn("Compile") .Does(() => { - EnsureDirectoryExists(packagesDir); - + WriteReleaseNotes(); System.IO.File.AppendAllLines(artifactsFile, new[] { "ReleaseNotes.md" }); - CopyFiles("./ReleaseNotes.md", packagesDir); - - // CopyFiles("./src/**/Release/Ocelot.*.nupkg", packagesDir); - // var projectFiles = GetFiles("./src/**/Release/Ocelot.*.nupkg"); - // foreach(var projectFile in projectFiles) - // { - // System.IO.File.AppendAllLines( - // artifactsFile, - // new[] { projectFile.GetFilename().FullPath } - // ); - // } + + CopyFiles("./src/**/Release/Ocelot.*.nupkg", packagesDir); + var projectFiles = GetFiles("./src/**/Release/Ocelot.*.nupkg"); + foreach(var projectFile in projectFiles) + { + System.IO.File.AppendAllLines( + artifactsFile, + new[] { projectFile.GetFilename().FullPath } + ); + } var artifacts = System.IO.File.ReadAllLines(artifactsFile) .Distinct(); - - foreach(var artifact in artifacts) + + Information($"Listing all {nameof(artifacts)}..."); + foreach (var artifact in artifacts) { var codePackage = packagesDir + File(artifact); if (FileExists(codePackage)) diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 691339490..49b877c10 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine +FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib git openssh-client @@ -6,4 +6,11 @@ RUN curl -L --output ./dotnet-install.sh https://dot.net/v1/dotnet-install.sh RUN chmod u+x ./dotnet-install.sh +# Install .NET 8 SDK (already included in the base image, but listed for consistency) +RUN ./dotnet-install.sh -c 8.0 -i /usr/share/dotnet + +# Install .NET 7 SDK +RUN ./dotnet-install.sh -c 7.0 -i /usr/share/dotnet + +# Install .NET 6 SDK RUN ./dotnet-install.sh -c 6.0 -i /usr/share/dotnet diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build index 5498c6106..51dff57ff 100644 --- a/docker/Dockerfile.build +++ b/docker/Dockerfile.build @@ -1,7 +1,8 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.9 + +FROM ocelot2/circleci-build:8.21.0 ARG OCELOT_COVERALLS_TOKEN @@ -13,4 +14,4 @@ COPY ./. . RUN dotnet tool restore -RUN dotnet cake \ No newline at end of file +RUN dotnet cake diff --git a/docker/Dockerfile.release b/docker/Dockerfile.release index e2659c035..90e2d6ee1 100644 --- a/docker/Dockerfile.release +++ b/docker/Dockerfile.release @@ -1,7 +1,8 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.9 + +FROM ocelot2/circleci-build:8.21.0 ARG OCELOT_COVERALLS_TOKEN ARG OCELOT_NUTGET_API_KEY @@ -17,4 +18,4 @@ COPY ./. . RUN dotnet tool restore -RUN dotnet cake \ No newline at end of file +RUN dotnet cake diff --git a/docker/README.md b/docker/README.md index 3eb46aa42..dcecc224d 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,3 +1,3 @@ # docker build -This folder contains the dockerfile and script to create the ocelot build container. \ No newline at end of file +This folder contains the `Dockerfile.*` and `build.sh` script to create the Ocelot build image & container. diff --git a/docker/build.sh b/docker/build.sh index bf2cee9b5..15d1325ad 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -1,7 +1,11 @@ -# this script build the ocelot docker file -version=0.0.9 -docker build --platform linux/amd64 -t mijitt0m/ocelot-build -f Dockerfile.base . +# This script builds the Ocelot Docker file + +# {DotNetSdkVer}.{OcelotVer} -> {.NET8}.{21.0} -> 8.21.0 +version=8.21.0 +docker build --platform linux/amd64 -t ocelot2/circleci-build -f Dockerfile.base . + echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin -docker tag mijitt0m/ocelot-build mijitt0m/ocelot-build:$version -docker push mijitt0m/ocelot-build:latest -docker push mijitt0m/ocelot-build:$version \ No newline at end of file + +docker tag ocelot2/circleci-build ocelot2/circleci-build:$version +docker push ocelot2/circleci-build:latest +docker push ocelot2/circleci-build:$version diff --git a/docs/building/building.rst b/docs/building/building.rst index ec794e296..5873350b8 100644 --- a/docs/building/building.rst +++ b/docs/building/building.rst @@ -10,4 +10,4 @@ Building * There is a `Makefile <https://github.com/ThreeMammals/Ocelot/blob/main/docs/Makefile>`_ to make it easier to call the various targets in `build.cake <https://github.com/ThreeMammals/Ocelot/blob/main/build.cake>`_. The scripts are called with **.sh** but can be easily changed to **.ps1** if you are using Windows. -* Alternatively you can build the project in VS2022 with the latest `.NET 7.0 <https://dotnet.microsoft.com/en-us/download/dotnet/7.0>`_ SDK. +* Alternatively you can build the project in VS2022 with the latest `.NET 8.0 <https://dotnet.microsoft.com/en-us/download/dotnet/8.0>`_ SDK. diff --git a/docs/building/releaseprocess.rst b/docs/building/releaseprocess.rst index ada142c39..ba7cff45a 100644 --- a/docs/building/releaseprocess.rst +++ b/docs/building/releaseprocess.rst @@ -10,7 +10,7 @@ Ocelot uses the following process to accept work into the NuGet packages. 1. User creates an issue or picks up an `existing issue <https://github.com/ThreeMammals/Ocelot/issues>`_ in GitHub. An issue can be created by converting `discussion <https://github.com/ThreeMammals/Ocelot/discussions>`_ topics if necessary and agreed upon. -2. User creates a fork and branches from this (unless a member of core team, they can just create a branch on the head repo) e.g. ``feature/xxx``, ``bug/xxx`` etc. +2. User creates `a fork <https://docs.github.com/en/get-started/quickstart/fork-a-repo>`_ and branches from this (unless a member of core team, they can just create a branch on the head repo) e.g. ``feature/xxx``, ``bug/xxx`` etc. It doesn't really matter what the "xxx" is. It might make sense to use the issue number and maybe a short description. 3. When the contributor is happy with their work they can create a pull request against **develop** in GitHub with their changes. diff --git a/docs/conf.py b/docs/conf.py index c8dbe77bd..8bd28ecbf 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -8,8 +8,8 @@ project = 'Ocelot' copyright = ' 2023 ThreeMammals Ocelot team' -author = 'Tom Pallister, Ocelot Core team at ThreeMammals and Ocelot GitHub community' -release = '20.0.0' +author = 'Tom Pallister, Ocelot Core team at ThreeMammals' +release = '21.0' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration @@ -19,8 +19,6 @@ templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - - # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output diff --git a/docs/features/configuration.rst b/docs/features/configuration.rst index feec24721..589c4a0b0 100644 --- a/docs/features/configuration.rst +++ b/docs/features/configuration.rst @@ -94,7 +94,7 @@ to you: Ocelot will now use the environment specific configuration and fall back to **ocelot.json** if there isn't one. You also need to set the corresponding environment variable which is ``ASPNETCORE_ENVIRONMENT``. -More info on this can be found in the ASP.NET Core docs: `Use multiple environments in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-7.0>`_. +More info on this can be found in the ASP.NET Core docs: `Use multiple environments in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments>`_. Merging Configuration Files --------------------------- diff --git a/docs/features/dependencyinjection.rst b/docs/features/dependencyinjection.rst index 711340efc..9dbd9b2be 100644 --- a/docs/features/dependencyinjection.rst +++ b/docs/features/dependencyinjection.rst @@ -108,7 +108,7 @@ It gives you full control on design and buiding of Ocelot pipeline, but be caref Warning! Most of services from minimal part of the pipeline should be reused, but only a few of services could be removed. Warning!! The method above is called after adding required services of ASP.NET MVC pipeline building by -`AddMvcCore <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoreservicecollectionextensions.addmvccore?view=aspnetcore-7.0>`_ method +`AddMvcCore <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoreservicecollectionextensions.addmvccore>`_ method over the ``Services`` property in upper calling context. These services are absolute minimum core services for ASP.NET MVC pipeline. They must be added to DI container always, and they are added implicitly before calling of the method by caller in upper context. So, ``AddMvcCore`` creates an ``IMvcCoreBuilder`` object with its assignment to the ``MvcCoreBuilder`` property. @@ -124,13 +124,13 @@ The Problem ^^^^^^^^^^^ The default `AddOcelot <#the-addocelot-method>`_ method adds -`Newtonsoft JSON <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.newtonsoftjsonmvccorebuilderextensions.addnewtonsoftjson?view=aspnetcore-7.0>`_ services +`Newtonsoft JSON <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.newtonsoftjsonmvccorebuilderextensions.addnewtonsoftjson>`_ services by the ``AddNewtonsoftJson`` extension method in default builder (the `AddDefaultAspNetServices <#the-adddefaultaspnetservices-method>`_ method). The ``AddNewtonsoftJson`` method calling was introduced in old .NET and Ocelot releases which was necessary when Microsoft did not launch the ``System.Text.Json`` library, but now it affects normal use, so we have an intention to solve the problem. -Modern `JSON services <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoremvccorebuilderextensions.addjsonoptions?view=aspnetcore-7.0>`_ -out of `the box <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoremvccorebuilderextensions?view=aspnetcore-7.0>`_ +Modern `JSON services <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoremvccorebuilderextensions.addjsonoptions>`_ +out of `the box <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.mvccoremvccorebuilderextensions>`_ will help to configure JSON settings by the ``JsonSerializerOptions`` property for JSON formatters during (de)serialization. Solution diff --git a/docs/features/logging.rst b/docs/features/logging.rst index 36572f778..979b16145 100644 --- a/docs/features/logging.rst +++ b/docs/features/logging.rst @@ -2,7 +2,7 @@ Logging ======= Ocelot uses the standard logging interfaces ``ILoggerFactory`` and ``ILogger<T>`` at the moment. -This is encapsulated in ``IOcelotLogger`` and ``IOcelotLoggerFactory`` with an implementation for the standard `ASP.NET Core logging <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-7.0>`_ stuff at the moment. +This is encapsulated in ``IOcelotLogger`` and ``IOcelotLoggerFactory`` with an implementation for the standard `ASP.NET Core logging <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/>`_ stuff at the moment. This is because Ocelot adds some extra info to the logs such as **request ID** if it is configured. There is a global `error handler middleware <https://github.com/search?q=repo%3AThreeMammals%2FOcelot%20ExceptionHandlerMiddleware&type=code>`_ that should catch any exceptions thrown and log them as errors. @@ -16,8 +16,8 @@ Nicely onto the next feature. Warning ------- -If you are logging to `Console <https://learn.microsoft.com/en-us/dotnet/api/system.console?view=net-7.0>`_, you will get terrible performance. -The team has had so many issues about performance issues with Ocelot and it is always logging level **Debug**, logging to `Console <https://learn.microsoft.com/en-us/dotnet/api/system.console?view=net-7.0>`_. +If you are logging to `Console <https://learn.microsoft.com/en-us/dotnet/api/system.console>`_, you will get terrible performance. +The team has had so many issues about performance issues with Ocelot and it is always logging level **Debug**, logging to `Console <https://learn.microsoft.com/en-us/dotnet/api/system.console>`_. * **Warning!** Make sure you are logging to something proper in production environment! * Use **Error** and **Critical** levels in production environment! diff --git a/docs/features/middlewareinjection.rst b/docs/features/middlewareinjection.rst index bf0ac2152..d1ee78478 100644 --- a/docs/features/middlewareinjection.rst +++ b/docs/features/middlewareinjection.rst @@ -38,7 +38,7 @@ So, the next called middlewares **will not** affect Ocelot configuration. ASP.NET Core Middlewares and Ocelot Pipeline Builder ---------------------------------------------------- -Ocelot pipeline is a part of entire `ASP.NET Core Middlewares <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0>`_ conveyor aka app pipeline. +Ocelot pipeline is a part of entire `ASP.NET Core Middlewares <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/>`_ conveyor aka app pipeline. The `BuildOcelotPipeline <https://github.com/search?q=repo%3AThreeMammals%2FOcelot+BuildOcelotPipeline+path%3A%2F%5Esrc%5C%2FOcelot%5C%2FMiddleware%5C%2F%2F&type=code>`_ method encapsulates Ocelot pipeline. The last middleware in the ``BuildOcelotPipeline`` method is ``HttpRequesterMiddleware`` that calls the next middleware, if added to the pipeline. diff --git a/docs/features/ratelimiting.rst b/docs/features/ratelimiting.rst index e0cf56690..9a69f4ded 100644 --- a/docs/features/ratelimiting.rst +++ b/docs/features/ratelimiting.rst @@ -57,9 +57,9 @@ There is no decision at the moment, and the old version of the feature is includ See more about new feature being added into ASP.NET Core 7.0 release: -* `RateLimiter Class <https://learn.microsoft.com/en-us/dotnet/api/system.threading.ratelimiting.ratelimiter?view=aspnetcore-7.0>`_, since ASP.NET Core **7.0** +* `RateLimiter Class <https://learn.microsoft.com/en-us/dotnet/api/system.threading.ratelimiting.ratelimiter>`_, since ASP.NET Core **7.0** * `System.Threading.RateLimiting <https://www.nuget.org/packages/System.Threading.RateLimiting>`_ NuGet package -* `Rate limiting middleware in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-7.0>`_ article by Arvin Kahbazi, Maarten Balliauw, and Rick Anderson +* `Rate limiting middleware in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit>`_ article by Arvin Kahbazi, Maarten Balliauw, and Rick Anderson However, it makes sense to keep the old implementation as a Ocelot built-in native feature, but we are going to migrate to the new Rate Limiter from ``Microsoft.AspNetCore.RateLimiting`` namespace. diff --git a/docs/features/websockets.rst b/docs/features/websockets.rst index 8dfc23321..5e1e4fc54 100644 --- a/docs/features/websockets.rst +++ b/docs/features/websockets.rst @@ -38,7 +38,7 @@ Links * WHATWG: `WebSockets Standard <https://websockets.spec.whatwg.org/>`_ * Mozilla Developer Network: `The WebSocket API (WebSockets) <https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API>`_ -* Microsoft Learn: `WebSockets support in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-7.0>`_ +* Microsoft Learn: `WebSockets support in ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets>`_ * Microsoft Learn: `WebSockets support in .NET <https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/websockets>`_ SignalR @@ -65,10 +65,10 @@ So, SignalR is `the part <https://github.com/dotnet/aspnetcore/tree/main/src/Sig <FrameworkReference Include="Microsoft.AspNetCore.App" /> </ItemGroup> -More information on framework compatibility can be found in instrictions: `Use ASP.NET Core APIs in a class library <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/target-aspnetcore?view=aspnetcore-7.0&tabs=visual-studio>`_. +More information on framework compatibility can be found in instrictions: `Use ASP.NET Core APIs in a class library <https://learn.microsoft.com/en-us/aspnet/core/fundamentals/target-aspnetcore>`_. **Second**, you need to tell your application to use *SignalR*. -Complete reference is here: `ASP.NET Core SignalR configuration <https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-7.0&tabs=dotnet>`_ +Complete reference is here: `ASP.NET Core SignalR configuration <https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration>`_ .. code-block:: csharp @@ -79,7 +79,7 @@ Complete reference is here: `ASP.NET Core SignalR configuration <https://learn.m } Pay attention to configuration of transport level of *WebSockets*, -so `configure allowed transports <https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration?view=aspnetcore-7.0&tabs=dotnet#configure-allowed-transports>`_ to allow *WebSockets* connections. +so `configure allowed transports <https://learn.microsoft.com/en-us/aspnet/core/signalr/configuration#configure-allowed-transports>`_ to allow *WebSockets* connections. **Then** in your **ocelot.json** add the following to proxy a Route using SignalR. Note normal Ocelot routing rules apply the main thing is the scheme which is set to ``ws``. diff --git a/docs/index.rst b/docs/index.rst index 38d6c0a87..3ec283703 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,4 +1,4 @@ -Welcome to Ocelot 20.0 +Welcome to Ocelot 21.0 ====================== Thanks for taking a look at the Ocelot documentation! Please use the left hand navigation to get around. diff --git a/docs/introduction/gettingstarted.rst b/docs/introduction/gettingstarted.rst index efe296971..333261992 100644 --- a/docs/introduction/gettingstarted.rst +++ b/docs/introduction/gettingstarted.rst @@ -1,16 +1,16 @@ Getting Started =============== -Ocelot is designed to work with ASP.NET and is currently on ``net7.0`` framework. +Ocelot is designed to work with ASP.NET and is currently on ``net6.0``, ``net7.0`` and ``net8.0`` frameworks. -.NET 7.0 +.NET 8.0 -------- Install NuGet package ^^^^^^^^^^^^^^^^^^^^^ Install Ocelot and it's dependencies using `NuGet <https://www.nuget.org/>`_. -You will need to create a `ASP.NET Core 7.0 project <https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-7.0&tabs=visual-studio>`_ and bring the package into it. +You will need to create a `ASP.NET Core minimal API project <https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api>`_ and bring the package into it. Then follow the startup below and :doc:`../features/configuration` sections to get up and running. .. code-block:: powershell diff --git a/docs/introduction/gotchas.rst b/docs/introduction/gotchas.rst index e62e1eedb..9a8f856ae 100644 --- a/docs/introduction/gotchas.rst +++ b/docs/introduction/gotchas.rst @@ -4,14 +4,14 @@ Gotchas IIS ----- - Microsoft Learn: `Host ASP.NET Core on Windows with IIS <https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-7.0>`_ + Microsoft Learn: `Host ASP.NET Core on Windows with IIS <https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/>`_ We do not recommend to deploy Ocelot app to IIS environments, but if you do, keep in mind the gotchas below. * When using ASP.NET Core 2.2+ and you want to use In-Process hosting, replace ``UseIISIntegration()`` with ``UseIIS()``, otherwise you will get startup errors. * Make sure you use Out-of-process hosting model instead of In-process one - (see `Out-of-process hosting with IIS and ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/out-of-process-hosting?view=aspnetcore-7.0>`_), + (see `Out-of-process hosting with IIS and ASP.NET Core <https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/out-of-process-hosting>`_), otherwise you will get very slow responses (see `1657 <https://github.com/ThreeMammals/Ocelot/issues/1657>`_). * Ensure all DNS servers of all downstream hosts are online and they function perfectly, otherwise you will get slow responses (see `1630 <https://github.com/ThreeMammals/Ocelot/issues/1630>`_). diff --git a/samples/AdministrationApi/AdministrationApi.csproj b/samples/AdministrationApi/AdministrationApi.csproj index 691f6bb63..cd995c774 100644 --- a/samples/AdministrationApi/AdministrationApi.csproj +++ b/samples/AdministrationApi/AdministrationApi.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> </PropertyGroup> @@ -8,8 +8,7 @@ <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="Ocelot.Administration" Version="18.0.0" /> - + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> </Project> diff --git a/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj index 41ad8deb6..9e381bb17 100644 --- a/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj +++ b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj @@ -1,18 +1,14 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> </PropertyGroup> - <ItemGroup> <Folder Include="Properties\" /> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj index 90f81c521..a41f67537 100644 --- a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj @@ -1,25 +1,20 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - - <ItemGroup> - <None Update="ocelot.json;appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="Ocelot.Provider.Eureka" Version="18.0.0" /> - <PackageReference Include="Ocelot.Provider.Polly" Version="18.0.0" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> +</Project> diff --git a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj index 73f006405..e0d47d1c9 100644 --- a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj @@ -1,21 +1,16 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Steeltoe.Discovery.Client" Version="1.1.0" /> - </ItemGroup> - - <ItemGroup> - <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Steeltoe.Discovery.Client" Version="1.1.0" /> + </ItemGroup> + <ItemGroup> + <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" /> + </ItemGroup> +</Project> diff --git a/samples/OcelotGraphQL/OcelotGraphQL.csproj b/samples/OcelotGraphQL/OcelotGraphQL.csproj index 6a7658f30..32039beba 100644 --- a/samples/OcelotGraphQL/OcelotGraphQL.csproj +++ b/samples/OcelotGraphQL/OcelotGraphQL.csproj @@ -1,19 +1,21 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - <ItemGroup> - <None Update="ocelot.json;appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="GraphQL" Version="4.8.0" /> - </ItemGroup> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="GraphQL" Version="4.8.0" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> </Project> diff --git a/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj index 548b13d79..f88cd602b 100644 --- a/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj @@ -1,20 +1,16 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> - <ItemGroup> - <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" /> + <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" /> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj index 914c863da..3c1cfefb2 100644 --- a/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj @@ -1,5 +1,4 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>disable</ImplicitUsings> @@ -7,10 +6,7 @@ <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> - <ItemGroup> - <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> </ItemGroup> - </Project> diff --git a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj index 4c7ccf28a..a05368868 100644 --- a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj +++ b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj @@ -1,22 +1,30 @@ <Project Sdk="Microsoft.NET.Sdk.Worker"> - <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> </PropertyGroup> - <ItemGroup> <PackageReference Include="Jaeger" Version="1.0.3" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" /> + </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" /> + </ItemGroup> <ItemGroup> <Content Update="appsettings.Development.json"> <ExcludeFromSingleFile>true</ExcludeFromSingleFile> @@ -28,5 +36,4 @@ <ExcludeFromSingleFile>true</ExcludeFromSingleFile> </Content> </ItemGroup> - </Project> diff --git a/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj b/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj index e987ea143..aac1dd20a 100644 --- a/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj +++ b/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj @@ -1,11 +1,8 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> </PropertyGroup> - <ItemGroup> <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj index 07284008b..c97238c53 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj @@ -1,23 +1,23 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <Description>Stateless Web Service for Stateful OcelotApplicationApiGateway App</Description> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <AssemblyName>OcelotApplicationApiGateway</AssemblyName> - <PackageId>OcelotApplicationApiGateway</PackageId> - <PlatformTarget>x64</PlatformTarget> - </PropertyGroup> - <ItemGroup> - <None Update="ocelot.json;appsettings.json;"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Microsoft.ServiceFabric" Version="9.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.Services" Version="6.1.1799" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\..\..\src\Ocelot\Ocelot.csproj" /> - </ItemGroup> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <Description>Stateless Web Service for Stateful OcelotApplicationApiGateway App</Description> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <AssemblyName>OcelotApplicationApiGateway</AssemblyName> + <PackageId>OcelotApplicationApiGateway</PackageId> + <PlatformTarget>x64</PlatformTarget> + </PropertyGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json;"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.ServiceFabric" Version="10.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.Services" Version="7.1.1541" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> </Project> diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj index 4bde15efc..6dc51c893 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <Description>Stateless Service Application</Description> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AssemblyName>OcelotApplicationService</AssemblyName> @@ -13,8 +13,8 @@ <None Remove="global.json" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.ServiceFabric" Version="9.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.Services" Version="6.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.AspNetCore.Kestrel" Version="6.1.1799" /> + <PackageReference Include="Microsoft.ServiceFabric" Version="10.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.Services" Version="7.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.AspNetCore.Kestrel" Version="7.1.1541" /> </ItemGroup> </Project> diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index 4b075c29d..4bb397ab3 100644 --- a/src/Ocelot.Administration/Ocelot.Administration.csproj +++ b/src/Ocelot.Administration/Ocelot.Administration.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Administration</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -26,11 +26,12 @@ <DebugType>full</DebugType> <DebugSymbols>True</DebugSymbols> </PropertyGroup> + <!-- Project dependencies --> <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> @@ -39,4 +40,19 @@ <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" /> + <PackageReference Include="System.Text.Encodings.Web" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.14" /> + <PackageReference Include="System.Text.Encodings.Web" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" /> + <PackageReference Include="System.Text.Encodings.Web" Version="8.0.0" /> + </ItemGroup> </Project> diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index f4f40691a..4636540bc 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Cache.CacheManager</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -26,11 +26,12 @@ <DebugType>full</DebugType> <DebugSymbols>True</DebugSymbols> </PropertyGroup> + <!-- Project dependencies --> <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> @@ -40,4 +41,28 @@ <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="6.0.11" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="7.0.4" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="8.0.0-preview.7.23375.6" /> + </ItemGroup> </Project> diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index b9cdb1127..f8149b859 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Consul</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -30,8 +30,8 @@ <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index 92b1ba985..b7d578440 100644 --- a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj +++ b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj @@ -1,43 +1,43 @@ -<Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>Provides Ocelot extensions to use Eureka</Description> - <AssemblyTitle>Ocelot.Provider.Eureka</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot.Provider.Eureka</AssemblyName> - <PackageId>Ocelot.Provider.Eureka</PackageId> - <PackageTags>API Gateway;.NET core</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - <ItemGroup> - <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - <PackageReference Include="Steeltoe.Discovery.Eureka" Version="3.2.3" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> -</Project> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>Provides Ocelot extensions to use Eureka</Description> + <AssemblyTitle>Ocelot.Provider.Eureka</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot.Provider.Eureka</AssemblyName> + <PackageId>Ocelot.Provider.Eureka</PackageId> + <PackageTags>API Gateway;.NET core</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + <PackageReference Include="Steeltoe.Discovery.Eureka" Version="3.2.5" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index 92afba3aa..375b89535 100644 --- a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj +++ b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj @@ -1,7 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -13,7 +12,7 @@ <AssemblyName>Ocelot.Provider.Kubernetes</AssemblyName> <PackageId>Ocelot.Provider.Kubernetes</PackageId> <PackageTags>API Gateway;.NET core</PackageTags> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> @@ -25,26 +24,21 @@ <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <Compile Remove="IKubeApiClientFactory.cs" /> <Compile Remove="KubeApiClientFactory.cs" /> </ItemGroup> - <ItemGroup> <PackageReference Include="KubeClient" Version="2.4.10" /> <PackageReference Include="KubeClient.Extensions.DependencyInjection" Version="2.4.10" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> - <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> - </Project> diff --git a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj index 4ffcb9eb6..a75db00e8 100644 --- a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj +++ b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -13,7 +13,7 @@ <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Polly</PackageProjectUrl> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Polly</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -31,10 +31,10 @@ <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Polly" Version="7.2.3" /> + <PackageReference Include="Polly" Version="8.2.0" /> </ItemGroup> <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> diff --git a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj index a955c6f0c..68b90652f 100644 --- a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj +++ b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj @@ -1,45 +1,43 @@ -<Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>This package provides methods to integrate Butterfly tracing with Ocelot.</Description> - <AssemblyTitle>Ocelot.Tracing.Butterfly</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot.Tracing.Butterfly</AssemblyName> - <PackageId>Ocelot.Tracing.Butterfly</PackageId> - <PackageTags>API Gateway;.NET core; Butterfly; ButterflyAPM</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <RootNamespace>Ocelot.Tracing.Butterfly</RootNamespace> - <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - <ItemGroup> - <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Butterfly.Client" Version="0.0.8" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>This package provides methods to integrate Butterfly tracing with Ocelot.</Description> + <AssemblyTitle>Ocelot.Tracing.Butterfly</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot.Tracing.Butterfly</AssemblyName> + <PackageId>Ocelot.Tracing.Butterfly</PackageId> + <PackageTags>API Gateway;.NET core; Butterfly; ButterflyAPM</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <RootNamespace>Ocelot.Tracing.Butterfly</RootNamespace> + <GenerateDocumentationFile>True</GenerateDocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Butterfly.Client" Version="0.0.8" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index e3b7336bf..635e3c77d 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -1,7 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <Version>0.0.0-dev</Version> @@ -15,21 +14,17 @@ <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <AdditionalFiles Include="stylecop.json" /> <None Include="..\..\images\ocelot_logo.png" Pack="true" Visible="true" PackagePath="\" /> </ItemGroup> - <ItemGroup> <PackageReference Include="OpenTracing" Version="0.12.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 6e8c79308..4649ecd0b 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -14,8 +14,16 @@ public static partial class ConfigurationBuilderExtensions public const string PrimaryConfigFile = "ocelot.json"; public const string GlobalConfigFile = "ocelot.global.json"; - [GeneratedRegex("^ocelot\\.(.*?)\\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, "en-US")] +#if NET7_0_OR_GREATER + [GeneratedRegex(@"^ocelot\.(.*?)\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, "en-US")] private static partial Regex SubConfigRegex(); +#else + private static readonly Regex SubConfigRegexVar = new(@"^ocelot\.(.*?)\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromMilliseconds(1000)); + private static Regex SubConfigRegex() + { + return SubConfigRegexVar; + } +#endif [Obsolete("Please set BaseUrl in ocelot.json GlobalConfiguration.BaseUrl")] public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder builder, string baseUrl) diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index f33f36c73..d5a8c0629 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -68,11 +68,11 @@ public void SetHeadersOnDownstreamRequest(IEnumerable<AddHeader> headers, HttpCo continue; } - requestHeader.Add(header.Key, new StringValues(value.Data)); + requestHeader.Append(header.Key, new StringValues(value.Data)); } else { - requestHeader.Add(header.Key, header.Value); + requestHeader.Append(header.Key, header.Value); } } } diff --git a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs index 85c6ad7d8..ec0a8c0da 100644 --- a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs @@ -14,7 +14,7 @@ public Response Replace(HttpContext context, List<HeaderFindAndReplace> fAndRs) { var replaced = values[f.Index].Replace(f.Find, f.Replace); context.Request.Headers.Remove(f.Key); - context.Request.Headers.Add(f.Key, replaced); + context.Request.Headers.Append(f.Key, replaced); } } diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index bc71e34ac..19f0a5bdc 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -1,46 +1,58 @@ -<Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features.</Description> - <AssemblyTitle>Ocelot</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot</AssemblyName> - <PackageId>Ocelot</PackageId> - <PackageTags>API Gateway;.NET core</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features.</Description> + <AssemblyTitle>Ocelot</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot</AssemblyName> + <PackageId>Ocelot</PackageId> + <PackageTags>API Gateway;.NET core</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - - <ItemGroup> - <PackageReference Include="FluentValidation" Version="11.5.2" /> - <PackageReference Include="IPAddressRange" Version="6.0.0" /> - <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="7.0.5" /> - <PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.32"> - <NoWarn>NU1701</NoWarn> - </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.5" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> - -</Project> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <!-- Project dependencies --> + <ItemGroup> + <PackageReference Include="FluentValidation" Version="11.8.0" /> + <PackageReference Include="IPAddressRange" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.32"> + <NoWarn>NU1701</NoWarn> + </PackageReference> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="6.0.25" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.25" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="7.0.14" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.14" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="8.0.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index 4e4fb6ba5..2c21e0c9e 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -93,7 +93,7 @@ private static void AddHeaderIfDoesntExist(HttpContext context, Header httpRespo { if (!context.Response.Headers.ContainsKey(httpResponseHeader.Key)) { - context.Response.Headers.Add(httpResponseHeader.Key, new StringValues(httpResponseHeader.Values.ToArray())); + context.Response.Headers.Append(httpResponseHeader.Key, new StringValues(httpResponseHeader.Values.ToArray())); } } } diff --git a/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs b/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs index fea55c146..bf336b54f 100644 --- a/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs +++ b/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs @@ -13,8 +13,17 @@ public ClientWebSocketOptionsProxy(ClientWebSocketOptions options) _real = options; } + // .NET 6 and lower doesn't support the properties below. + // Instead of throwing a NotSupportedException, we just implement the getter/setter. + // This way, we can use the same code for .NET 6 and .NET 7+. + // TODO The design should be reviewed since we are hiding the ClientWebSocketOptions properties. +#if NET7_0_OR_GREATER public Version HttpVersion { get => _real.HttpVersion; set => _real.HttpVersion = value; } public HttpVersionPolicy HttpVersionPolicy { get => _real.HttpVersionPolicy; set => _real.HttpVersionPolicy = value; } +#else + public Version HttpVersion { get; set; } + public HttpVersionPolicy HttpVersionPolicy { get; set; } +#endif public bool UseDefaultCredentials { get => _real.UseDefaultCredentials; set => _real.UseDefaultCredentials = value; } public ICredentials Credentials { get => _real.Credentials; set => _real.Credentials = value; } public IWebProxy Proxy { get => _real.Proxy; set => _real.Proxy = value; } @@ -23,8 +32,11 @@ public ClientWebSocketOptionsProxy(ClientWebSocketOptions options) public CookieContainer Cookies { get => _real.Cookies; set => _real.Cookies = value; } public TimeSpan KeepAliveInterval { get => _real.KeepAliveInterval; set => _real.KeepAliveInterval = value; } public WebSocketDeflateOptions DangerousDeflateOptions { get => _real.DangerousDeflateOptions; set => _real.DangerousDeflateOptions = value; } +#if NET7_0_OR_GREATER public bool CollectHttpResponseDetails { get => _real.CollectHttpResponseDetails; set => _real.CollectHttpResponseDetails = value; } - +#else + public bool CollectHttpResponseDetails { get; set; } +#endif public void AddSubProtocol(string subProtocol) => _real.AddSubProtocol(subProtocol); public void SetBuffer(int receiveBufferSize, int sendBufferSize) => _real.SetBuffer(receiveBufferSize, sendBufferSize);
diff --git a/test/Ocelot.AcceptanceTests/CachingTests.cs b/test/Ocelot.AcceptanceTests/CachingTests.cs index 95f6f5166..b2ef34d6c 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -211,7 +211,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re { if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(key)) { - context.Response.Headers.Add(key, value); + context.Response.Headers.Append(key, value); } context.Response.StatusCode = statusCode; diff --git a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs index f138675b9..6d0c31a3a 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -370,7 +370,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string var kvp = new FakeConsulGetResponse(base64); json = JsonConvert.SerializeObject(new[] { kvp }); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") @@ -398,7 +398,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { var json = JsonConvert.SerializeObject(_consulServices); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs index d03d7e6b9..38e4e18c8 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -126,7 +126,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 8def02990..1be8c7798 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -141,7 +141,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string }; var json = JsonConvert.SerializeObject(applications); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 5a28e1753..1a7979a1d 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -448,7 +448,7 @@ private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int { context.Response.OnStarting(() => { - context.Response.Headers.Add(headerKey, headerValue); + context.Response.Headers.Append(headerKey, headerValue); context.Response.StatusCode = statusCode; return Task.CompletedTask; }); diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index c54810e36..760b03bae 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,53 +1,51 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.AcceptanceTests</AssemblyName> - <OutputType>Exe</OutputType> - <PackageId>Ocelot.AcceptanceTests</PackageId> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <OutputType>Exe</OutputType> + <PackageId>Ocelot.AcceptanceTests</PackageId> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - - <ItemGroup> - <None Update="appsettings.product.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - <ProjectReference Include="..\Ocelot.ManualTest\Ocelot.ManualTest.csproj" /> - </ItemGroup> - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <ItemGroup> + <None Update="appsettings.product.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\Ocelot.ManualTest\Ocelot.ManualTest.csproj" /> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -55,31 +53,58 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.5" /> - <PackageReference Include="Moq" Version="4.18.4" /> - <PackageReference Include="OpenTracing" Version="0.12.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> - <PackageReference Include="Shouldly" Version="4.1.0" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" /> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="Moq" Version="4.20.69" /> + <PackageReference Include="OpenTracing" Version="0.12.1" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" /> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs index c182721ad..9d8f3ec39 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -6,7 +6,6 @@ namespace Ocelot.AcceptanceTests public class PollyQoSTests : IDisposable { private readonly Steps _steps; - private int _requestCount; private readonly ServiceHandler _serviceHandler; public PollyQoSTests() @@ -227,32 +226,17 @@ private static void GivenIWaitMilliseconds(int ms) private void GivenThereIsAPossiblyBrokenServiceRunningOn(string url, string responseBody) { + var requestCount = 0; _serviceHandler.GivenThereIsAServiceRunningOn(url, async context => { - //circuit starts closed - if (_requestCount == 0) + if (requestCount == 1) { - _requestCount++; - context.Response.StatusCode = 200; - await context.Response.WriteAsync(responseBody); - return; - } - - //request one times out and polly throws exception, circuit opens - if (_requestCount == 1) - { - _requestCount++; await Task.Delay(1000); - context.Response.StatusCode = 200; - return; } - //after break closes we return 200 OK - if (_requestCount == 2) - { - context.Response.StatusCode = 200; - await context.Response.WriteAsync(responseBody); - } + requestCount++; + context.Response.StatusCode = 200; + await context.Response.WriteAsync(responseBody); }); } diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index 2e7987846..e1de4f313 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -171,7 +171,7 @@ private void GivenThereIsAServiceRunningOn(string url) _serviceHandler.GivenThereIsAServiceRunningOn(url, context => { context.Request.Headers.TryGetValue(_steps.RequestIdKey, out var requestId); - context.Response.Headers.Add(_steps.RequestIdKey, requestId.First()); + context.Response.Headers[_steps.RequestIdKey] = requestId.First(); return Task.CompletedTask; }); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index 1814db1e8..c9f093bf0 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -516,7 +516,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } var json = JsonConvert.SerializeObject(_consulServices); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 30b3d7235..3a695bb9c 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -97,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) if (context.Request.Path.Value == "/v1/health/service/product") { var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index cdf0002c7..4e99d1fe0 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -10,7 +10,7 @@ namespace Ocelot.Benchmarks { - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] + [SimpleJob(launchCount: 1, warmupCount: 2, iterationCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig { @@ -51,7 +51,7 @@ public void SetUp() QueryString = new QueryString("?a=b"), }, }; - httpContext.Request.Headers.Add("Host", "most"); + httpContext.Request.Headers.Append("Host", "most"); httpContext.Items.SetIInternalConfiguration(new InternalConfiguration(new List<Route>(), null, null, null, null, null, null, null, null)); _httpContext = httpContext; diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index 0dde79085..35e0f25b0 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -8,7 +8,7 @@ namespace Ocelot.Benchmarks { - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] + [SimpleJob(launchCount: 1, warmupCount: 2, iterationCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig { diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index 12081074d..ffbd2d8a4 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -1,8 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> @@ -10,7 +9,7 @@ <AssemblyName>Ocelot.Benchmarks</AssemblyName> <OutputType>Exe</OutputType> <PackageId>Ocelot.Benchmarks</PackageId> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> @@ -18,18 +17,15 @@ <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - <ItemGroup> - <PackageReference Include="BenchmarkDotNet" Version="0.13.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="BenchmarkDotNet" Version="0.13.10" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index c78949e19..dbd821b49 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -1,44 +1,43 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.IntegrationTests</AssemblyName> - <OutputType>Exe</OutputType> - <PackageId>Ocelot.IntegrationTests</PackageId> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <OutputType>Exe</OutputType> + <PackageId>Ocelot.IntegrationTests</PackageId> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> - <None Update="peers.json;appsettings.json;mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <ItemGroup> + <None Update="peers.json;appsettings.json;mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -46,23 +45,48 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Shouldly" Version="4.2.1" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Microsoft.Data.SQLite" Version="7.0.5" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index 18601b7f0..81aabb2f1 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -1,14 +1,14 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <PreserveCompilationContext>true</PreserveCompilationContext> <AssemblyName>Ocelot.ManualTest</AssemblyName> <OutputType>Exe</OutputType> <PackageId>Ocelot.ManualTest</PackageId> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> @@ -32,6 +32,22 @@ <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> @@ -39,9 +55,16 @@ <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> </ItemGroup> <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 98bfd1ea0..b36029232 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1564,11 +1564,20 @@ private class TestOptions : AuthenticationSchemeOptions } private class TestHandler : AuthenticationHandler<TestOptions> - { + { + // https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/8.0/isystemclock-obsolete + // .NET 8.0: TimeProvider is now a settable property on the Options classes for the authentication and identity components. + // It can be set directly or by registering a provider in the dependency injection container. +#if NET8_0_OR_GREATER + public TestHandler(IOptionsMonitor<TestOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder) + { + } +#else public TestHandler(IOptionsMonitor<TestOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { - } - + } +#endif + protected override Task<AuthenticateResult> HandleAuthenticateAsync() { var principal = new ClaimsPrincipal(); diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index 115727676..e00c8a0af 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -205,7 +205,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 2b8827c6a..b59c0bb68 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -102,7 +102,7 @@ public void should_throw_exception_if_config_provider_throws() private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) { - _httpContext.Request.Headers.Add(key, value); + _httpContext.Request.Headers.Append(key, value); /* _httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); */ diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index d0236ad61..86eec01f0 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -79,17 +79,10 @@ private void GivenHttpRequestWithoutHeaders() } private void GivenHttpRequestWithHeader(string headerKey, string headerValue) - { - _context = new DefaultHttpContext - { - Request = - { - Headers = - { - { headerKey, headerValue }, - }, - }, - }; + { + var context = new DefaultHttpContext(); + context.Request.Headers.Append(headerKey, headerValue); + _context = context; } private void WhenAddingHeader(string headerKey, string headerValue) diff --git a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs index 6bc8d6c40..51fe342b1 100644 --- a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs @@ -21,7 +21,7 @@ public HttpContextRequestHeaderReplacerTests() public void should_replace_headers() { var context = new DefaultHttpContext(); - context.Request.Headers.Add("test", "test"); + context.Request.Headers.Append("test", "test"); var fAndRs = new List<HeaderFindAndReplace> { new("test", "test", "chiken", 0) }; @@ -36,7 +36,7 @@ public void should_replace_headers() public void should_not_replace_headers() { var context = new DefaultHttpContext(); - context.Request.Headers.Add("test", "test"); + context.Request.Headers.Append("test", "test"); var fAndRs = new List<HeaderFindAndReplace>(); diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 41433df78..d9441462b 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -106,7 +106,7 @@ private void ThenTheIHttpResponseHeaderReplacerIsCalledCorrectly() private void GivenTheFollowingRequest() { - _httpContext.Request.Headers.Add("test", "test"); + _httpContext.Request.Headers.Append("test", "test"); } } } diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index c7f71723a..0b6dd1832 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -123,7 +123,7 @@ public void should_return_upstreamHost() { var upstreamHost = "UpstreamHostA"; var httpContext = new DefaultHttpContext(); - httpContext.Request.Headers.Add("Host", upstreamHost); + httpContext.Request.Headers.Append("Host", upstreamHost); _accessor.Setup(x => x.HttpContext).Returns(httpContext); var result = _placeholders.Get("{UpstreamHost}"); result.Data.ShouldBe(upstreamHost); diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs index 2e9fe7ab5..272128a95 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs @@ -128,7 +128,7 @@ private void GivenThereIsAFakeKubeServiceDiscoveryProvider(string url, string se } var json = JsonConvert.SerializeObject(_endpointEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index be5d367b2..2766f58ab 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -21,7 +21,7 @@ public LeastConnectionTests() } [Fact] - public void should_be_able_to_lease_and_release_concurrently() + public async Task should_be_able_to_lease_and_release_concurrently() { var serviceName = "products"; @@ -41,11 +41,11 @@ public void should_be_able_to_lease_and_release_concurrently() tasks[i] = LeaseDelayAndRelease(); } - Task.WaitAll(tasks); + await Task.WhenAll(tasks); } [Fact] - public void should_handle_service_returning_to_available() + public async Task should_handle_service_returning_to_available() { var serviceName = "products"; @@ -57,9 +57,9 @@ public void should_handle_service_returning_to_available() _leastConnection = new LeastConnection(() => Task.FromResult(availableServices), serviceName); - var hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + var hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - var hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + var hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -69,9 +69,9 @@ public void should_handle_service_returning_to_available() new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty<string>()), }; - hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.1"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -82,9 +82,9 @@ public void should_handle_service_returning_to_available() new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty<string>()), }; - hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -117,7 +117,7 @@ public void should_get_next_url() } [Fact] - public void should_serve_from_service_with_least_connections() + public async Task should_serve_from_service_with_least_connections() { var serviceName = "products"; @@ -131,21 +131,21 @@ public void should_serve_from_service_with_least_connections() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[2].HostAndPort.DownstreamHost); } [Fact] - public void should_build_connections_per_service() + public async Task should_build_connections_per_service() { var serviceName = "products"; @@ -158,25 +158,25 @@ public void should_build_connections_per_service() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } [Fact] - public void should_release_connection() + public async Task should_release_connection() { var serviceName = "products"; @@ -189,26 +189,26 @@ public void should_release_connection() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); //release this so 2 should have 1 connection and we should get 2 back as our next host and port _leastConnection.Release(availableServices[1].HostAndPort); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index a981467c2..78196c13e 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -39,17 +39,17 @@ public void should_get_next_address() } [Fact] - public void should_go_back_to_first_address_after_finished_last() + public async Task should_go_back_to_first_address_after_finished_last() { var stopWatch = Stopwatch.StartNew(); while (stopWatch.ElapsedMilliseconds < 1000) { - var address = _roundRobin.Lease(_httpContext).Result; + var address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[0].HostAndPort); - address = _roundRobin.Lease(_httpContext).Result; + address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[1].HostAndPort); - address = _roundRobin.Lease(_httpContext).Result; + address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[2].HostAndPort); } } diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index 6c844ccd9..a7e6d2cb2 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -13,24 +13,19 @@ public class MultiplexingMiddlewareTests private readonly MultiplexingMiddleware _middleware; private Ocelot.DownstreamRouteFinder.DownstreamRouteHolder _downstreamRoute; private int _count; - private readonly Mock<IResponseAggregator> _aggregator; - private readonly Mock<IResponseAggregatorFactory> _factory; private readonly HttpContext _httpContext; - private readonly RequestDelegate _next; - private readonly Mock<IOcelotLoggerFactory> _loggerFactory; - private readonly Mock<IOcelotLogger> _logger; public MultiplexingMiddlewareTests() { _httpContext = new DefaultHttpContext(); - _factory = new Mock<IResponseAggregatorFactory>(); - _aggregator = new Mock<IResponseAggregator>(); - _factory.Setup(x => x.Get(It.IsAny<Route>())).Returns(_aggregator.Object); - _loggerFactory = new Mock<IOcelotLoggerFactory>(); - _logger = new Mock<IOcelotLogger>(); - _loggerFactory.Setup(x => x.CreateLogger<MultiplexingMiddleware>()).Returns(_logger.Object); - _next = context => Task.FromResult(_count++); - _middleware = new MultiplexingMiddleware(_next, _loggerFactory.Object, _factory.Object); + var factory = new Mock<IResponseAggregatorFactory>(); + var aggregator = new Mock<IResponseAggregator>(); + factory.Setup(x => x.Get(It.IsAny<Route>())).Returns(aggregator.Object); + var loggerFactory = new Mock<IOcelotLoggerFactory>(); + var logger = new Mock<IOcelotLogger>(); + loggerFactory.Setup(x => x.CreateLogger<MultiplexingMiddleware>()).Returns(logger.Object); + Task Next(HttpContext context) => Task.FromResult(_count++); + _middleware = new MultiplexingMiddleware(Next, loggerFactory.Object, factory.Object); } [Fact] diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index 0c9fe46f7..c54b547a4 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -1,63 +1,56 @@ <Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.UnitTests</AssemblyName> - <PackageId>Ocelot.UnitTests</PackageId> - <OutputType>Exe</OutputType> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <PackageId>Ocelot.UnitTests</PackageId> + <OutputType>Exe</OutputType> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - - <ItemGroup> - <Compile Remove="Kubernetes\KubeProviderFactoryTests.cs" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> - </ItemGroup> - - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - - <ItemGroup> - <None Update="appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <Compile Remove="Kubernetes\KubeProviderFactoryTests.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <None Update="appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Nito.AsyncEx" Version="5.1.2" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -65,30 +58,57 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> - <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.5" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Moq" Version="4.18.4" /> - <PackageReference Include="Shouldly" Version="4.1.0" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> - <PackageReference Include="Polly" Version="7.2.3" /> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Moq" Version="4.20.69" /> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> + <PackageReference Include="Polly" Version="8.2.0" /> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs index ad93c9d4e..bd6c5a736 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -274,7 +274,7 @@ private void ThenTheMappedRequestHasContentDispositionHeader(string expected) private void GivenTheContentDispositionIs(string input) { - _inputRequest.Headers.Add("Content-Disposition", input); + _inputRequest.Headers.Append("Content-Disposition", input); } private void ThenTheMappedRequestHasContentMD5Header(byte[] expected) @@ -285,7 +285,7 @@ private void ThenTheMappedRequestHasContentMD5Header(byte[] expected) private void GivenTheContentMD5Is(byte[] input) { var base64 = Convert.ToBase64String(input); - _inputRequest.Headers.Add("Content-MD5", base64); + _inputRequest.Headers.Append("Content-MD5", base64); } private void ThenTheMappedRequestHasContentRangeHeader() @@ -296,7 +296,7 @@ private void ThenTheMappedRequestHasContentRangeHeader() private void GivenTheContentRangeIs(string input) { - _inputRequest.Headers.Add("Content-Range", input); + _inputRequest.Headers.Append("Content-Range", input); } private void ThenTheMappedRequestHasContentLocationHeader(string expected) @@ -306,7 +306,7 @@ private void ThenTheMappedRequestHasContentLocationHeader(string expected) private void GivenTheContentLocationIs(string input) { - _inputRequest.Headers.Add("Content-Location", input); + _inputRequest.Headers.Append("Content-Location", input); } private void ThenTheMappedRequestHasContentLanguageHeader(string expected) @@ -316,7 +316,7 @@ private void ThenTheMappedRequestHasContentLanguageHeader(string expected) private void GivenTheContentLanguageIs(string input) { - _inputRequest.Headers.Add("Content-Language", input); + _inputRequest.Headers.Append("Content-Language", input); } private void ThenTheMappedRequestHasContentEncodingHeader(string expected, string expectedTwo) @@ -327,7 +327,7 @@ private void ThenTheMappedRequestHasContentEncodingHeader(string expected, strin private void GivenTheContentEncodingIs(string input) { - _inputRequest.Headers.Add("Content-Encoding", input); + _inputRequest.Headers.Append("Content-Encoding", input); } private void GivenTheContentTypeIs(string contentType) diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index 54b223c2c..641f9c9cc 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -32,7 +32,7 @@ public RequestIdMiddlewareTests() _loggerFactory.Setup(x => x.CreateLogger<RequestIdMiddleware>()).Returns(_logger.Object); _next = context => { - _httpContext.Response.Headers.Add("LSRequestId", _httpContext.TraceIdentifier); + _httpContext.Response.Headers.Append("LSRequestId", _httpContext.TraceIdentifier); return Task.CompletedTask; }; _middleware = new RequestIdMiddleware(_next, _loggerFactory.Object, _repo.Object); diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index 523e1a483..3e273bf85 100644 --- a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -9,16 +9,15 @@ namespace Ocelot.UnitTests.Responder public class HttpContextResponderTests { private readonly HttpContextResponder _responder; - private readonly RemoveOutputHeaders _removeOutputHeaders; public HttpContextResponderTests() { - _removeOutputHeaders = new RemoveOutputHeaders(); - _responder = new HttpContextResponder(_removeOutputHeaders); + var removeOutputHeaders = new RemoveOutputHeaders(); + _responder = new HttpContextResponder(removeOutputHeaders); } [Fact] - public void should_remove_transfer_encoding_header() + public async Task should_remove_transfer_encoding_header() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -27,42 +26,38 @@ public void should_remove_transfer_encoding_header() new("Transfer-Encoding", new List<string> {"woop"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["Transfer-Encoding"]; header.ShouldBeEmpty(); } [Fact] - public void should_ignore_content_if_null() + public async Task should_ignore_content_if_null() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(null, HttpStatusCode.OK, new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason"); - Should.NotThrow(() => + await Should.NotThrowAsync(async () => { - _responder - .SetResponseOnHttpContext(httpContext, response) - .GetAwaiter() - .GetResult() - ; + await _responder.SetResponseOnHttpContext(httpContext, response); }); } [Fact] - public void should_have_content_length() + public async Task should_have_content_length() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent("test"), HttpStatusCode.OK, new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["Content-Length"]; header.First().ShouldBe("4"); } [Fact] - public void should_add_header() + public async Task should_add_header() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -71,13 +66,13 @@ public void should_add_header() new("test", new List<string> {"test"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["test"]; header.First().ShouldBe("test"); } [Fact] - public void should_add_reason_phrase() + public async Task should_add_reason_phrase() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -86,7 +81,7 @@ public void should_add_reason_phrase() new("test", new List<string> {"test"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); httpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase.ShouldBe(response.ReasonPhrase); }
Ocelot to .NET 8 ## Expected Behavior / New Feature [.NET 8 was launched this week](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/), so we expect Ocelot to be compatible with .NET 8 as soon as possible. 😸 - [Announcing .NET 8 | .NET Blog](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/) by Gaurav Seth on November 14th, 2023 ## Actual Behavior / Motivation for New Feature Only supporting .NET 7 ## Specifications - After a chat with @RaynaldM, we should provide .NET8 and .NET7 support for the Ocelot sources (`<TargetFrameworks>` and `Item` groups with conditions) - After yet another chat with @raman-m we should provide .NET6 support too... - Tests and examples are targeting .NET8, .NET7 and .NET6 if possible ☕ 🥃 😸
⚠️⚠️⚠️ ❗Important❗ Feature branch is [release/net8](https://github.com/ThreeMammals/Ocelot/tree/release/net8). It is created from **main**. Delivery process is based on Gitflow Hotfix one. That means, this feature (upgrade) should be delivered first, before [Oct'23](../milestone/1)! > Tests and examples are targeting .NET8 I'm not sure about this. If the lib targets multiple frameworks then why should tests target only one framework? Ok, let's begin from scratch again, to summarize: - using release/net8 branch - Targeting net6;net7;net8 - Updating config, making sure that we are using 2 whitespaces for indent in xml files - Tests and Samples should, if feasible, target to net6;net7 and net8 too 👨🏼‍🚀 During last month I have been thinking about release strategy. On some day we will have to decide on versioning and release strategy. It seems today is this day... The old school release strategy was - separate release branch for each version - multiple building pipelines for each version - supporting a version via back porting of features & bugfixes - releasing each version separately But when .NET 6 provided multi targeted frameworks feature everything was changed, and release strategy could be more simplest if changes are .NET versioning only. Also, git repo back porting doesn't make sense anymore. Support can be organized using one repo and one release branch, having one code base. But in this modern approach we have to use more preprocessor directives. Let's try this approach and we will see how it's useful... This release strategy requires less resources.
2023-11-19T23:55:14Z
0.1
[]
['Ocelot.UnitTests.Responder.HttpContextResponderTests.should_remove_transfer_encoding_header', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_ignore_content_if_null', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_have_content_length', 'Ocelot.UnitTests.Headers.AddHeadersToResponseTests.should_add_header', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_add_header', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_add_reason_phrase', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_be_able_to_lease_and_release_concurrently', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_handle_service_returning_to_available', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_serve_from_service_with_least_connections', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_build_connections_per_service', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_release_connection', 'Ocelot.UnitTests.LoadBalancer.RoundRobinTests.should_go_back_to_first_address_after_finished_last', 'Ocelot.UnitTests.Headers.HttpContextRequestHeaderReplacerTests.should_replace_headers', 'Ocelot.UnitTests.Headers.HttpContextRequestHeaderReplacerTests.should_not_replace_headers', 'Ocelot.UnitTests.Infrastructure.PlaceholdersTests.should_return_upstreamHost']
ThreeMammals/Ocelot
threemammals__ocelot-1789
d3a623ee7ae6de00b939fd847cc7cef6d4c89276
diff --git a/.circleci/config.yml b/.circleci/config.yml index 4a5f1d936..cbdcf7c9d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,13 +4,13 @@ orbs: jobs: build: docker: - - image: mijitt0m/ocelot-build:0.0.9 + - image: ocelot2/circleci-build:latest steps: - checkout - run: dotnet tool restore && dotnet cake release: docker: - - image: mijitt0m/ocelot-build:0.0.9 + - image: ocelot2/circleci-build:latest steps: - checkout - run: dotnet tool restore && dotnet cake --target=Release @@ -19,7 +19,7 @@ workflows: main: jobs: - queue/block_workflow: - time: "20" + time: '20' only-on-branch: main - release: requires: @@ -38,6 +38,6 @@ workflows: - build: filters: branches: - ignore: + ignore: - main - develop diff --git a/.editorconfig b/.editorconfig index 6aa3d30f4..e4e769b52 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,7 +4,12 @@ root = true end_of_line = lf insert_final_newline = true -[*.cs] +[*.cs] end_of_line = lf indent_style = space indent_size = 4 + +# XML files +[*.xml] +indent_style = space +indent_size = 2 diff --git a/Ocelot.sln b/Ocelot.sln index c4abd99a9..1215130de 100644 --- a/Ocelot.sln +++ b/Ocelot.sln @@ -1,7 +1,7 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 -VisualStudioVersion = 17.6.33723.286 +VisualStudioVersion = 17.8.34309.116 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5CFB79B7-C9DC-45A4-9A75-625D92471702}" EndProject diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 691339490..49b877c10 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine +FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib git openssh-client @@ -6,4 +6,11 @@ RUN curl -L --output ./dotnet-install.sh https://dot.net/v1/dotnet-install.sh RUN chmod u+x ./dotnet-install.sh +# Install .NET 8 SDK (already included in the base image, but listed for consistency) +RUN ./dotnet-install.sh -c 8.0 -i /usr/share/dotnet + +# Install .NET 7 SDK +RUN ./dotnet-install.sh -c 7.0 -i /usr/share/dotnet + +# Install .NET 6 SDK RUN ./dotnet-install.sh -c 6.0 -i /usr/share/dotnet diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build index 5498c6106..39d3107b9 100644 --- a/docker/Dockerfile.build +++ b/docker/Dockerfile.build @@ -1,7 +1,8 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.9 + +FROM ocelot2/circleci-build:latest ARG OCELOT_COVERALLS_TOKEN @@ -13,4 +14,4 @@ COPY ./. . RUN dotnet tool restore -RUN dotnet cake \ No newline at end of file +RUN dotnet cake diff --git a/docker/Dockerfile.release b/docker/Dockerfile.release index e2659c035..89c1b3f79 100644 --- a/docker/Dockerfile.release +++ b/docker/Dockerfile.release @@ -1,7 +1,8 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.9 + +FROM ocelot2/circleci-build:latest ARG OCELOT_COVERALLS_TOKEN ARG OCELOT_NUTGET_API_KEY @@ -17,4 +18,4 @@ COPY ./. . RUN dotnet tool restore -RUN dotnet cake \ No newline at end of file +RUN dotnet cake diff --git a/docker/README.md b/docker/README.md index 3eb46aa42..dcecc224d 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,3 +1,3 @@ # docker build -This folder contains the dockerfile and script to create the ocelot build container. \ No newline at end of file +This folder contains the `Dockerfile.*` and `build.sh` script to create the Ocelot build image & container. diff --git a/docker/build.sh b/docker/build.sh index bf2cee9b5..15d1325ad 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -1,7 +1,11 @@ -# this script build the ocelot docker file -version=0.0.9 -docker build --platform linux/amd64 -t mijitt0m/ocelot-build -f Dockerfile.base . +# This script builds the Ocelot Docker file + +# {DotNetSdkVer}.{OcelotVer} -> {.NET8}.{21.0} -> 8.21.0 +version=8.21.0 +docker build --platform linux/amd64 -t ocelot2/circleci-build -f Dockerfile.base . + echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin -docker tag mijitt0m/ocelot-build mijitt0m/ocelot-build:$version -docker push mijitt0m/ocelot-build:latest -docker push mijitt0m/ocelot-build:$version \ No newline at end of file + +docker tag ocelot2/circleci-build ocelot2/circleci-build:$version +docker push ocelot2/circleci-build:latest +docker push ocelot2/circleci-build:$version diff --git a/samples/AdministrationApi/AdministrationApi.csproj b/samples/AdministrationApi/AdministrationApi.csproj index 691f6bb63..cd995c774 100644 --- a/samples/AdministrationApi/AdministrationApi.csproj +++ b/samples/AdministrationApi/AdministrationApi.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> </PropertyGroup> @@ -8,8 +8,7 @@ <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="Ocelot.Administration" Version="18.0.0" /> - + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> </Project> diff --git a/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj index 41ad8deb6..9e381bb17 100644 --- a/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj +++ b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj @@ -1,18 +1,14 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> </PropertyGroup> - <ItemGroup> <Folder Include="Properties\" /> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj index 90f81c521..a41f67537 100644 --- a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj @@ -1,25 +1,20 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - - <ItemGroup> - <None Update="ocelot.json;appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="Ocelot.Provider.Eureka" Version="18.0.0" /> - <PackageReference Include="Ocelot.Provider.Polly" Version="18.0.0" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> +</Project> diff --git a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj index 73f006405..e0d47d1c9 100644 --- a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj @@ -1,21 +1,16 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Steeltoe.Discovery.Client" Version="1.1.0" /> - </ItemGroup> - - <ItemGroup> - <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Steeltoe.Discovery.Client" Version="1.1.0" /> + </ItemGroup> + <ItemGroup> + <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" /> + </ItemGroup> +</Project> diff --git a/samples/OcelotGraphQL/OcelotGraphQL.csproj b/samples/OcelotGraphQL/OcelotGraphQL.csproj index 6a7658f30..32039beba 100644 --- a/samples/OcelotGraphQL/OcelotGraphQL.csproj +++ b/samples/OcelotGraphQL/OcelotGraphQL.csproj @@ -1,19 +1,21 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - </PropertyGroup> - <ItemGroup> - <None Update="ocelot.json;appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <Folder Include="wwwroot\" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Ocelot" Version="18.0.0" /> - <PackageReference Include="GraphQL" Version="4.8.0" /> - </ItemGroup> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + </PropertyGroup> + <ItemGroup> + <Folder Include="wwwroot\" /> + </ItemGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="GraphQL" Version="4.8.0" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> </Project> diff --git a/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj index 548b13d79..f88cd602b 100644 --- a/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj @@ -1,20 +1,16 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> - <ItemGroup> - <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" /> + <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" /> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj index 914c863da..3c1cfefb2 100644 --- a/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj @@ -1,5 +1,4 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>disable</ImplicitUsings> @@ -7,10 +6,7 @@ <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> - <ItemGroup> - <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> </ItemGroup> - </Project> diff --git a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj index 4c7ccf28a..a05368868 100644 --- a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj +++ b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj @@ -1,22 +1,30 @@ <Project Sdk="Microsoft.NET.Sdk.Worker"> - <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> </PropertyGroup> - <ItemGroup> <PackageReference Include="Jaeger" Version="1.0.3" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" /> + </ItemGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" /> + </ItemGroup> <ItemGroup> <Content Update="appsettings.Development.json"> <ExcludeFromSingleFile>true</ExcludeFromSingleFile> @@ -28,5 +36,4 @@ <ExcludeFromSingleFile>true</ExcludeFromSingleFile> </Content> </ItemGroup> - </Project> diff --git a/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj b/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj index e987ea143..aac1dd20a 100644 --- a/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj +++ b/samples/OcelotServiceDiscovery/ApiGateway/Ocelot.Samples.ServiceDiscovery.ApiGateway.csproj @@ -1,11 +1,8 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> </PropertyGroup> - <ItemGroup> <ProjectReference Include="..\..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj index 07284008b..c97238c53 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj @@ -1,23 +1,23 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - <PropertyGroup> - <Description>Stateless Web Service for Stateful OcelotApplicationApiGateway App</Description> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <AssemblyName>OcelotApplicationApiGateway</AssemblyName> - <PackageId>OcelotApplicationApiGateway</PackageId> - <PlatformTarget>x64</PlatformTarget> - </PropertyGroup> - <ItemGroup> - <None Update="ocelot.json;appsettings.json;"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Microsoft.ServiceFabric" Version="9.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.Services" Version="6.1.1799" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\..\..\src\Ocelot\Ocelot.csproj" /> - </ItemGroup> +<Project Sdk="Microsoft.NET.Sdk.Web"> + <PropertyGroup> + <Description>Stateless Web Service for Stateful OcelotApplicationApiGateway App</Description> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <AssemblyName>OcelotApplicationApiGateway</AssemblyName> + <PackageId>OcelotApplicationApiGateway</PackageId> + <PlatformTarget>x64</PlatformTarget> + </PropertyGroup> + <ItemGroup> + <None Update="ocelot.json;appsettings.json;"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.ServiceFabric" Version="10.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.Services" Version="7.1.1541" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\..\..\src\Ocelot\Ocelot.csproj" /> + </ItemGroup> </Project> diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj index 4bde15efc..6dc51c893 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <Description>Stateless Service Application</Description> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <AssemblyName>OcelotApplicationService</AssemblyName> @@ -13,8 +13,8 @@ <None Remove="global.json" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.ServiceFabric" Version="9.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.Services" Version="6.1.1799" /> - <PackageReference Include="Microsoft.ServiceFabric.AspNetCore.Kestrel" Version="6.1.1799" /> + <PackageReference Include="Microsoft.ServiceFabric" Version="10.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.Services" Version="7.1.1541" /> + <PackageReference Include="Microsoft.ServiceFabric.AspNetCore.Kestrel" Version="7.1.1541" /> </ItemGroup> </Project> diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index 4b075c29d..4bb397ab3 100644 --- a/src/Ocelot.Administration/Ocelot.Administration.csproj +++ b/src/Ocelot.Administration/Ocelot.Administration.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Administration</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -26,11 +26,12 @@ <DebugType>full</DebugType> <DebugSymbols>True</DebugSymbols> </PropertyGroup> + <!-- Project dependencies --> <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> @@ -39,4 +40,19 @@ <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" /> + <PackageReference Include="System.Text.Encodings.Web" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.14" /> + <PackageReference Include="System.Text.Encodings.Web" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" /> + <PackageReference Include="System.Text.Encodings.Web" Version="8.0.0" /> + </ItemGroup> </Project> diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index f4f40691a..4636540bc 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Cache.CacheManager</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -26,11 +26,12 @@ <DebugType>full</DebugType> <DebugSymbols>True</DebugSymbols> </PropertyGroup> + <!-- Project dependencies --> <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> @@ -40,4 +41,28 @@ <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="6.0.11" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="7.0.4" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.NETCore.Platforms" Version="8.0.0-preview.7.23375.6" /> + </ItemGroup> </Project> diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index b9cdb1127..f8149b859 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -12,7 +12,7 @@ <PackageTags>API Gateway;.NET core</PackageTags> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Consul</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -30,8 +30,8 @@ <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index 92b1ba985..b7d578440 100644 --- a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj +++ b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj @@ -1,43 +1,43 @@ -<Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>Provides Ocelot extensions to use Eureka</Description> - <AssemblyTitle>Ocelot.Provider.Eureka</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot.Provider.Eureka</AssemblyName> - <PackageId>Ocelot.Provider.Eureka</PackageId> - <PackageTags>API Gateway;.NET core</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - <ItemGroup> - <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - <PackageReference Include="Steeltoe.Discovery.Eureka" Version="3.2.3" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> -</Project> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>Provides Ocelot extensions to use Eureka</Description> + <AssemblyTitle>Ocelot.Provider.Eureka</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot.Provider.Eureka</AssemblyName> + <PackageId>Ocelot.Provider.Eureka</PackageId> + <PackageTags>API Gateway;.NET core</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Eureka</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + <PackageReference Include="Steeltoe.Discovery.Eureka" Version="3.2.5" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index 92afba3aa..375b89535 100644 --- a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj +++ b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj @@ -1,7 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -13,7 +12,7 @@ <AssemblyName>Ocelot.Provider.Kubernetes</AssemblyName> <PackageId>Ocelot.Provider.Kubernetes</PackageId> <PackageTags>API Gateway;.NET core</PackageTags> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> @@ -25,26 +24,21 @@ <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <Compile Remove="IKubeApiClientFactory.cs" /> <Compile Remove="KubeApiClientFactory.cs" /> </ItemGroup> - <ItemGroup> <PackageReference Include="KubeClient" Version="2.4.10" /> <PackageReference Include="KubeClient.Extensions.DependencyInjection" Version="2.4.10" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> - <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> - </Project> diff --git a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj index 4ffcb9eb6..a75db00e8 100644 --- a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj +++ b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <NoPackageAnalysis>true</NoPackageAnalysis> @@ -13,7 +13,7 @@ <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Polly</PackageProjectUrl> <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot.Provider.Polly</PackageProjectUrl> <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> @@ -31,10 +31,10 @@ <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Polly" Version="7.2.3" /> + <PackageReference Include="Polly" Version="8.2.0" /> </ItemGroup> <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> diff --git a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj index a955c6f0c..68b90652f 100644 --- a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj +++ b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj @@ -1,45 +1,43 @@ -<Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>This package provides methods to integrate Butterfly tracing with Ocelot.</Description> - <AssemblyTitle>Ocelot.Tracing.Butterfly</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot.Tracing.Butterfly</AssemblyName> - <PackageId>Ocelot.Tracing.Butterfly</PackageId> - <PackageTags>API Gateway;.NET core; Butterfly; ButterflyAPM</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <RootNamespace>Ocelot.Tracing.Butterfly</RootNamespace> - <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - <ItemGroup> - <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> - </ItemGroup> - <ItemGroup> - <PackageReference Include="Butterfly.Client" Version="0.0.8" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>This package provides methods to integrate Butterfly tracing with Ocelot.</Description> + <AssemblyTitle>Ocelot.Tracing.Butterfly</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot.Tracing.Butterfly</AssemblyName> + <PackageId>Ocelot.Tracing.Butterfly</PackageId> + <PackageTags>API Gateway;.NET core; Butterfly; ButterflyAPM</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <RootNamespace>Ocelot.Tracing.Butterfly</RootNamespace> + <GenerateDocumentationFile>True</GenerateDocumentationFile> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Butterfly.Client" Version="0.0.8" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index e3b7336bf..635e3c77d 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -1,7 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <Version>0.0.0-dev</Version> @@ -15,21 +14,17 @@ <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <AdditionalFiles Include="stylecop.json" /> <None Include="..\..\images\ocelot_logo.png" Pack="true" Visible="true" PackagePath="\" /> </ItemGroup> - <ItemGroup> <PackageReference Include="OpenTracing" Version="0.12.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <ProjectReference Include="..\Ocelot\Ocelot.csproj" /> </ItemGroup> - </Project> diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 6e8c79308..4649ecd0b 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -14,8 +14,16 @@ public static partial class ConfigurationBuilderExtensions public const string PrimaryConfigFile = "ocelot.json"; public const string GlobalConfigFile = "ocelot.global.json"; - [GeneratedRegex("^ocelot\\.(.*?)\\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, "en-US")] +#if NET7_0_OR_GREATER + [GeneratedRegex(@"^ocelot\.(.*?)\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, "en-US")] private static partial Regex SubConfigRegex(); +#else + private static readonly Regex SubConfigRegexVar = new(@"^ocelot\.(.*?)\.json$", RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromMilliseconds(1000)); + private static Regex SubConfigRegex() + { + return SubConfigRegexVar; + } +#endif [Obsolete("Please set BaseUrl in ocelot.json GlobalConfiguration.BaseUrl")] public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder builder, string baseUrl) diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index f33f36c73..d5a8c0629 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -68,11 +68,11 @@ public void SetHeadersOnDownstreamRequest(IEnumerable<AddHeader> headers, HttpCo continue; } - requestHeader.Add(header.Key, new StringValues(value.Data)); + requestHeader.Append(header.Key, new StringValues(value.Data)); } else { - requestHeader.Add(header.Key, header.Value); + requestHeader.Append(header.Key, header.Value); } } } diff --git a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs index 85c6ad7d8..ec0a8c0da 100644 --- a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs @@ -14,7 +14,7 @@ public Response Replace(HttpContext context, List<HeaderFindAndReplace> fAndRs) { var replaced = values[f.Index].Replace(f.Find, f.Replace); context.Request.Headers.Remove(f.Key); - context.Request.Headers.Add(f.Key, replaced); + context.Request.Headers.Append(f.Key, replaced); } } diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index bc71e34ac..19f0a5bdc 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -1,46 +1,58 @@ -<Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <TargetFramework>net7.0</TargetFramework> - <ImplicitUsings>disable</ImplicitUsings> - <Nullable>disable</Nullable> - <NoPackageAnalysis>true</NoPackageAnalysis> - <Description>Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features.</Description> - <AssemblyTitle>Ocelot</AssemblyTitle> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <AssemblyName>Ocelot</AssemblyName> - <PackageId>Ocelot</PackageId> - <PackageTags>API Gateway;.NET core</PackageTags> - <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> - <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GeneratePackageOnBuild>True</GeneratePackageOnBuild> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <Authors>Tom Pallister</Authors> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> + <ImplicitUsings>disable</ImplicitUsings> + <Nullable>disable</Nullable> + <NoPackageAnalysis>true</NoPackageAnalysis> + <Description>Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features.</Description> + <AssemblyTitle>Ocelot</AssemblyTitle> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <AssemblyName>Ocelot</AssemblyName> + <PackageId>Ocelot</PackageId> + <PackageTags>API Gateway;.NET core</PackageTags> + <PackageProjectUrl>https://github.com/ThreeMammals/Ocelot</PackageProjectUrl> + <PackageIconUrl>https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png</PackageIconUrl> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GeneratePackageOnBuild>True</GeneratePackageOnBuild> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <Authors>Tom Pallister</Authors> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <GenerateDocumentationFile>True</GenerateDocumentationFile> - <NoWarn>1591</NoWarn> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - - <ItemGroup> - <PackageReference Include="FluentValidation" Version="11.5.2" /> - <PackageReference Include="IPAddressRange" Version="6.0.0" /> - <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="7.0.5" /> - <PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.32"> - <NoWarn>NU1701</NoWarn> - </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.5" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> - -</Project> + <NoWarn>1591</NoWarn> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <!-- Project dependencies --> + <ItemGroup> + <PackageReference Include="FluentValidation" Version="11.8.0" /> + <PackageReference Include="IPAddressRange" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.32"> + <NoWarn>NU1701</NoWarn> + </PackageReference> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="6.0.25" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.25" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="7.0.14" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.14" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="8.0.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" /> + </ItemGroup> +</Project> diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index 4e4fb6ba5..2c21e0c9e 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -93,7 +93,7 @@ private static void AddHeaderIfDoesntExist(HttpContext context, Header httpRespo { if (!context.Response.Headers.ContainsKey(httpResponseHeader.Key)) { - context.Response.Headers.Add(httpResponseHeader.Key, new StringValues(httpResponseHeader.Values.ToArray())); + context.Response.Headers.Append(httpResponseHeader.Key, new StringValues(httpResponseHeader.Values.ToArray())); } } } diff --git a/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs b/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs index fea55c146..bf336b54f 100644 --- a/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs +++ b/src/Ocelot/WebSockets/ClientWebSocketOptionsProxy.cs @@ -13,8 +13,17 @@ public ClientWebSocketOptionsProxy(ClientWebSocketOptions options) _real = options; } + // .NET 6 and lower doesn't support the properties below. + // Instead of throwing a NotSupportedException, we just implement the getter/setter. + // This way, we can use the same code for .NET 6 and .NET 7+. + // TODO The design should be reviewed since we are hiding the ClientWebSocketOptions properties. +#if NET7_0_OR_GREATER public Version HttpVersion { get => _real.HttpVersion; set => _real.HttpVersion = value; } public HttpVersionPolicy HttpVersionPolicy { get => _real.HttpVersionPolicy; set => _real.HttpVersionPolicy = value; } +#else + public Version HttpVersion { get; set; } + public HttpVersionPolicy HttpVersionPolicy { get; set; } +#endif public bool UseDefaultCredentials { get => _real.UseDefaultCredentials; set => _real.UseDefaultCredentials = value; } public ICredentials Credentials { get => _real.Credentials; set => _real.Credentials = value; } public IWebProxy Proxy { get => _real.Proxy; set => _real.Proxy = value; } @@ -23,8 +32,11 @@ public ClientWebSocketOptionsProxy(ClientWebSocketOptions options) public CookieContainer Cookies { get => _real.Cookies; set => _real.Cookies = value; } public TimeSpan KeepAliveInterval { get => _real.KeepAliveInterval; set => _real.KeepAliveInterval = value; } public WebSocketDeflateOptions DangerousDeflateOptions { get => _real.DangerousDeflateOptions; set => _real.DangerousDeflateOptions = value; } +#if NET7_0_OR_GREATER public bool CollectHttpResponseDetails { get => _real.CollectHttpResponseDetails; set => _real.CollectHttpResponseDetails = value; } - +#else + public bool CollectHttpResponseDetails { get; set; } +#endif public void AddSubProtocol(string subProtocol) => _real.AddSubProtocol(subProtocol); public void SetBuffer(int receiveBufferSize, int sendBufferSize) => _real.SetBuffer(receiveBufferSize, sendBufferSize);
diff --git a/test/Ocelot.AcceptanceTests/CachingTests.cs b/test/Ocelot.AcceptanceTests/CachingTests.cs index 95f6f5166..b2ef34d6c 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -211,7 +211,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re { if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(key)) { - context.Response.Headers.Add(key, value); + context.Response.Headers.Append(key, value); } context.Response.StatusCode = statusCode; diff --git a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs index f138675b9..6d0c31a3a 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -370,7 +370,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string var kvp = new FakeConsulGetResponse(base64); json = JsonConvert.SerializeObject(new[] { kvp }); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") @@ -398,7 +398,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { var json = JsonConvert.SerializeObject(_consulServices); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs index d03d7e6b9..38e4e18c8 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -126,7 +126,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 8def02990..1be8c7798 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -141,7 +141,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string }; var json = JsonConvert.SerializeObject(applications); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 5a28e1753..1a7979a1d 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -448,7 +448,7 @@ private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int { context.Response.OnStarting(() => { - context.Response.Headers.Add(headerKey, headerValue); + context.Response.Headers.Append(headerKey, headerValue); context.Response.StatusCode = statusCode; return Task.CompletedTask; }); diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index c54810e36..760b03bae 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,53 +1,51 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.AcceptanceTests</AssemblyName> - <OutputType>Exe</OutputType> - <PackageId>Ocelot.AcceptanceTests</PackageId> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <OutputType>Exe</OutputType> + <PackageId>Ocelot.AcceptanceTests</PackageId> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - - <ItemGroup> - <None Update="appsettings.product.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - <ProjectReference Include="..\Ocelot.ManualTest\Ocelot.ManualTest.csproj" /> - </ItemGroup> - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <ItemGroup> + <None Update="appsettings.product.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Tracing.OpenTracing\Ocelot.Tracing.OpenTracing.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\Ocelot.ManualTest\Ocelot.ManualTest.csproj" /> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -55,31 +53,58 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.5" /> - <PackageReference Include="Moq" Version="4.18.4" /> - <PackageReference Include="OpenTracing" Version="0.12.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> - <PackageReference Include="Shouldly" Version="4.1.0" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" /> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="Moq" Version="4.20.69" /> + <PackageReference Include="OpenTracing" Version="0.12.1" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" /> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs index c182721ad..9d8f3ec39 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -6,7 +6,6 @@ namespace Ocelot.AcceptanceTests public class PollyQoSTests : IDisposable { private readonly Steps _steps; - private int _requestCount; private readonly ServiceHandler _serviceHandler; public PollyQoSTests() @@ -227,32 +226,17 @@ private static void GivenIWaitMilliseconds(int ms) private void GivenThereIsAPossiblyBrokenServiceRunningOn(string url, string responseBody) { + var requestCount = 0; _serviceHandler.GivenThereIsAServiceRunningOn(url, async context => { - //circuit starts closed - if (_requestCount == 0) + if (requestCount == 1) { - _requestCount++; - context.Response.StatusCode = 200; - await context.Response.WriteAsync(responseBody); - return; - } - - //request one times out and polly throws exception, circuit opens - if (_requestCount == 1) - { - _requestCount++; await Task.Delay(1000); - context.Response.StatusCode = 200; - return; } - //after break closes we return 200 OK - if (_requestCount == 2) - { - context.Response.StatusCode = 200; - await context.Response.WriteAsync(responseBody); - } + requestCount++; + context.Response.StatusCode = 200; + await context.Response.WriteAsync(responseBody); }); } diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index 2e7987846..e1de4f313 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -171,7 +171,7 @@ private void GivenThereIsAServiceRunningOn(string url) _serviceHandler.GivenThereIsAServiceRunningOn(url, context => { context.Request.Headers.TryGetValue(_steps.RequestIdKey, out var requestId); - context.Response.Headers.Add(_steps.RequestIdKey, requestId.First()); + context.Response.Headers[_steps.RequestIdKey] = requestId.First(); return Task.CompletedTask; }); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index 1814db1e8..c9f093bf0 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -516,7 +516,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } var json = JsonConvert.SerializeObject(_consulServices); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 30b3d7235..3a695bb9c 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -97,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) if (context.Request.Path.Value == "/v1/health/service/product") { var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index cdf0002c7..4e99d1fe0 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -10,7 +10,7 @@ namespace Ocelot.Benchmarks { - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] + [SimpleJob(launchCount: 1, warmupCount: 2, iterationCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig { @@ -51,7 +51,7 @@ public void SetUp() QueryString = new QueryString("?a=b"), }, }; - httpContext.Request.Headers.Add("Host", "most"); + httpContext.Request.Headers.Append("Host", "most"); httpContext.Items.SetIInternalConfiguration(new InternalConfiguration(new List<Route>(), null, null, null, null, null, null, null, null)); _httpContext = httpContext; diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index 0dde79085..35e0f25b0 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -8,7 +8,7 @@ namespace Ocelot.Benchmarks { - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] + [SimpleJob(launchCount: 1, warmupCount: 2, iterationCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig { diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index 12081074d..ffbd2d8a4 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -1,8 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> @@ -10,7 +9,7 @@ <AssemblyName>Ocelot.Benchmarks</AssemblyName> <OutputType>Exe</OutputType> <PackageId>Ocelot.Benchmarks</PackageId> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> @@ -18,18 +17,15 @@ <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> - <ItemGroup> - <PackageReference Include="BenchmarkDotNet" Version="0.13.1" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> + <PackageReference Include="BenchmarkDotNet" Version="0.13.10" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> - <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> </ItemGroup> diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index c78949e19..dbd821b49 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -1,44 +1,43 @@ <Project Sdk="Microsoft.NET.Sdk"> - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.IntegrationTests</AssemblyName> - <OutputType>Exe</OutputType> - <PackageId>Ocelot.IntegrationTests</PackageId> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <OutputType>Exe</OutputType> + <PackageId>Ocelot.IntegrationTests</PackageId> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - <ItemGroup> - <None Update="peers.json;appsettings.json;mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <ItemGroup> + <None Update="peers.json;appsettings.json;mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -46,23 +45,48 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Shouldly" Version="4.2.1" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Microsoft.Data.SQLite" Version="7.0.5" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - </ItemGroup> - <ItemGroup> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Data.SQLite" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> + <ItemGroup> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index 18601b7f0..81aabb2f1 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -1,14 +1,14 @@ <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <PreserveCompilationContext>true</PreserveCompilationContext> <AssemblyName>Ocelot.ManualTest</AssemblyName> <OutputType>Exe</OutputType> <PackageId>Ocelot.ManualTest</PackageId> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> @@ -32,6 +32,22 @@ <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> </ItemGroup> <ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> @@ -39,9 +55,16 @@ <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> </ItemGroup> <ItemGroup> <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 98bfd1ea0..b36029232 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1564,11 +1564,20 @@ private class TestOptions : AuthenticationSchemeOptions } private class TestHandler : AuthenticationHandler<TestOptions> - { + { + // https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/8.0/isystemclock-obsolete + // .NET 8.0: TimeProvider is now a settable property on the Options classes for the authentication and identity components. + // It can be set directly or by registering a provider in the dependency injection container. +#if NET8_0_OR_GREATER + public TestHandler(IOptionsMonitor<TestOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder) + { + } +#else public TestHandler(IOptionsMonitor<TestOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { - } - + } +#endif + protected override Task<AuthenticateResult> HandleAuthenticateAsync() { var principal = new ClaimsPrincipal(); diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index 115727676..e00c8a0af 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -205,7 +205,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } var json = JsonConvert.SerializeObject(_serviceEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 2b8827c6a..b59c0bb68 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -102,7 +102,7 @@ public void should_throw_exception_if_config_provider_throws() private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) { - _httpContext.Request.Headers.Add(key, value); + _httpContext.Request.Headers.Append(key, value); /* _httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); */ diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index d0236ad61..86eec01f0 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -79,17 +79,10 @@ private void GivenHttpRequestWithoutHeaders() } private void GivenHttpRequestWithHeader(string headerKey, string headerValue) - { - _context = new DefaultHttpContext - { - Request = - { - Headers = - { - { headerKey, headerValue }, - }, - }, - }; + { + var context = new DefaultHttpContext(); + context.Request.Headers.Append(headerKey, headerValue); + _context = context; } private void WhenAddingHeader(string headerKey, string headerValue) diff --git a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs index 6bc8d6c40..51fe342b1 100644 --- a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs @@ -21,7 +21,7 @@ public HttpContextRequestHeaderReplacerTests() public void should_replace_headers() { var context = new DefaultHttpContext(); - context.Request.Headers.Add("test", "test"); + context.Request.Headers.Append("test", "test"); var fAndRs = new List<HeaderFindAndReplace> { new("test", "test", "chiken", 0) }; @@ -36,7 +36,7 @@ public void should_replace_headers() public void should_not_replace_headers() { var context = new DefaultHttpContext(); - context.Request.Headers.Add("test", "test"); + context.Request.Headers.Append("test", "test"); var fAndRs = new List<HeaderFindAndReplace>(); diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 41433df78..d9441462b 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -106,7 +106,7 @@ private void ThenTheIHttpResponseHeaderReplacerIsCalledCorrectly() private void GivenTheFollowingRequest() { - _httpContext.Request.Headers.Add("test", "test"); + _httpContext.Request.Headers.Append("test", "test"); } } } diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index c7f71723a..0b6dd1832 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -123,7 +123,7 @@ public void should_return_upstreamHost() { var upstreamHost = "UpstreamHostA"; var httpContext = new DefaultHttpContext(); - httpContext.Request.Headers.Add("Host", upstreamHost); + httpContext.Request.Headers.Append("Host", upstreamHost); _accessor.Setup(x => x.HttpContext).Returns(httpContext); var result = _placeholders.Get("{UpstreamHost}"); result.Data.ShouldBe(upstreamHost); diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs index 2e9fe7ab5..272128a95 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs @@ -128,7 +128,7 @@ private void GivenThereIsAFakeKubeServiceDiscoveryProvider(string url, string se } var json = JsonConvert.SerializeObject(_endpointEntries); - context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index be5d367b2..2766f58ab 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -21,7 +21,7 @@ public LeastConnectionTests() } [Fact] - public void should_be_able_to_lease_and_release_concurrently() + public async Task should_be_able_to_lease_and_release_concurrently() { var serviceName = "products"; @@ -41,11 +41,11 @@ public void should_be_able_to_lease_and_release_concurrently() tasks[i] = LeaseDelayAndRelease(); } - Task.WaitAll(tasks); + await Task.WhenAll(tasks); } [Fact] - public void should_handle_service_returning_to_available() + public async Task should_handle_service_returning_to_available() { var serviceName = "products"; @@ -57,9 +57,9 @@ public void should_handle_service_returning_to_available() _leastConnection = new LeastConnection(() => Task.FromResult(availableServices), serviceName); - var hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + var hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - var hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + var hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -69,9 +69,9 @@ public void should_handle_service_returning_to_available() new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty<string>()), }; - hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.1"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -82,9 +82,9 @@ public void should_handle_service_returning_to_available() new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty<string>()), }; - hostAndPortOne = _leastConnection.Lease(_httpContext).Result; + hostAndPortOne = await _leastConnection.Lease(_httpContext); hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; + hostAndPortTwo = await _leastConnection.Lease(_httpContext); hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -117,7 +117,7 @@ public void should_get_next_url() } [Fact] - public void should_serve_from_service_with_least_connections() + public async Task should_serve_from_service_with_least_connections() { var serviceName = "products"; @@ -131,21 +131,21 @@ public void should_serve_from_service_with_least_connections() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[2].HostAndPort.DownstreamHost); } [Fact] - public void should_build_connections_per_service() + public async Task should_build_connections_per_service() { var serviceName = "products"; @@ -158,25 +158,25 @@ public void should_build_connections_per_service() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } [Fact] - public void should_release_connection() + public async Task should_release_connection() { var serviceName = "products"; @@ -189,26 +189,26 @@ public void should_release_connection() _services = availableServices; _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); - var response = _leastConnection.Lease(_httpContext).Result; + var response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); //release this so 2 should have 1 connection and we should get 2 back as our next host and port _leastConnection.Release(availableServices[1].HostAndPort); - response = _leastConnection.Lease(_httpContext).Result; + response = await _leastConnection.Lease(_httpContext); response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost); } diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index a981467c2..78196c13e 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -39,17 +39,17 @@ public void should_get_next_address() } [Fact] - public void should_go_back_to_first_address_after_finished_last() + public async Task should_go_back_to_first_address_after_finished_last() { var stopWatch = Stopwatch.StartNew(); while (stopWatch.ElapsedMilliseconds < 1000) { - var address = _roundRobin.Lease(_httpContext).Result; + var address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[0].HostAndPort); - address = _roundRobin.Lease(_httpContext).Result; + address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[1].HostAndPort); - address = _roundRobin.Lease(_httpContext).Result; + address = await _roundRobin.Lease(_httpContext); address.Data.ShouldBe(_services[2].HostAndPort); } } diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index 6c844ccd9..a7e6d2cb2 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -13,24 +13,19 @@ public class MultiplexingMiddlewareTests private readonly MultiplexingMiddleware _middleware; private Ocelot.DownstreamRouteFinder.DownstreamRouteHolder _downstreamRoute; private int _count; - private readonly Mock<IResponseAggregator> _aggregator; - private readonly Mock<IResponseAggregatorFactory> _factory; private readonly HttpContext _httpContext; - private readonly RequestDelegate _next; - private readonly Mock<IOcelotLoggerFactory> _loggerFactory; - private readonly Mock<IOcelotLogger> _logger; public MultiplexingMiddlewareTests() { _httpContext = new DefaultHttpContext(); - _factory = new Mock<IResponseAggregatorFactory>(); - _aggregator = new Mock<IResponseAggregator>(); - _factory.Setup(x => x.Get(It.IsAny<Route>())).Returns(_aggregator.Object); - _loggerFactory = new Mock<IOcelotLoggerFactory>(); - _logger = new Mock<IOcelotLogger>(); - _loggerFactory.Setup(x => x.CreateLogger<MultiplexingMiddleware>()).Returns(_logger.Object); - _next = context => Task.FromResult(_count++); - _middleware = new MultiplexingMiddleware(_next, _loggerFactory.Object, _factory.Object); + var factory = new Mock<IResponseAggregatorFactory>(); + var aggregator = new Mock<IResponseAggregator>(); + factory.Setup(x => x.Get(It.IsAny<Route>())).Returns(aggregator.Object); + var loggerFactory = new Mock<IOcelotLoggerFactory>(); + var logger = new Mock<IOcelotLogger>(); + loggerFactory.Setup(x => x.CreateLogger<MultiplexingMiddleware>()).Returns(logger.Object); + Task Next(HttpContext context) => Task.FromResult(_count++); + _middleware = new MultiplexingMiddleware(Next, loggerFactory.Object, factory.Object); } [Fact] diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index 0c9fe46f7..c54b547a4 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -1,63 +1,56 @@ <Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <VersionPrefix>0.0.0-dev</VersionPrefix> - <TargetFramework>net7.0</TargetFramework> + <PropertyGroup> + <VersionPrefix>0.0.0-dev</VersionPrefix> + <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> <IsPackable>false</IsPackable> <IsTestProject>true</IsTestProject> <AssemblyName>Ocelot.UnitTests</AssemblyName> - <PackageId>Ocelot.UnitTests</PackageId> - <OutputType>Exe</OutputType> - <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> - <RuntimeIdentifiers>osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64</RuntimeIdentifiers> - <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> - <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> - <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> - <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> - <GenerateDocumentationFile>True</GenerateDocumentationFile> + <PackageId>Ocelot.UnitTests</PackageId> + <OutputType>Exe</OutputType> + <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles> + <RuntimeIdentifiers>win-x64;osx-x64</RuntimeIdentifiers> + <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> + <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> + <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> + <CodeAnalysisRuleSet>..\..\codeanalysis.ruleset</CodeAnalysisRuleSet> + <GenerateDocumentationFile>True</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> - - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> - <DebugType>full</DebugType> - <DebugSymbols>True</DebugSymbols> - </PropertyGroup> - - <ItemGroup> - <Compile Remove="Kubernetes\KubeProviderFactoryTests.cs" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> - <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> - <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> - </ItemGroup> - - <ItemGroup> - <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> - </ItemGroup> - - <ItemGroup> - <None Update="appsettings.json"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - <None Update="mycert.pfx"> - <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> - </None> - </ItemGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.3" /> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DebugType>full</DebugType> + <DebugSymbols>True</DebugSymbols> + </PropertyGroup> + <ItemGroup> + <Compile Remove="Kubernetes\KubeProviderFactoryTests.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" /> + <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Consul\Ocelot.Provider.Consul.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Eureka\Ocelot.Provider.Eureka.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" /> + <ProjectReference Include="..\..\src\Ocelot.Tracing.Butterfly\Ocelot.Tracing.Butterfly.csproj" /> + </ItemGroup> + <ItemGroup> + <Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" /> + </ItemGroup> + <ItemGroup> + <None Update="appsettings.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + <None Update="mycert.pfx"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Nito.AsyncEx" Version="5.1.2" /> - <PackageReference Include="xunit" Version="2.5.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.5.0"> + <PackageReference Include="xunit" Version="2.6.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> @@ -65,30 +58,57 @@ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> - <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> - <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.5" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> - <PrivateAssets>all</PrivateAssets> - </PackageReference> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> - <PackageReference Include="Moq" Version="4.18.4" /> - <PackageReference Include="Shouldly" Version="4.1.0" /> - <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> - <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> - <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> - <PackageReference Include="IdentityServer4" Version="4.1.2" /> - <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.3" /> - <PackageReference Include="Consul" Version="1.6.10.9" /> - <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" /> - <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> - <PackageReference Include="Polly" Version="7.2.3" /> - <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> - </ItemGroup> + <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507"> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="Moq" Version="4.20.69" /> + <PackageReference Include="Shouldly" Version="4.2.1" /> + <PackageReference Include="TestStack.BDDfy" Version="4.3.2" /> + <PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" /> + <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> + <PackageReference Include="IdentityServer4" Version="4.1.2" /> + <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + <PackageReference Include="Consul" Version="1.7.14.1" /> + <PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" /> + <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> + <PackageReference Include="Polly" Version="8.2.0" /> + <PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 6.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.25" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.1" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 7.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.14" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" /> + </ItemGroup> + <!-- Conditionally obtain references for the net 8.0 target --> + <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> + <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" /> + </ItemGroup> </Project> diff --git a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs index ad93c9d4e..bd6c5a736 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -274,7 +274,7 @@ private void ThenTheMappedRequestHasContentDispositionHeader(string expected) private void GivenTheContentDispositionIs(string input) { - _inputRequest.Headers.Add("Content-Disposition", input); + _inputRequest.Headers.Append("Content-Disposition", input); } private void ThenTheMappedRequestHasContentMD5Header(byte[] expected) @@ -285,7 +285,7 @@ private void ThenTheMappedRequestHasContentMD5Header(byte[] expected) private void GivenTheContentMD5Is(byte[] input) { var base64 = Convert.ToBase64String(input); - _inputRequest.Headers.Add("Content-MD5", base64); + _inputRequest.Headers.Append("Content-MD5", base64); } private void ThenTheMappedRequestHasContentRangeHeader() @@ -296,7 +296,7 @@ private void ThenTheMappedRequestHasContentRangeHeader() private void GivenTheContentRangeIs(string input) { - _inputRequest.Headers.Add("Content-Range", input); + _inputRequest.Headers.Append("Content-Range", input); } private void ThenTheMappedRequestHasContentLocationHeader(string expected) @@ -306,7 +306,7 @@ private void ThenTheMappedRequestHasContentLocationHeader(string expected) private void GivenTheContentLocationIs(string input) { - _inputRequest.Headers.Add("Content-Location", input); + _inputRequest.Headers.Append("Content-Location", input); } private void ThenTheMappedRequestHasContentLanguageHeader(string expected) @@ -316,7 +316,7 @@ private void ThenTheMappedRequestHasContentLanguageHeader(string expected) private void GivenTheContentLanguageIs(string input) { - _inputRequest.Headers.Add("Content-Language", input); + _inputRequest.Headers.Append("Content-Language", input); } private void ThenTheMappedRequestHasContentEncodingHeader(string expected, string expectedTwo) @@ -327,7 +327,7 @@ private void ThenTheMappedRequestHasContentEncodingHeader(string expected, strin private void GivenTheContentEncodingIs(string input) { - _inputRequest.Headers.Add("Content-Encoding", input); + _inputRequest.Headers.Append("Content-Encoding", input); } private void GivenTheContentTypeIs(string contentType) diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index 54b223c2c..641f9c9cc 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -32,7 +32,7 @@ public RequestIdMiddlewareTests() _loggerFactory.Setup(x => x.CreateLogger<RequestIdMiddleware>()).Returns(_logger.Object); _next = context => { - _httpContext.Response.Headers.Add("LSRequestId", _httpContext.TraceIdentifier); + _httpContext.Response.Headers.Append("LSRequestId", _httpContext.TraceIdentifier); return Task.CompletedTask; }; _middleware = new RequestIdMiddleware(_next, _loggerFactory.Object, _repo.Object); diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index 523e1a483..3e273bf85 100644 --- a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -9,16 +9,15 @@ namespace Ocelot.UnitTests.Responder public class HttpContextResponderTests { private readonly HttpContextResponder _responder; - private readonly RemoveOutputHeaders _removeOutputHeaders; public HttpContextResponderTests() { - _removeOutputHeaders = new RemoveOutputHeaders(); - _responder = new HttpContextResponder(_removeOutputHeaders); + var removeOutputHeaders = new RemoveOutputHeaders(); + _responder = new HttpContextResponder(removeOutputHeaders); } [Fact] - public void should_remove_transfer_encoding_header() + public async Task should_remove_transfer_encoding_header() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -27,42 +26,38 @@ public void should_remove_transfer_encoding_header() new("Transfer-Encoding", new List<string> {"woop"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["Transfer-Encoding"]; header.ShouldBeEmpty(); } [Fact] - public void should_ignore_content_if_null() + public async Task should_ignore_content_if_null() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(null, HttpStatusCode.OK, new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason"); - Should.NotThrow(() => + await Should.NotThrowAsync(async () => { - _responder - .SetResponseOnHttpContext(httpContext, response) - .GetAwaiter() - .GetResult() - ; + await _responder.SetResponseOnHttpContext(httpContext, response); }); } [Fact] - public void should_have_content_length() + public async Task should_have_content_length() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent("test"), HttpStatusCode.OK, new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["Content-Length"]; header.First().ShouldBe("4"); } [Fact] - public void should_add_header() + public async Task should_add_header() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -71,13 +66,13 @@ public void should_add_header() new("test", new List<string> {"test"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); var header = httpContext.Response.Headers["test"]; header.First().ShouldBe("test"); } [Fact] - public void should_add_reason_phrase() + public async Task should_add_reason_phrase() { var httpContext = new DefaultHttpContext(); var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, @@ -86,7 +81,7 @@ public void should_add_reason_phrase() new("test", new List<string> {"test"}), }, "some reason"); - _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); + await _responder.SetResponseOnHttpContext(httpContext, response); httpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase.ShouldBe(response.ReasonPhrase); }
Ocelot to .NET 8 ## Expected Behavior / New Feature [.NET 8 was launched this week](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/), so we expect Ocelot to be compatible with .NET 8 as soon as possible. 😸 - [Announcing .NET 8 | .NET Blog](https://devblogs.microsoft.com/dotnet/announcing-dotnet-8/) by Gaurav Seth on November 14th, 2023 ## Actual Behavior / Motivation for New Feature Only supporting .NET 7 ## Specifications - After a chat with @RaynaldM, we should provide .NET8 and .NET7 support for the Ocelot sources (`<TargetFrameworks>` and `Item` groups with conditions) - After yet another chat with @raman-m we should provide .NET6 support too... - Tests and examples are targeting .NET8, .NET7 and .NET6 if possible ☕ 🥃 😸
null
2023-11-19T00:44:55Z
0.1
[]
['Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_be_able_to_lease_and_release_concurrently', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_handle_service_returning_to_available', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_serve_from_service_with_least_connections', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_build_connections_per_service', 'Ocelot.UnitTests.LoadBalancer.LeastConnectionTests.should_release_connection', 'Ocelot.UnitTests.LoadBalancer.RoundRobinTests.should_go_back_to_first_address_after_finished_last', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_remove_transfer_encoding_header', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_ignore_content_if_null', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_have_content_length', 'Ocelot.UnitTests.Headers.AddHeadersToResponseTests.should_add_header', 'Ocelot.UnitTests.Responder.HttpContextResponderTests.should_add_reason_phrase', 'Ocelot.UnitTests.Headers.HttpContextRequestHeaderReplacerTests.should_replace_headers', 'Ocelot.UnitTests.Headers.HttpContextRequestHeaderReplacerTests.should_not_replace_headers', 'Ocelot.UnitTests.Infrastructure.PlaceholdersTests.should_return_upstreamHost', 'Ocelot.UnitTests.Errors.ExceptionHandlerMiddlewareTests.should_throw_exception_if_config_provider_throws']
ThreeMammals/Ocelot
threemammals__ocelot-1769
319e397d4078e6e3496cd925d715cbc3b8c589df
diff --git a/src/Ocelot/Errors/OcelotErrorCode.cs b/src/Ocelot/Errors/OcelotErrorCode.cs index 9063e7142..f74cdace1 100644 --- a/src/Ocelot/Errors/OcelotErrorCode.cs +++ b/src/Ocelot/Errors/OcelotErrorCode.cs @@ -43,5 +43,6 @@ public enum OcelotErrorCode ConnectionToDownstreamServiceError = 38, CouldNotFindLoadBalancerCreator = 39, ErrorInvokingLoadBalancerCreator = 40, + PayloadTooLargeError = 41, } } diff --git a/src/Ocelot/Middleware/HttpItemsExtensions.cs b/src/Ocelot/Middleware/HttpItemsExtensions.cs index 5d2ada0a5..d8d82ef9d 100644 --- a/src/Ocelot/Middleware/HttpItemsExtensions.cs +++ b/src/Ocelot/Middleware/HttpItemsExtensions.cs @@ -56,7 +56,7 @@ public static IInternalConfiguration IInternalConfiguration(this IDictionary<obj public static List<Error> Errors(this IDictionary<object, object> input) { var errors = input.Get<List<Error>>("Errors"); - return errors ?? new List<Error>(); + return errors ?? []; } public static DownstreamRouteFinder.DownstreamRouteHolder diff --git a/src/Ocelot/Request/Mapper/PayloadTooLargeError.cs b/src/Ocelot/Request/Mapper/PayloadTooLargeError.cs new file mode 100644 index 000000000..ba7081982 --- /dev/null +++ b/src/Ocelot/Request/Mapper/PayloadTooLargeError.cs @@ -0,0 +1,10 @@ +using Ocelot.Errors; + +namespace Ocelot.Request.Mapper; + +public class PayloadTooLargeError : Error +{ + public PayloadTooLargeError(Exception exception) : base(exception.Message, OcelotErrorCode.PayloadTooLargeError, (int) System.Net.HttpStatusCode.RequestEntityTooLarge) + { + } +} diff --git a/src/Ocelot/Requester/HttpExceptionToErrorMapper.cs b/src/Ocelot/Requester/HttpExceptionToErrorMapper.cs index dad0e856c..5c54d39a4 100644 --- a/src/Ocelot/Requester/HttpExceptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExceptionToErrorMapper.cs @@ -1,6 +1,8 @@ +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Ocelot.Errors; using Ocelot.Errors.QoS; +using Ocelot.Request.Mapper; namespace Ocelot.Requester { @@ -9,6 +11,9 @@ public class HttpExceptionToErrorMapper : IExceptionToErrorMapper /// <summary>This is a dictionary of custom mappers for exceptions.</summary> private readonly Dictionary<Type, Func<Exception, Error>> _mappers; + /// <summary>413 status.</summary> + private const int RequestEntityTooLarge = (int)HttpStatusCode.RequestEntityTooLarge; + public HttpExceptionToErrorMapper(IServiceProvider serviceProvider) { _mappers = serviceProvider.GetService<Dictionary<Type, Func<Exception, Error>>>(); @@ -39,6 +44,13 @@ public Error Map(Exception exception) if (type == typeof(HttpRequestException) || type == typeof(TimeoutException)) { + // Inner exception is a BadHttpRequestException, and only this exception exposes the StatusCode property. + // We check if the inner exception is a BadHttpRequestException and if the StatusCode is 413, we return a PayloadTooLargeError + if (exception.InnerException is BadHttpRequestException { StatusCode: RequestEntityTooLarge }) + { + return new PayloadTooLargeError(exception); + } + return new ConnectionToDownstreamServiceError(exception); } diff --git a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs index 2d0e9e8c2..b633e6d9b 100644 --- a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs @@ -55,6 +55,11 @@ public int Map(List<Error> errors) return 500; } + if (errors.Any(e => e.Code == OcelotErrorCode.PayloadTooLargeError)) + { + return 413; + } + return 404; } }
diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index 390879fc4..bb1399943 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -69,6 +69,7 @@ <PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" /> <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" /> <PackageReference Include="Steeltoe.Discovery.ClientCore" Version="3.2.5" /> + <PackageReference Include="Xunit.SkippableFact" Version="1.4.13" /> </ItemGroup> <!-- Conditionally obtain references for the net 6.0 target --> <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' "> diff --git a/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs b/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs new file mode 100644 index 000000000..35c789143 --- /dev/null +++ b/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs @@ -0,0 +1,166 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using System.Runtime.InteropServices; +using System.Text; + +namespace Ocelot.AcceptanceTests.Requester; + +public sealed class PayloadTooLargeTests : Steps, IDisposable +{ + private readonly ServiceHandler _serviceHandler; + private IHost _realServer; + + private const string Payload = + "[{\"_id\":\"6540f8ee7beff536c1304e3a\",\"index\":0,\"guid\":\"349307e2-5b1b-4ea9-8e42-d0d26b35059e\",\"isActive\":true,\"balance\":\"$2,458.86\",\"picture\":\"http://placehold.it/32x32\",\"age\":36,\"eyeColor\":\"blue\",\"name\":\"WalshSloan\",\"gender\":\"male\",\"company\":\"ENOMEN\",\"email\":\"walshsloan@enomen.com\",\"phone\":\"+1(818)463-2479\",\"address\":\"863StoneAvenue,Islandia,NewHampshire,7062\",\"about\":\"Exvelitelitutsintlaborisofficialaborisreprehenderittemporsitminim.Exveniamexetesse.Reprehenderitirurealiquipsuntnostrudcillumaliquipsuntvoluptateessenisivoluptatetemporexercitationsint.Laborumexestipsumincididuntvelit.Idnisiproidenttemporelitnonconsequatestnostrudmollit.\\r\\n\",\"registered\":\"2014-11-13T01:53:09-01:00\",\"latitude\":-1.01137,\"longitude\":160.133312,\"tags\":[\"nisi\",\"eu\",\"anim\",\"ipsum\",\"fugiat\",\"excepteur\",\"culpa\"],\"friends\":[{\"id\":0,\"name\":\"MayNoel\"},{\"id\":1,\"name\":\"RichardsDiaz\"},{\"id\":2,\"name\":\"JannieHarvey\"}],\"greeting\":\"Hello,WalshSloan!Youhave6unreadmessages.\",\"favoriteFruit\":\"banana\"},{\"_id\":\"6540f8ee39e04d0ac854b05d\",\"index\":1,\"guid\":\"0f210e11-94a1-45c7-84a4-c2bfcbe0bbfb\",\"isActive\":false,\"balance\":\"$3,371.91\",\"picture\":\"http://placehold.it/32x32\",\"age\":25,\"eyeColor\":\"green\",\"name\":\"FergusonIngram\",\"gender\":\"male\",\"company\":\"DOGSPA\",\"email\":\"fergusoningram@dogspa.com\",\"phone\":\"+1(804)599-2376\",\"address\":\"130RiverStreet,Bellamy,DistrictOfColumbia,9522\",\"about\":\"Duisvoluptatemollitullamcomollitessedolorvelit.Nonpariaturadipisicingsintdoloranimveniammollitdolorlaborumquisnulla.Ametametametnonlaborevoluptate.Eiusmoddocupidatatveniamirureessequiullamcoincididuntea.\\r\\n\",\"registered\":\"2014-11-01T03:51:36-01:00\",\"latitude\":-57.122954,\"longitude\":-91.22665,\"tags\":[\"nostrud\",\"ipsum\",\"id\",\"cupidatat\",\"consectetur\",\"labore\",\"ullamco\"],\"friends\":[{\"id\":0,\"name\":\"TabithaHuffman\"},{\"id\":1,\"name\":\"LydiaStark\"},{\"id\":2,\"name\":\"FaithStuart\"}],\"greeting\":\"Hello,FergusonIngram!Youhave3unreadmessages.\",\"favoriteFruit\":\"banana\"}]"; + + public PayloadTooLargeTests() + { + _serviceHandler = new ServiceHandler(); + } + + /// <summary> + /// Disposes the instance. + /// </summary> + /// <remarks> + /// Dispose pattern is implemented in the base <see cref="Steps"/> class. + /// </remarks> + public override void Dispose() + { + _serviceHandler.Dispose(); + _realServer?.Dispose(); + base.Dispose(); + } + + [Fact] + public void Should_throw_payload_too_large_exception_using_kestrel() + { + var port = PortFinder.GetRandomPort(); + var route = GivenRoute(port, HttpMethods.Post); + var configuration = GivenConfiguration(route); + + this.Given(x => x.GivenThereIsAServiceRunningOn(DownstreamUrl(port))) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunningOnKestrelWithCustomBodyMaxSize(1024)) + .When(x => WhenIPostUrlOnTheApiGateway("/", new ByteArrayContent(Encoding.UTF8.GetBytes(Payload)))) + .Then(x => ThenTheStatusCodeShouldBe((int)HttpStatusCode.RequestEntityTooLarge)) + .BDDfy(); + } + + [SkippableFact] + public void Should_throw_payload_too_large_exception_using_http_sys() + { + Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); + + var port = PortFinder.GetRandomPort(); + var route = GivenRoute(port, HttpMethods.Post); + var configuration = GivenConfiguration(route); + + this.Given(x => x.GivenThereIsAServiceRunningOn(DownstreamUrl(port))) + .And(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunningOnHttpSysWithCustomBodyMaxSize(1024)) + .When(x => WhenIPostUrlOnTheApiGateway("/", new ByteArrayContent(Encoding.UTF8.GetBytes(Payload)))) + .Then(x => ThenTheStatusCodeShouldBe((int)HttpStatusCode.RequestEntityTooLarge)) + .BDDfy(); + } + + private static FileRoute GivenRoute(int port, string method = null) => new() + { + DownstreamPathTemplate = "/", + DownstreamHostAndPorts = + [ + new("localhost", port), + ], + DownstreamScheme = Uri.UriSchemeHttp, + UpstreamPathTemplate = "/", + UpstreamHttpMethod = [method ?? HttpMethods.Get], + }; + + private void GivenThereIsAServiceRunningOn(string baseUrl) + { + _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, async context => + { + context.Response.StatusCode = (int)HttpStatusCode.OK; + await context.Response.WriteAsync(string.Empty); + }); + } + + private void GivenOcelotIsRunningOnKestrelWithCustomBodyMaxSize(long customBodyMaxSize) + { + _realServer = Host.CreateDefaultBuilder() + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseKestrel() + .ConfigureKestrel((_, options) => + { + options.Limits.MaxRequestBodySize = customBodyMaxSize; + }) + .ConfigureAppConfiguration((hostingContext, config) => + { + config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); + var env = hostingContext.HostingEnvironment; + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); + config.AddJsonFile(_ocelotConfigFileName, optional: true, reloadOnChange: false); + config.AddEnvironmentVariables(); + }) + .ConfigureServices(s => + { + s.AddOcelot(); + }) + .Configure(app => + { + app.UseOcelot().Wait(); + }) + .UseUrls("http://localhost:5001"); + }).Build(); + _realServer.Start(); + + _ocelotClient = new HttpClient + { + BaseAddress = new Uri("http://localhost:5001"), + }; + } + + private void GivenOcelotIsRunningOnHttpSysWithCustomBodyMaxSize(long customBodyMaxSize) + { + _realServer = Host.CreateDefaultBuilder() + .ConfigureWebHostDefaults(webBuilder => + { +#pragma warning disable CA1416 // Validate platform compatibility + webBuilder.UseHttpSys(options => + { + options.MaxRequestBodySize = customBodyMaxSize; + }) +#pragma warning restore CA1416 // Validate platform compatibility + .ConfigureAppConfiguration((hostingContext, config) => + { + config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); + var env = hostingContext.HostingEnvironment; + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false); + config.AddJsonFile(_ocelotConfigFileName, optional: true, reloadOnChange: false); + config.AddEnvironmentVariables(); + }) + .ConfigureServices(s => + { + s.AddOcelot(); + }) + .Configure(app => + { + app.UseOcelot().Wait(); + }) + .UseUrls("http://localhost:5001"); + }).Build(); + _realServer.Start(); + + _ocelotClient = new HttpClient + { + BaseAddress = new Uri("http://localhost:5001"), + }; + } +} diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index bac8fbe57..4e70e95e1 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Ocelot.AcceptanceTests.Caching; @@ -248,13 +249,10 @@ public void GivenOcelotIsRunning() /// </summary> /// <typeparam name="T">The <see cref="ILoadBalancer"/> type.</typeparam> /// <param name="loadBalancerFactoryFunc">The delegate object to load balancer factory.</param> - public void GivenOcelotIsRunningWithCustomLoadBalancer<T>( - Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, T> loadBalancerFactoryFunc) + public void GivenOcelotIsRunningWithCustomLoadBalancer<T>(Func<IServiceProvider, DownstreamRoute, IServiceDiscoveryProvider, T> loadBalancerFactoryFunc) where T : ILoadBalancer { - _webHostBuilder = new WebHostBuilder(); - - _webHostBuilder + _webHostBuilder = new WebHostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); @@ -272,7 +270,6 @@ public void GivenOcelotIsRunningWithCustomLoadBalancer<T>( .Configure(app => { app.UseOcelot().Wait(); }); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 32c5c8a33..e80551117 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -81,7 +81,13 @@ public void should_return_bad_gateway_error(OcelotErrorCode errorCode) public void should_return_not_found(OcelotErrorCode errorCode) { ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.NotFound); - } + } + + [Fact] + public void should_return_request_entity_too_large() + { + ShouldMapErrorsToStatusCode([OcelotErrorCode.PayloadTooLargeError], HttpStatusCode.RequestEntityTooLarge); + } [Fact] public void AuthenticationErrorsHaveHighestPriority() @@ -128,7 +134,7 @@ public void check_we_have_considered_all_errors_in_these_tests() // If this test fails then it's because the number of error codes has changed. // You should make the appropriate changes to the test cases here to ensure // they cover all the error codes, and then modify this assertion. - Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(41, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?"); + Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(42, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?"); } private void ShouldMapErrorToStatusCode(OcelotErrorCode errorCode, HttpStatusCode expectedHttpStatusCode)
Bad error handling for IOException while reading incoming request body ## Expected Behavior If an `IOException` happens while reading the incoming request body (in `RequestMapper.MapContent` [here](https://github.com/ThreeMammals/Ocelot/blob/02e5cea7b1bdd3d78cfe1a5bb688383f54a809fc/src/Ocelot/Request/Mapper/RequestMapper.cs#L24)), Ocelot fails the request with an `UnmappableRequestError` and status code 404. 404 is not appropriate, and the error logged by ocelot should be more specific than `UnmappableRequestError`. It just so happens that the exception happens while doing request mapping, but it's really an IO problem while reading the incoming request stream. Response status shouldn't be 404. In the case of too large request, 400 might be appropriate. In other cases, something in the 5xx range. ## Steps to Reproduce the Problem This happens consistently, for example, for requests that are too large for the server (`HttpSys` throws an IOException if the Content-Length of the incoming request is larger than 30MB by default -- see: [AspNetCore source](https://github.com/aspnet/AspNetCore/blob/cd0eab88eaa230fa276c27ab5dc71ea267efe14f/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs#L435-L436)). 1. Send a request to Ocelot, hosted on HttpSys, with Content-Length larger than 30,000,000. 1. Boom! Ocelot returns 404, and logs `UnmappableRequestError`. ## Specifications - Version: 12.0.1 (should also apply to 13.0.0 by code inspection) - Platform: Windows Server 2016 / .NET Framework 4.6.2
I think [413 Payload Too Large](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) is a better error code. What do you guys think? @TomPallister >@davidni commented [on Jan 15, 2019](#issue-399093900) David, thanks for reporting! I don't see any PRs from you... Is it still relevant? The issue was created for the old legacy version of Ocelot. Do you have an intention to discuss the bug? --------- > 404 is not appropriate, and the error logged by ocelot should be more specific than UnmappableRequestError. It just so happens that the exception happens while doing request mapping, but it's really an IO problem while reading the incoming request stream. Response status shouldn't be 404. In the case of too large request, 400 might be appropriate. In other cases, something in the 5xx range. You might be surprised, but Ocelot has strange error handling mechanism with status code overriding aka [Http Error Status Codes](https://ocelot.readthedocs.io/en/latest/features/errorcodes.html) ([docs in source](../blob/develop/docs/features/errorcodes.rst)) feature. This is Tom's design. In future it should be redesigned. I don't like HTTP status codes overriding, because the actual status is lost in Ocelot core. And, I guess, Ocelot doesn't return actual code in custom response header. ---- > In other cases, something in the 5xx range. What cases are you talking about? ---- > 400 might be appropriate Why Not? When do you create a PR with a bug fix? In my opinion, [411 Length Required](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/411), [413 Content Too Large](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) are more appropriate, because they are more specific. > @Jalalx commented [on Nov 9, 2020](#issuecomment-723938073) Agree on 413! This is the best status code to return in case of Content-Length problems with request. **P.S.** Don't reference Tom in chats. He doesn't read Ocelot GitHub notifications since 2020... Only current maintainers read notifications, it's me and Raynald. @raman-m This is issue present with latest Ocelot version too. I am able to replicate now. Was missing to configure UseHttpSys(). @ks1990cn I would prefer to wait for a reply from issue raiser, because I need to understand his vision and idea of fixing this bug. If he will be silent then he will be unassigned. Let's wait for a couple of weeks, up to one month... Please refer to dummy changes I made on `RequestMapper.cs` on my branch https://github.com/ks1990cn/Ocelot/tree/ts/issue_729. @raman-m I respect your statement & waiting for @davidni to come with his idea on this bug. I am just trying to understand flow and understand what I can do to fix this, if anything comes up. Meanwhile I come up with following question:- On `RequestMapper.cs` of my branch, I have created another parameterized constructor which gives different `MaximumRequestBodySize` on different host server `IIS, Http.Sys, kestrel`. Is there any generic way to figure out `MaximumRequestBodySize` irrespective of hosted server? note - I can see on this stackoverflow discussion they use and define server specific only while doing on Global level. https://stackoverflow.com/questions/38698350/increase-upload-file-size-in-asp-net-core @ks1990cn OK, great! In my opinion we can wait for David's reply for a months, and years... But who knows... If your solution is ready, you could open a PR to **develop** branch. Also, pay attention to the fact, we have another PR #1724 which relates to `RequestMapper`! Sure, I am looking into it.. Just I am trying to figure out - On which hosting server current application is hosted, because `MaximumRequestBodySize` gives 30MB in every hosted server - IIS, https.sys, kestrel & we can modify it too, but how to find which one we are using in current application. Looking into aspnetcore application too, to understand how I can find this value. > ## Steps to Reproduce the Problem > > This happens consistently, for example, for requests that are too large for the server (`HttpSys` throws an IOException if the Content-Length of the incoming request is larger than 30MB by default -- see: [AspNetCore source](https://github.com/aspnet/AspNetCore/blob/cd0eab88eaa230fa276c27ab5dc71ea267efe14f/src/Servers/HttpSys/src/RequestProcessing/RequestStream.cs#L435-L436)). > > 1. Send a request to Ocelot, hosted on HttpSys, with Content-Length larger than 30,000,000. > 1. Boom! > We need to fix this issue for [HttpSys](https://github.com/dotnet/aspnetcore/blob/main/src/Servers/HttpSys/README.md) only, right? But Ocelot team is not responsible for third-party deployments and hosting, except Docker and Kestrel hosting, with limited support of IIS user cases. It seems this is very rare user case. And, It will be not easy to fix that because HttpSys IIS environment must be deployed for testing... @davidni FYI And, come back to us with ready PR please.
2023-10-31T13:27:43Z
0.1
['Ocelot.AcceptanceTests.Requester.PayloadTooLargeTests.Should_throw_payload_too_large_exception_using_kestrel', 'Ocelot.UnitTests.Responder.ErrorsToHttpStatusCodeMapperTests.should_return_request_entity_too_large', 'Ocelot.UnitTests.Responder.ErrorsToHttpStatusCodeMapperTests.check_we_have_considered_all_errors_in_these_tests']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-18694
b16975cb0402cd10358f17135d25c3dd3aac7ac6
diff --git a/src/Avalonia.Controls/DataValidationErrors.cs b/src/Avalonia.Controls/DataValidationErrors.cs index 243032e725c..f11c6210304 100644 --- a/src/Avalonia.Controls/DataValidationErrors.cs +++ b/src/Avalonia.Controls/DataValidationErrors.cs @@ -18,7 +18,6 @@ namespace Avalonia.Controls [PseudoClasses(":error")] public class DataValidationErrors : ContentControl { - private static bool s_overridingErrors; /// <summary> /// Defines the DataValidationErrors.Errors attached property. @@ -49,6 +48,12 @@ public class DataValidationErrors : ContentControl /// </summary> private static readonly AttachedProperty<IEnumerable<object>?> OriginalErrorsProperty = AvaloniaProperty.RegisterAttached<DataValidationErrors, Control, IEnumerable<object>?>("OriginalErrors"); + + /// <summary> + /// Prevents executing ErrorsChanged after they are updated internally from OnErrorsOrConverterChanged + /// </summary> + private static readonly AttachedProperty<bool> OverridingErrorsInternallyProperty = + AvaloniaProperty.RegisterAttached<DataValidationErrors, Control, bool>("OverridingErrorsInternally", defaultValue: false); private Control? _owner; @@ -96,9 +101,10 @@ public IDataTemplate ErrorTemplate private static void ErrorsChanged(AvaloniaPropertyChangedEventArgs e) { - if (s_overridingErrors) return; - var control = (Control)e.Sender; + + if (control.GetValue(OverridingErrorsInternallyProperty)) return; + var errors = (IEnumerable<object>?)e.NewValue; // Update original errors @@ -140,14 +146,14 @@ private static void OnErrorsOrConverterChanged(Control control) .Where(e => e is not null))? .ToArray(); - s_overridingErrors = true; + control.SetCurrentValue(OverridingErrorsInternallyProperty, true); try { control.SetCurrentValue(ErrorsProperty, newErrors!); } finally { - s_overridingErrors = false; + control.SetCurrentValue(OverridingErrorsInternallyProperty, false); } control.SetValue(HasErrorsProperty, newErrors?.Any() == true);
diff --git a/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs b/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs index 67f55055ec8..d13a25f2105 100644 --- a/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs @@ -421,6 +421,28 @@ public void Text_Validation() }); } + [Fact] + public void Text_Validation_TextBox_Errors_Binding() + { + RunTest((control, textbox) => + { + // simulate the TemplateBinding that would be used within the AutoCompleteBox control theme for the inner PART_TextBox + // DataValidationErrors.Errors="{TemplateBinding (DataValidationErrors.Errors)}" + textbox.Bind(DataValidationErrors.ErrorsProperty, control.GetBindingObservable(DataValidationErrors.ErrorsProperty)); + + var exception = new InvalidCastException("failed validation"); + var textObservable = new BehaviorSubject<BindingNotification>(new BindingNotification(exception, BindingErrorType.DataValidationError)); + control.Bind(AutoCompleteBox.TextProperty, textObservable); + Dispatcher.UIThread.RunJobs(); + + Assert.True(DataValidationErrors.GetHasErrors(control)); + Assert.Equal([exception], DataValidationErrors.GetErrors(control)); + + Assert.True(DataValidationErrors.GetHasErrors(textbox)); + Assert.Equal([exception], DataValidationErrors.GetErrors(textbox)); + }); + } + [Fact] public void SelectedItem_Validation() {
DataValidationErrors not working correctly with Bindings (in AutoCompleteBox control) ### Describe the bug When using Bindings to synchronize `DataValidationErrors.Errors` for one control with the `DataValidationErrors.Errors` property of another control, the secondary control's `DataValidationErrors.HasErrors` property does not get updated correctly. ### To Reproduce This is most easily observed in the AutoComlpeteBox control. The control uses a child TextBox control, and in the theme file, the TextBox uses this line to synchronize its Errors property: `DataValidationErrors.Errors="{TemplateBinding (DataValidationErrors.Errors)}"` When the parent AutoCompleteBox's Errors property gets updated, the child TextBox does have its Errors synchronized, however its HasErrors property remains false even though the property is true for the parent control. (You can easily see this with the F12 DevTools, looking at the `DataValidationErrors` properties for the child TextBox) [AutoCompleteBoxTest.zip](https://github.com/user-attachments/files/19825398/AutoCompleteBoxTest.zip) NOTE: I have also included the AutoCompleteBoxTest project in my fork of Avalonia here: [https://github.com/drone1400/Avalonia/tree/temp/drone-samples-autocompletebox-test](https://github.com/drone1400/Avalonia/tree/temp/drone-samples-autocompletebox-test) I have attached a simple application with both an AutoCompleteBox and second TextBox control with both of their Text properties bound to the same string property in the view model. When the string property change triggers a Validation update, the stand-alone TextBox control displays the validation error message correctly, while the AutoCompleteBox does not. NOTE: The AutoCompleteBox does display the validation error message upon first initialization, but not subsequent updates. ### Expected behavior The inner TextBox control of the AutoCompleteBox should have its `DataValidationErrors.HasErrors` property updated when its `DataValidationErrors.Errors` property is updated using Bindings. ### Avalonia version 11.2.7 ### OS Windows ### Additional context I actually looked into why this was happening and found a fix for it before submitting this issue. I will be submitting a PR as well for it, but here is an explanation. The issue is located in the Avalonia.Controls project, in the DataValidationErrors.cs file. The root of the issue seems to be that the DataValidationErrors uses the `private static bool s_overridingErrors` field to temporarily inhibit the `ErrorsChanged` handler after updating the `Errors` property internally in `OnErrorsOrConverterChanged` While this is usually fine, when using bindings, the 2nd control's `ErrorsChanged` handler gets called before `s_overridingErrors` has a chance to be cleared and thus no longer gets executed. In the case of the AutoCompleteBox, after changing its Errors property, upon entering the handler `private static void ErrorsChanged(AvaloniaPropertyChangedEventArgs e)`, the `e.Sender` and `s_overridingErrors` properties end up having the following values: | | e.Sender | s_overridingErrors | |---|-----------------|--------------------| | 1 | AutoCompleteBox | false | | 2 | AutoCompleteBox | true | | 3 | PART_TextBox | true | | 4 | AutoCompleteBox | false | | 5 | AutoCompleteBox | true | | 6 | PART_TextBox | true | When the handler gets executed for the child TextBox, the `s_overridingErrors` property is true each time and nothing gets executed. As I mentioned above, I will be submitting a PR with my fix for this issue momentarily.
null
2025-04-20T13:41:07Z
0.1
['Avalonia.Controls.UnitTests.AutoCompleteBoxTests.Text_Validation_TextBox_Errors_Binding']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-18634
f42af483c9760dd2d164972b1ea8484dbeb36cfe
diff --git a/src/Avalonia.Controls/ItemCollection.cs b/src/Avalonia.Controls/ItemCollection.cs index 03f46551c5f..03fed042bec 100644 --- a/src/Avalonia.Controls/ItemCollection.cs +++ b/src/Avalonia.Controls/ItemCollection.cs @@ -11,15 +11,10 @@ namespace Avalonia.Controls /// </summary> public class ItemCollection : ItemsSourceView, IList { -// Suppress "Avoid zero-length array allocations": This is a sentinel value and must be unique. -#pragma warning disable CA1825 - private static readonly object?[] s_uninitialized = new object?[0]; -#pragma warning restore CA1825 - private Mode _mode; internal ItemCollection() - : base(s_uninitialized) + : base(UninitializedSource) { } @@ -100,7 +95,7 @@ private IList WritableSource { if (IsReadOnly) ThrowIsItemsSource(); - if (Source == s_uninitialized) + if (Source == UninitializedSource) SetSource(CreateDefaultCollection()); return Source; } diff --git a/src/Avalonia.Controls/ItemsSourceView.cs b/src/Avalonia.Controls/ItemsSourceView.cs index 977d712371a..22cddddd058 100644 --- a/src/Avalonia.Controls/ItemsSourceView.cs +++ b/src/Avalonia.Controls/ItemsSourceView.cs @@ -27,6 +27,13 @@ public class ItemsSourceView : IReadOnlyList<object?>, /// </summary> public static ItemsSourceView Empty { get; } = new ItemsSourceView(Array.Empty<object?>()); + /// <summary> + /// Gets an instance representing an uninitialized source. + /// </summary> + [SuppressMessage("Performance", "CA1825:Avoid zero-length array allocations", Justification = "This is a sentinel value and must be unique.")] + [SuppressMessage("ReSharper", "UseCollectionExpression", Justification = "This is a sentinel value and must be unique.")] + internal static object?[] UninitializedSource { get; } = new object?[0]; + private IList _source; private NotifyCollectionChangedEventHandler? _collectionChanged; private NotifyCollectionChangedEventHandler? _preCollectionChanged; @@ -49,6 +56,9 @@ public class ItemsSourceView : IReadOnlyList<object?>, /// </summary> public IList Source => _source; + internal IList? TryGetInitializedSource() + => _source == UninitializedSource ? null : _source; + /// <summary> /// Retrieves the item at the specified index. /// </summary> diff --git a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs index 0d98d41f080..59289838bbf 100644 --- a/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs +++ b/src/Avalonia.Controls/Primitives/SelectingItemsControl.cs @@ -592,10 +592,7 @@ protected override void OnInitialized() { base.OnInitialized(); - if (_selection is object) - { - _selection.Source = ItemsView.Source; - } + TryInitializeSelectionSource(_selection, _updateState is null); } /// <inheritdoc /> @@ -896,8 +893,8 @@ private ISelectionModel GetOrCreateSelectionModel() private void OnItemsViewSourceChanged(object? sender, EventArgs e) { - if (_selection is not null && _updateState is null) - _selection.Source = ItemsView.Source; + if (_updateState is null) + TryInitializeSelectionSource(_selection, true); } /// <summary> @@ -1202,7 +1199,7 @@ private void InitializeSelectionModel(ISelectionModel model) { if (_updateState is null) { - model.Source = ItemsView.Source; + TryInitializeSelectionSource(model, false); } model.PropertyChanged += OnSelectionModelPropertyChanged; @@ -1237,6 +1234,32 @@ private void InitializeSelectionModel(ISelectionModel model) } } + private void TryInitializeSelectionSource(ISelectionModel? selection, bool shouldSelectItemFromSelectedValue) + { + if (selection is not null && ItemsView.TryGetInitializedSource() is { } source) + { + // InternalSelectionModel keeps the SelectedIndex and SelectedItem values before the ItemsSource is set. + // However, SelectedValue isn't part of that model, so we have to set the SelectedItem from + // SelectedValue manually now that we have a source. + // + // While this works, this is messy: we effectively have "lazy selection initialization" in 3 places: + // - UpdateState (all selection properties, for BeginInit/EndInit) + // - InternalSelectionModel (SelectedIndex/SelectedItem) + // - SelectedItemsControl (SelectedValue) + // + // There's the opportunity to have a single place responsible for this logic. + // TODO12 (or 13): refactor this. + if (shouldSelectItemFromSelectedValue && selection.SelectedIndex == -1 && selection.SelectedItem is null) + { + var item = FindItemWithValue(SelectedValue); + if (item != AvaloniaProperty.UnsetValue) + selection.SelectedItem = item; + } + + selection.Source = source; + } + } + private void DeinitializeSelectionModel(ISelectionModel? model) { if (model is object) @@ -1266,7 +1289,7 @@ private void EndUpdating() if (_selection is InternalSelectionModel s) { - s.Update(ItemsView.Source, state.SelectedItems); + s.Update(ItemsView.TryGetInitializedSource(), state.SelectedItems); } else { @@ -1275,7 +1298,7 @@ private void EndUpdating() SelectedItems = state.SelectedItems.Value; } - Selection.Source = ItemsView.Source; + TryInitializeSelectionSource(Selection, false); } if (state.SelectedValue.HasValue)
diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs index 5c1ece224ad..13c6ee50a5b 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests.cs @@ -441,7 +441,7 @@ public void Setting_SelectedIndex_Should_Set_SelectedItem() } [Fact] - public void Setting_SelectedIndex_Out_Of_Bounds_Should_Clear_Selection() + public void Setting_SelectedIndex_Out_Of_Bounds_With_ItemsSource_Should_Clear_Selection() { var items = new[] { @@ -462,11 +462,50 @@ public void Setting_SelectedIndex_Out_Of_Bounds_Should_Clear_Selection() } [Fact] - public void Setting_SelectedItem_To_Non_Existent_Item_Should_Clear_Selection() + public void Setting_SelectedIndex_Out_Of_Bounds_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set() { var target = new SelectingItemsControl { - Template = Template(), + Template = Template() + }; + + target.ApplyTemplate(); + target.SelectedIndex = 2; + + Assert.Equal(2, target.SelectedIndex); + + target.ItemsSource = Array.Empty<Item>(); + + Assert.Equal(-1, target.SelectedIndex); + } + + [Fact] + public void Setting_SelectedIndex_Without_ItemsSource_Should_Keep_Selection_If_Index_Exists_When_ItemsSource_IsSet() + { + var target = new SelectingItemsControl + { + Template = Template() + }; + + target.ApplyTemplate(); + target.SelectedIndex = 2; + + Assert.Equal(2, target.SelectedIndex); + + var items = new Item[] { new(), new(), new(), new() }; + target.ItemsSource = items; + + Assert.Equal(2, target.SelectedIndex); + Assert.Same(items[2], target.SelectedItem); + } + + [Fact] + public void Setting_SelectedItem_To_Non_Existent_Item_With_ItemsSource_Should_Clear_Selection() + { + var target = new SelectingItemsControl + { + ItemsSource = Array.Empty<Item>(), + Template = Template() }; target.ApplyTemplate(); @@ -476,6 +515,50 @@ public void Setting_SelectedItem_To_Non_Existent_Item_Should_Clear_Selection() Assert.Null(target.SelectedItem); } + [Fact] + public void Setting_SelectedItem_To_Non_Existent_Item_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set() + { + var item = new Item(); + + var target = new SelectingItemsControl + { + Template = Template() + }; + + target.ApplyTemplate(); + target.SelectedItem = item; + + Assert.Equal(-1, target.SelectedIndex); + Assert.Same(item, target.SelectedItem); + + target.ItemsSource = Array.Empty<Item>(); + + Assert.Equal(-1, target.SelectedIndex); + Assert.Null(target.SelectedItem); + } + + [Fact] + public void Setting_SelectedItem_Without_ItemsSource_Should_Keep_Selection_If_Item_Exists_When_ItemsSource_IsSet() + { + var item = new Item(); + + var target = new SelectingItemsControl + { + Template = Template() + }; + + target.ApplyTemplate(); + target.SelectedItem = item; + + Assert.Equal(-1, target.SelectedIndex); + Assert.Same(item, target.SelectedItem); + + target.ItemsSource = new[] { new(), new(), item, new() }; + + Assert.Equal(2, target.SelectedIndex); + Assert.Same(item, target.SelectedItem); + } + [Fact] public void Adding_Selected_Item_Should_Update_Selection() { diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_SelectedValue.cs b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_SelectedValue.cs index b0e430cbe07..a779e8d0744 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_SelectedValue.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/SelectingItemsControlTests_SelectedValue.cs @@ -170,6 +170,53 @@ public void Setting_SelectedValue_Before_Initialize_Should_Retain_Selection() Assert.Equal(items[2].Name, sic.SelectedValue); } + [Fact] + public void Setting_SelectedValue_To_Non_Existent_Item_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set() + { + var target = new SelectingItemsControl + { + Template = Template(), + SelectedValueBinding = new Binding("Name") + }; + + target.ApplyTemplate(); + target.SelectedValue = "Item2"; + + Assert.Equal(-1, target.SelectedIndex); + Assert.Null(target.SelectedItem); + Assert.Same("Item2", target.SelectedValue); + + target.ItemsSource = Array.Empty<TestClass>(); + + Assert.Equal(-1, target.SelectedIndex); + Assert.Null(target.SelectedItem); + Assert.Null(target.SelectedValue); + } + + [Fact] + public void Setting_SelectedValue_Without_ItemsSource_Should_Keep_Selection_If_Item_Exists_When_ItemsSource_IsSet() + { + var target = new SelectingItemsControl + { + Template = Template(), + SelectedValueBinding = new Binding("Name") + }; + + target.ApplyTemplate(); + target.SelectedValue = "Item2"; + + Assert.Equal(-1, target.SelectedIndex); + Assert.Null(target.SelectedItem); + Assert.Same("Item2", target.SelectedValue); + + var items = TestClass.GetItems(); + target.ItemsSource = items; + + Assert.Equal(2, target.SelectedIndex); + Assert.Same(items[2], target.SelectedItem); + Assert.Equal("Item2", target.SelectedValue); + } + [Fact] public void Setting_SelectedValue_During_Initialize_Should_Take_Priority_Over_Previous_Value() {
Datagrid ComboBox SelectedItem Show Error ### Describe the bug ![Image](https://github.com/user-attachments/assets/5ed61cc9-5094-425d-acc5-95aaa51abc5d) // DataType ComboBox ItemsSource,this show OK public static List<string> DataTypes => Enum.GetNames(typeof(DataTypeEnum)).ToList(); // DataType2 ComboBox ItemsSource, no static ,this show Error public List<string> DataTypeList => Enum.GetNames(typeof(DataTypeEnum)).ToList(); ### To Reproduce ``` public enum DataTypeEnum { Bit, Byte, Int16, Uint16, Int32, Uint32, Real, String, Wstring, DateTime } ``` ``` public partial class MainWindowViewModel : ViewModelBase { [ObservableProperty] private ObservableCollection<TagViewModel>? _tags; // DataType ComboBox ItemsSource,this show OK public static List<string> DataTypes => Enum.GetNames(typeof(DataTypeEnum)).ToList(); // DataType2 ComboBox ItemsSource, no static ,this show Error public List<string> DataTypeList => Enum.GetNames(typeof(DataTypeEnum)).ToList(); public MainWindowViewModel() { Tags = new ObservableCollection<TagViewModel>(); } private static readonly Random _random = new Random(); private string GenerateRandomAddress() { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, 8) .Select(s => s[_random.Next(s.Length)]).ToArray()); } [RelayCommand] private void Refresh() { var tags = new List<TagViewModel> { new TagViewModel { Id = 1, DeviceId = 101, DeviceName = "Device1", Name = "Tag1", Address = GenerateRandomAddress(), Desc = "Description1", DataType = DataTypeEnum.Int16.ToString(),DataType2=DataTypeEnum.Int16.ToString(), ArrayCount = 1 }, new TagViewModel { Id = 2, DeviceId = 102,DataType2=DataTypeEnum.Int16.ToString(), DeviceName = "Device2", Name = "Tag2", Address = GenerateRandomAddress(), Desc = "Description2", DataType = DataTypeEnum.Int32.ToString(), ArrayCount = 2 }, new TagViewModel { Id = 3, DeviceId = 103, DeviceName = "Device3", Name = "Tag3", Address = GenerateRandomAddress(), Desc = "Description3", DataType = DataTypeEnum.Real.ToString(), DataType2=DataTypeEnum.Int16.ToString(), ArrayCount = 3 }, new TagViewModel { Id = 4, DeviceId = 104, DeviceName = "Device4", Name = "Tag4", Address = GenerateRandomAddress(), Desc = "Description4", DataType = DataTypeEnum.String.ToString(), DataType2 = DataTypeEnum.Int16.ToString(), ArrayCount = 4 } }; Tags?.Clear(); foreach (var tag in tags) { Tags?.Add(tag); } } } ``` ``` <DataGridTemplateColumn Header="DataType" Width="120"> <DataGridTemplateColumn.CellTemplate> <DataTemplate x:DataType="vm:TagViewModel"> <ComboBox ItemsSource="{x:Static vm:MainWindowViewModel.DataTypes}" SelectedItem="{Binding DataType, Mode=TwoWay}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="数据类型2" Width="120"> <DataGridTemplateColumn.CellTemplate> <DataTemplate x:DataType="vm:TagViewModel"> <ComboBox x:CompileBindings="False" ItemsSource="{Binding $parent[DataGrid].DataContext.DataTypeList}}" SelectedItem="{Binding DataType2, Mode=TwoWay}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> ``` ### Expected behavior _No response_ ### Avalonia version 11.2.6 ### OS Windows ### Additional context _No response_
demo [DatagridDemo.zip](https://github.com/user-attachments/files/19662338/DatagridDemo.zip) This is not a bug. The reason is that the binding for `SelectedItem` may complete before the binding for `ItemsSource`, making your initial value setting ineffective. In this case, the `SelectedItem` you set does not exist in the `ItemsSource`. You can resolve this issue through some design changes, such as subscribing to the `ValueChanged` event of `ComboBox.ItemsSource` and binding `ComboBox.SelectedItem` after it is not null.
2025-04-12T15:27:20Z
0.1
['Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests.Setting_SelectedIndex_Out_Of_Bounds_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests.Setting_SelectedIndex_Without_ItemsSource_Should_Keep_Selection_If_Index_Exists_When_ItemsSource_IsSet', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests.Setting_SelectedItem_To_Non_Existent_Item_With_ItemsSource_Should_Clear_Selection', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests.Setting_SelectedItem_To_Non_Existent_Item_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests.Setting_SelectedItem_Without_ItemsSource_Should_Keep_Selection_If_Item_Exists_When_ItemsSource_IsSet', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests_SelectedValue.Setting_SelectedValue_To_Non_Existent_Item_Without_ItemsSource_Should_Keep_Selection_Until_ItemsSource_Is_Set', 'Avalonia.Controls.UnitTests.Primitives.SelectingItemsControlTests_SelectedValue.Setting_SelectedValue_Without_ItemsSource_Should_Keep_Selection_If_Item_Exists_When_ItemsSource_IsSet']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17326
fe0b91d5417632721b8733c17a0db709f687734f
diff --git a/src/Avalonia.Base/Input/IInputRoot.cs b/src/Avalonia.Base/Input/IInputRoot.cs index 2be58472207..c1c5968ebe3 100644 --- a/src/Avalonia.Base/Input/IInputRoot.cs +++ b/src/Avalonia.Base/Input/IInputRoot.cs @@ -12,7 +12,7 @@ public interface IInputRoot : IInputElement /// <summary> /// Gets or sets the keyboard navigation handler. /// </summary> - IKeyboardNavigationHandler KeyboardNavigationHandler { get; } + IKeyboardNavigationHandler? KeyboardNavigationHandler { get; } /// <summary> /// Gets focus manager of the root. diff --git a/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs b/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs index 2e14b54716c..a7c7a17e6a3 100644 --- a/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs +++ b/src/Avalonia.Controls/Primitives/OverlayPopupHost.cs @@ -2,14 +2,15 @@ using System.Collections.Generic; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Diagnostics; +using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Metadata; -using Avalonia.VisualTree; +using Avalonia.Platform; namespace Avalonia.Controls.Primitives { - public class OverlayPopupHost : ContentControl, IPopupHost, IManagedPopupPositionerPopup + public class OverlayPopupHost : ContentControl, IPopupHost, IManagedPopupPositionerPopup, IInputRoot { /// <summary> /// Defines the <see cref="Transform"/> property. @@ -19,15 +20,21 @@ public class OverlayPopupHost : ContentControl, IPopupHost, IManagedPopupPositio private readonly OverlayLayer _overlayLayer; private readonly ManagedPopupPositioner _positioner; + private readonly IKeyboardNavigationHandler? _keyboardNavigationHandler; private Point _lastRequestedPosition; private PopupPositionRequest? _popupPositionRequest; private Size _popupSize; private bool _needsUpdate; + static OverlayPopupHost() + => KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<OverlayPopupHost>(KeyboardNavigationMode.Cycle); + public OverlayPopupHost(OverlayLayer overlayLayer) { _overlayLayer = overlayLayer; _positioner = new ManagedPopupPositioner(this); + _keyboardNavigationHandler = AvaloniaLocator.Current.GetService<IKeyboardNavigationHandler>(); + _keyboardNavigationHandler?.SetOwner(this); } /// <inheritdoc /> @@ -53,6 +60,38 @@ bool IPopupHost.Topmost set { /* Not currently supported in overlay popups */ } } + private IInputRoot? InputRoot + => TopLevel.GetTopLevel(this); + + IKeyboardNavigationHandler? IInputRoot.KeyboardNavigationHandler + => _keyboardNavigationHandler; + + IFocusManager? IInputRoot.FocusManager + => InputRoot?.FocusManager; + + IPlatformSettings? IInputRoot.PlatformSettings + => InputRoot?.PlatformSettings; + + IInputElement? IInputRoot.PointerOverElement + { + get => InputRoot?.PointerOverElement; + set + { + if (InputRoot is { } inputRoot) + inputRoot.PointerOverElement = value; + } + } + + bool IInputRoot.ShowAccessKeys + { + get => InputRoot?.ShowAccessKeys ?? false; + set + { + if (InputRoot is { } inputRoot) + inputRoot.ShowAccessKeys = value; + } + } + /// <inheritdoc /> internal override Interactive? InteractiveParent => Parent as Interactive; @@ -63,6 +102,12 @@ bool IPopupHost.Topmost public void Show() { _overlayLayer.Children.Add(this); + + if (Content is Visual { IsAttachedToVisualTree: false }) + { + // We need to force a measure pass so any descendants are built, for focus to work. + UpdateLayout(); + } } /// <inheritdoc /> @@ -147,7 +192,7 @@ void IManagedPopupPositionerPopup.MoveAndResize(Point devicePoint, Size virtualS double IManagedPopupPositionerPopup.Scaling => 1; // TODO12: mark PrivateAPI or internal. - [Unstable("PopupHost is consireded an internal API. Use Popup or any Popup-based controls (Flyout, Tooltip) instead.")] + [Unstable("PopupHost is considered an internal API. Use Popup or any Popup-based controls (Flyout, Tooltip) instead.")] public static IPopupHost CreatePopupHost(Visual target, IAvaloniaDependencyResolver? dependencyResolver) { if (TopLevel.GetTopLevel(target) is { } topLevel && topLevel.PlatformImpl?.CreatePopup() is { } popupImpl) diff --git a/src/Avalonia.Controls/TopLevel.cs b/src/Avalonia.Controls/TopLevel.cs index 3d1c0b5b5f9..62c860c7a98 100644 --- a/src/Avalonia.Controls/TopLevel.cs +++ b/src/Avalonia.Controls/TopLevel.cs @@ -471,12 +471,12 @@ void UpdatePlatformImpl() /// <summary> /// Gets the access key handler for the window. /// </summary> - internal IAccessKeyHandler AccessKeyHandler => _accessKeyHandler!; + internal IAccessKeyHandler? AccessKeyHandler => _accessKeyHandler; /// <summary> /// Gets or sets the keyboard navigation handler for the window. /// </summary> - IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler!; + IKeyboardNavigationHandler? IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler; /// <inheritdoc/> IInputElement? IInputRoot.PointerOverElement
diff --git a/tests/Avalonia.Controls.UnitTests/FlyoutTests.cs b/tests/Avalonia.Controls.UnitTests/FlyoutTests.cs index dad8c3b78e7..d748a709a56 100644 --- a/tests/Avalonia.Controls.UnitTests/FlyoutTests.cs +++ b/tests/Avalonia.Controls.UnitTests/FlyoutTests.cs @@ -20,6 +20,8 @@ namespace Avalonia.Controls.UnitTests { public class FlyoutTests { + protected bool UseOverlayPopups { get; set; } + [Fact] public void Opening_Raises_Single_Opening_Event() { @@ -373,10 +375,10 @@ public void ShowMode_Standard_Attemps_Focus_Flyout_Content() window.Show(); button.Focus(); - Assert.True(window.FocusManager.GetFocusedElement() == button); + Assert.Same(button, window.FocusManager!.GetFocusedElement()); button.Flyout.ShowAt(button); Assert.False(button.IsFocused); - Assert.True(window.FocusManager.GetFocusedElement() == flyoutTextBox); + Assert.Same(flyoutTextBox, window.FocusManager!.GetFocusedElement()); } } @@ -640,14 +642,11 @@ public void Setting_FlyoutPresenterClasses_Sets_Classes_On_FlyoutPresenter() } } - private static IDisposable CreateServicesWithFocus() + private IDisposable CreateServicesWithFocus() { return UnitTestApplication.Start(TestServices.StyledWindow.With(windowingPlatform: new MockWindowingPlatform(null, - x => - { - return MockWindowingPlatform.CreatePopupMock(x).Object; - }), + x => UseOverlayPopups ? null : MockWindowingPlatform.CreatePopupMock(x).Object), focusManager: new FocusManager(), keyboardDevice: () => new KeyboardDevice())); } @@ -681,4 +680,10 @@ public class TestFlyout : Flyout public new Popup Popup => base.Popup; } } + + public class OverlayPopupFlyoutTests : FlyoutTests + { + public OverlayPopupFlyoutTests() + => UseOverlayPopups = true; + } } diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs index da37c9ad487..29671f07665 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs @@ -633,46 +633,39 @@ public void Focusable_Controls_In_Popup_Should_Get_Focus() { using (CreateServicesWithFocus()) { - var window = PreparedWindow(); + var window = PreparedWindow(new Panel { Children = { new Slider() }}); - var tb = new TextBox(); - var b = new Button(); - var p = new Popup + var textBox = new TextBox(); + var button = new Button(); + var popup = new Popup { PlacementTarget = window, Child = new StackPanel { Children = { - tb, - b + textBox, + button } } }; - ((ISetLogicalParent)p).SetParent(p.PlacementTarget); - window.Show(); - p.Open(); + ((ISetLogicalParent)popup).SetParent(popup.PlacementTarget); + window.Show(); + popup.Open(); - if(p.Host is OverlayPopupHost host) - { - //Need to measure/arrange for visual children to show up - //in OverlayPopupHost - host.Measure(Size.Infinity); - host.Arrange(new Rect(host.DesiredSize)); - } + button.Focus(); - tb.Focus(); + var inputRoot = Assert.IsAssignableFrom<IInputRoot>(popup.Host); - var focusManager = TopLevel.GetTopLevel(tb)!.FocusManager; - tb = Assert.IsType<TextBox>(focusManager.GetFocusedElement()); + var focusManager = inputRoot.FocusManager!; + Assert.Same(button, focusManager.GetFocusedElement()); //Ensure focus remains in the popup - var nextFocus = KeyboardNavigationHandler.GetNext(tb, NavigationDirection.Next); - - Assert.True(nextFocus == b); + inputRoot.KeyboardNavigationHandler!.Move(focusManager.GetFocusedElement()!, NavigationDirection.Next); + Assert.Same(textBox, focusManager.GetFocusedElement()); - p.Close(); + popup.Close(); } } @@ -1248,7 +1241,6 @@ public void Custom_Placement_Callback_Is_Executed() } } - private static PopupRoot CreateRoot(TopLevel popupParent, IPopupImpl impl = null) { impl ??= popupParent.PlatformImpl.CreatePopup(); @@ -1279,7 +1271,8 @@ private IDisposable CreateServicesWithFocus() return UnitTestApplication.Start(TestServices.StyledWindow.With( windowingPlatform: CreateMockWindowingPlatform(), focusManager: new FocusManager(), - keyboardDevice: () => new KeyboardDevice())); + keyboardDevice: () => new KeyboardDevice(), + keyboardNavigation: () => new KeyboardNavigationHandler())); }
OverlayPopups is True affects the “down” key of the combox ### Describe the bug ![image](https://github.com/user-attachments/assets/79fe1700-1eeb-4b3e-8197-779edffcd6d3) .With(new Win32PlatformOptions { OverlayPopups = true, } 'down' keys not working ### To Reproduce 1. .With(new Win32PlatformOptions { OverlayPopups = true, } 2.'down' keys not working ### Expected behavior when OverlayPopups = true, 'down' keys is working normal![image](https://github.com/user-attachments/assets/79fe1700-1eeb-4b3e-8197-779edffcd6d3) ### Avalonia version 11.1.3 ### OS Windows ### Additional context _No response_
null
2024-10-22T15:45:46Z
0.1
['Avalonia.Controls.UnitTests.FlyoutTests.ShowMode_Standard_Attemps_Focus_Flyout_Content', 'Avalonia.Controls.UnitTests.OverlayPopupFlyoutTests.ShowMode_Standard_Attemps_Focus_Flyout_Content', 'Avalonia.Controls.UnitTests.Primitives.PopupTests.Focusable_Controls_In_Popup_Should_Get_Focus', 'Avalonia.Controls.UnitTests.Primitives.PopupTestsWithPopupRoot.Focusable_Controls_In_Popup_Should_Get_Focus']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17292
9cecb90ba1e681d1783e3a89db4b8d860859550f
diff --git a/api/Avalonia.nupkg.xml b/api/Avalonia.nupkg.xml index 1edc3b5ec25..f6797ada377 100644 --- a/api/Avalonia.nupkg.xml +++ b/api/Avalonia.nupkg.xml @@ -91,4 +91,10 @@ <Left>baseline/netstandard2.0/Avalonia.Controls.dll</Left> <Right>target/netstandard2.0/Avalonia.Controls.dll</Right> </Suppression> + <Suppression> + <DiagnosticId>CP0012</DiagnosticId> + <Target>M:Avalonia.Controls.Button.OnAccessKey(Avalonia.Interactivity.RoutedEventArgs)</Target> + <Left>baseline/netstandard2.0/Avalonia.Controls.dll</Left> + <Right>target/netstandard2.0/Avalonia.Controls.dll</Right> + </Suppression> </Suppressions> \ No newline at end of file diff --git a/samples/ControlCatalog/MainView.xaml b/samples/ControlCatalog/MainView.xaml index 6246c73ce2c..e3eed5fb0e3 100644 --- a/samples/ControlCatalog/MainView.xaml +++ b/samples/ControlCatalog/MainView.xaml @@ -18,6 +18,9 @@ <TabItem Header="Composition"> <pages:CompositionPage /> </TabItem> + <TabItem Header="Accelerator"> + <pages:AcceleratorPage /> + </TabItem> <TabItem Header="Acrylic"> <pages:AcrylicPage /> </TabItem> diff --git a/samples/ControlCatalog/Pages/AcceleratorPage.xaml b/samples/ControlCatalog/Pages/AcceleratorPage.xaml new file mode 100644 index 00000000000..18072ef1c3d --- /dev/null +++ b/samples/ControlCatalog/Pages/AcceleratorPage.xaml @@ -0,0 +1,115 @@ +<UserControl xmlns="https://github.com/avaloniaui" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + x:Class="ControlCatalog.Pages.AcceleratorPage"> + <StackPanel Orientation="Vertical" Spacing="4"> + + <WrapPanel HorizontalAlignment="Left"> + <StackPanel> + <Menu> + <MenuItem Header="_First"> + <MenuItem Header="Standard _Menu Item" InputGesture="Ctrl+A" /> + <MenuItem Header="_Disabled Menu Item" IsEnabled="False" InputGesture="Ctrl+D" /> + <Separator /> + <MenuItem Header="Menu with Sub _Menu"> + <MenuItem Header="Submenu _1" /> + <MenuItem Header="Submenu _2 with Submenu"> + <MenuItem Header="Submenu Level 2" /> + </MenuItem> + <MenuItem Header="Submenu _3 with Submenu Disabled" IsEnabled="False"> + <MenuItem Header="Submenu Level 2" /> + </MenuItem> + </MenuItem> + <MenuItem Header="Menu Item with _Icon" InputGesture="Ctrl+Shift+B"> + <MenuItem.Icon> + <Image Source="/Assets/github_icon.png" /> + </MenuItem.Icon> + </MenuItem> + <MenuItem Header="Menu Item with _Checkbox" ToggleType="CheckBox" /> + </MenuItem> + <MenuItem Header="_Second"> + <MenuItem Header="Second _Menu Item" /> + <MenuItem IsChecked="True" Header="Second _Menu toggle item" ToggleType="CheckBox" /> + <Separator /> + <MenuItem GroupName="A" Header="Radio 1 - group" ToggleType="Radio" /> + <MenuItem IsChecked="True" GroupName="A" Header="Radio 2 - group" ToggleType="Radio" /> + <MenuItem GroupName="A" Header="Radio 3 - group" ToggleType="Radio"> + <MenuItem Header="Radio 4 - group" ToggleType="Radio" GroupName="A" /> + <MenuItem Header="Radio 5 - group" ToggleType="Radio" GroupName="A" /> + </MenuItem> + <Separator /> + <MenuItem Header="Radio 1" ToggleType="Radio" /> + <MenuItem IsChecked="True" Header="Radio 2" ToggleType="Radio" /> + <MenuItem Header="Radio 3" ToggleType="Radio"> + <MenuItem Header="Radio 4" ToggleType="Radio" /> + <MenuItem Header="Radio 5" ToggleType="Radio" /> + </MenuItem> + </MenuItem> + <MenuItem Header="Thir_d"> + <MenuItem Header="About"/> + <MenuItem Header="_Child"> + <MenuItem Header="_Grandchild"/> + </MenuItem> + </MenuItem> + </Menu> + </StackPanel> + + </WrapPanel> + + <StackPanel Spacing="10"> + <TextBlock Classes="h2">Accelerator Support</TextBlock> + + <TabControl Margin="10" BorderBrush="Gray" BorderThickness="1"> + <TabItem Header="_Tab 1"> + <StackPanel> + <TextBlock Margin="5">This is tab 1 content</TextBlock> + <Label Name="Tab1Label1" Target="Tab1TextBox1">_Label Tab1Label1</Label> + <TextBox Name="Tab1TextBox1" Margin="5">This is tab 1 content</TextBox> + <Label Name="Tab1Label2" Target="Tab1TextBox2">Label _Tab1Label2</Label> + <TextBox Name="Tab1TextBox2" Margin="5">This is tab 1 content</TextBox> + </StackPanel> + + </TabItem> + <TabItem Header="T_ab 2"> + <TextBlock Margin="5">This is tab 2 content</TextBlock> + </TabItem> + <TabItem Header="_Tab 3"> + + </TabItem> + <TabItem Header="_Tab 4"> + <TextBlock Margin="5">This is tab 4 content</TextBlock> + </TabItem> + <TabItem Header="_Fab 5"> + <TextBlock Margin="5">This is fab 5 content</TextBlock> + </TabItem> + </TabControl> + </StackPanel> + + + <StackPanel Spacing="10"> + <Label Name="Label0">Label with Ac_celerator 'C' and no Target</Label> + <TextBox Name="TextBox0" Text="Some Text"></TextBox> + + <Label Name="Label1" Target="TextBox1">_Label with Accelerator 'L'</Label> + <TextBox Name="TextBox1" Text="Some Text"></TextBox> + + <Label Name="Label2" Target="TextBox2">La_bel with Accelerator 'B'</Label> + <TextBox Name="TextBox2" Text="Some Text"></TextBox> + + <Label Name="Label3" Target="TextBox3">L_abel with Accelerator 'A'</Label> + <TextBox Name="TextBox3" Text="Some Text"></TextBox> + + <Label Name="Label4" Target="TextBox4">La_bel with Accelerator 'B'</Label> + <TextBox Name="TextBox4" Text="Some Text"></TextBox> + + <Label Name="Label5" Target="TextBox5">_Flabel with Accelerator 'F' (Same as in Menu > File)</Label> + <TextBox Name="TextBox5" Text="Some Text"></TextBox> + + </StackPanel> + + <StackPanel Spacing="10" Orientation="Horizontal"> + <Button Name="Button1">_Button 1</Button> + <Button Name="Button2">_Button 2</Button> + <Button Name="Button3">_Button 3</Button> + </StackPanel> + </StackPanel> +</UserControl> diff --git a/samples/ControlCatalog/Pages/AcceleratorPage.xaml.cs b/samples/ControlCatalog/Pages/AcceleratorPage.xaml.cs new file mode 100644 index 00000000000..0d0d684700c --- /dev/null +++ b/samples/ControlCatalog/Pages/AcceleratorPage.xaml.cs @@ -0,0 +1,18 @@ +using Avalonia.Controls; +using Avalonia.Markup.Xaml; + +namespace ControlCatalog.Pages +{ + public class AcceleratorPage : UserControl + { + public AcceleratorPage() + { + this.InitializeComponent(); + } + + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + } + } +} diff --git a/src/Avalonia.Base/Input/AccessKeyHandler.cs b/src/Avalonia.Base/Input/AccessKeyHandler.cs index fe5e2c46a21..96a4847db8e 100644 --- a/src/Avalonia.Base/Input/AccessKeyHandler.cs +++ b/src/Avalonia.Base/Input/AccessKeyHandler.cs @@ -3,6 +3,7 @@ using System.Linq; using Avalonia.Interactivity; using Avalonia.LogicalTree; +using Avalonia.VisualTree; namespace Avalonia.Input { @@ -11,11 +12,20 @@ namespace Avalonia.Input /// </summary> internal class AccessKeyHandler : IAccessKeyHandler { + /// <summary> + /// Defines the AccessKey attached event. + /// </summary> + public static readonly RoutedEvent<AccessKeyEventArgs> AccessKeyEvent = + RoutedEvent.Register<AccessKeyEventArgs>( + "AccessKey", + RoutingStrategies.Bubble, + typeof(AccessKeyHandler)); + /// <summary> /// Defines the AccessKeyPressed attached event. /// </summary> - public static readonly RoutedEvent<RoutedEventArgs> AccessKeyPressedEvent = - RoutedEvent.Register<RoutedEventArgs>( + public static readonly RoutedEvent<AccessKeyPressedEventArgs> AccessKeyPressedEvent = + RoutedEvent.Register<AccessKeyPressedEventArgs>( "AccessKeyPressed", RoutingStrategies.Bubble, typeof(AccessKeyHandler)); @@ -23,7 +33,9 @@ internal class AccessKeyHandler : IAccessKeyHandler /// <summary> /// The registered access keys. /// </summary> - private readonly List<(string AccessKey, IInputElement Element)> _registered = new(); + private readonly List<AccessKeyRegistration> _registrations = []; + + protected IReadOnlyList<AccessKeyRegistration> Registrations => _registrations; /// <summary> /// The window to which the handler belongs. @@ -48,7 +60,7 @@ internal class AccessKeyHandler : IAccessKeyHandler /// <summary> /// Element to restore following AltKey taking focus. /// </summary> - private IInputElement? _restoreFocusElement; + private WeakReference<IInputElement>? _restoreFocusElementRef; /// <summary> /// The window's main menu. @@ -97,6 +109,12 @@ public void SetOwner(IInputRoot owner) _owner.AddHandler(InputElement.KeyDownEvent, OnKeyDown, RoutingStrategies.Bubble); _owner.AddHandler(InputElement.KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); _owner.AddHandler(InputElement.PointerPressedEvent, OnPreviewPointerPressed, RoutingStrategies.Tunnel); + + OnSetOwner(owner); + } + + protected virtual void OnSetOwner(IInputRoot owner) + { } /// <summary> @@ -106,14 +124,19 @@ public void SetOwner(IInputRoot owner) /// <param name="element">The input element.</param> public void Register(char accessKey, IInputElement element) { - var existing = _registered.FirstOrDefault(x => x.Item2 == element); - - if (existing != default) + var key = NormalizeKey(accessKey.ToString()); + + // remove dead elements with matching key + for (var i = _registrations.Count - 1; i >= 0; i--) { - _registered.Remove(existing); + var registration = _registrations[i]; + if (registration.Key == key && registration.GetInputElement() == null) + { + _registrations.RemoveAt(i); + } } - _registered.Add((accessKey.ToString().ToUpperInvariant(), element)); + _registrations.Add(new AccessKeyRegistration(key, new WeakReference<IInputElement>(element))); } /// <summary> @@ -122,9 +145,15 @@ public void Register(char accessKey, IInputElement element) /// <param name="element">The input element.</param> public void Unregister(IInputElement element) { - foreach (var i in _registered.Where(x => x.Item2 == element).ToList()) + // remove element and all dead elements + for (var i = _registrations.Count - 1; i >= 0; i--) { - _registered.Remove(i); + var registration = _registrations[i]; + var inputElement = registration.GetInputElement(); + if (inputElement == null || inputElement == element) + { + _registrations.RemoveAt(i); + } } } @@ -135,21 +164,29 @@ public void Unregister(IInputElement element) /// <param name="e">The event args.</param> protected virtual void OnPreviewKeyDown(object? sender, KeyEventArgs e) { - if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt) + // if the owner (IInputRoot) does not have the keyboard focus, ignore all keyboard events + // KeyboardDevice.IsKeyboardFocusWithin in case of a PopupRoot seems to only work once, so we created our own + var isFocusWithinOwner = IsFocusWithinOwner(_owner!); + if (!isFocusWithinOwner) + return; + + if (e.Key is Key.LeftAlt or Key.RightAlt) { _altIsDown = true; - if (MainMenu == null || !MainMenu.IsOpen) + if (MainMenu is not { IsOpen: true }) { var focusManager = FocusManager.GetFocusManager(e.Source as IInputElement); - + // TODO: Use FocusScopes to store the current element and restore it when context menu is closed. // Save currently focused input element. - _restoreFocusElement = focusManager?.GetFocusedElement(); + var focusedElement = focusManager?.GetFocusedElement(); + if (focusedElement is not null) + _restoreFocusElementRef = new WeakReference<IInputElement>(focusedElement); // When Alt is pressed without a main menu, or with a closed main menu, show // access key markers in the window (i.e. "_File"). - _owner!.ShowAccessKeys = _showingAccessKeys = true; + _owner!.ShowAccessKeys = _showingAccessKeys = isFocusWithinOwner; } else { @@ -157,8 +194,11 @@ protected virtual void OnPreviewKeyDown(object? sender, KeyEventArgs e) CloseMenu(); _ignoreAltUp = true; - _restoreFocusElement?.Focus(); - _restoreFocusElement = null; + if (_restoreFocusElementRef?.TryGetTarget(out var restoreElement) ?? false) + { + restoreElement.Focus(); + } + _restoreFocusElementRef = null; } } else if (_altIsDown) @@ -174,35 +214,20 @@ protected virtual void OnPreviewKeyDown(object? sender, KeyEventArgs e) /// <param name="e">The event args.</param> protected virtual void OnKeyDown(object? sender, KeyEventArgs e) { - bool menuIsOpen = MainMenu?.IsOpen == true; + // if the owner (IInputRoot) does not have the keyboard focus, ignore all keyboard events + // KeyboardDevice.IsKeyboardFocusWithin in case of a PopupRoot seems to only work once, so we created our own + var isFocusWithinOwner = IsFocusWithinOwner(_owner!); + if (!isFocusWithinOwner) + return; - if (e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) && !e.KeyModifiers.HasAllFlags(KeyModifiers.Control) || menuIsOpen) - { - // If any other key is pressed with the Alt key held down, or the main menu is open, - // find all controls who have registered that access key. - var text = e.Key.ToString(); - var matches = _registered - .Where(x => string.Equals(x.AccessKey, text, StringComparison.OrdinalIgnoreCase) - && x.Element.IsEffectivelyVisible - && x.Element.IsEffectivelyEnabled) - .Select(x => x.Element); - - // If the menu is open, only match controls in the menu's visual tree. - if (menuIsOpen) - { - matches = matches.Where(x => x is not null && ((Visual)MainMenu!).IsLogicalAncestorOf((Visual)x)); - } - - var match = matches.FirstOrDefault(); + if ((!e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) || e.KeyModifiers.HasAllFlags(KeyModifiers.Control)) && + MainMenu?.IsOpen != true) + return; - // If there was a match, raise the AccessKeyPressed event on it. - if (match is not null) - { - match.RaiseEvent(new RoutedEventArgs(AccessKeyPressedEvent)); - } - } + e.Handled = ProcessKey(e.Key.ToString(), e.Source as IInputElement); } + /// <summary> /// Handles the Alt/F10 keys being released in the window. /// </summary> @@ -255,5 +280,302 @@ private void MainMenuClosed(object? sender, EventArgs e) { _owner!.ShowAccessKeys = false; } + + /// <summary> + /// Processes the given key for the element's targets + /// </summary> + /// <param name="key">The access key to process.</param> + /// <param name="element">The element to get the targets which are in scope.</param> + /// <returns>If there matches <c>true</c>, otherwise <c>false</c>.</returns> + protected bool ProcessKey(string key, IInputElement? element) + { + key = NormalizeKey(key); + var senderInfo = GetTargetForElement(element, key); + // Find the possible targets matching the access key + var targets = SortByHierarchy(GetTargetsForKey(key, element, senderInfo)); + var result = ProcessKey(key, targets); + return result != ProcessKeyResult.NoMatch; + } + + private static string NormalizeKey(string key) => key.ToUpperInvariant(); + + private static ProcessKeyResult ProcessKey(string key, List<IInputElement> targets) + { + if (!targets.Any()) + return ProcessKeyResult.NoMatch; + + var isSingleTarget = true; + var lastWasFocused = false; + + IInputElement? effectiveTarget = null; + + var chosenIndex = 0; + for (var i = 0; i < targets.Count; i++) + { + var target = targets[i]; + + if (!IsTargetable(target)) + continue; + + if (effectiveTarget == null) + { + effectiveTarget = target; + chosenIndex = i; + } + else + { + if (lastWasFocused) + { + effectiveTarget = target; + chosenIndex = i; + } + + isSingleTarget = false; + } + + lastWasFocused = target.IsFocused; + } + + if (effectiveTarget == null) + return ProcessKeyResult.NoMatch; + + var args = new AccessKeyEventArgs(key, isMultiple: !isSingleTarget); + effectiveTarget.RaiseEvent(args); + + return chosenIndex == targets.Count - 1 ? ProcessKeyResult.LastMatch : ProcessKeyResult.MoreMatches; + } + + private List<IInputElement> GetTargetsForKey(string key, IInputElement? sender, + AccessKeyInformation senderInfo) + { + var possibleElements = CopyMatchingAndPurgeDead(key); + + if (!possibleElements.Any()) + return possibleElements; + + var finalTargets = new List<IInputElement>(1); + + // Go through all the possible elements, find the interesting candidates + foreach (var element in possibleElements) + { + if (element != sender) + { + if (!IsTargetable(element)) + continue; + + var elementInfo = GetTargetForElement(element, key); + if (elementInfo.Target == null) + continue; + + finalTargets.Add(elementInfo.Target); + } + else + { + // This is the same element that sent the event so it must be in the same scope. + // Just add it to the final targets + if (senderInfo.Target == null) + continue; + + finalTargets.Add(senderInfo.Target); + } + } + + return finalTargets; + } + + private static bool IsTargetable(IInputElement element) => + element is { IsEffectivelyEnabled: true, IsEffectivelyVisible: true }; + + private List<IInputElement> CopyMatchingAndPurgeDead(string key) + { + var matches = new List<IInputElement>(_registrations.Count); + + // collect live elements with matching key and remove dead elements + for (var i = _registrations.Count - 1; i >= 0; i--) + { + var registration = _registrations[i]; + var inputElement = registration.GetInputElement(); + if (inputElement != null) + { + if (registration.Key == key) + { + matches.Add(inputElement); + } + } + else + { + _registrations.RemoveAt(i); + } + } + + // since we collected the elements when iterating from back to front + // we need to reverse them to ensure the original order + matches.Reverse(); + + return matches; + } + + /// <summary> + /// Returns targeting information for the given element. + /// </summary> + /// <param name="element"></param> + /// <param name="key"></param> + /// <returns>AccessKeyInformation with target for the access key.</returns> + private static AccessKeyInformation GetTargetForElement(IInputElement? element, string key) + { + var info = new AccessKeyInformation(); + if (element == null) + return info; + + var args = new AccessKeyPressedEventArgs(key); + element.RaiseEvent(args); + info.Target = args.Target; + + return info; + } + + /// <summary> + /// Checks if the focused element is a descendent of the owner. + /// </summary> + /// <param name="owner">The owner to check.</param> + /// <returns>If focused element is decendant of owner <c>true</c>, otherwise <c>false</c>. </returns> + private static bool IsFocusWithinOwner(IInputRoot owner) + { + var focusedElement = KeyboardDevice.Instance?.FocusedElement; + if (focusedElement is not InputElement inputElement) + return false; + + var isAncestorOf = owner is Visual root && root.IsVisualAncestorOf(inputElement); + return isAncestorOf; + } + + /// <summary> + /// Sorts the list of targets according to logical ancestors in the hierarchy + /// so that child elements, for example within in the content of a tab, + /// are processed before the next parent item i.e. the next tab item. + /// </summary> + private static List<IInputElement> SortByHierarchy(List<IInputElement> targets) + { + // bail out, if there are no targets to sort + if (targets.Count <= 1) + return targets; + + var sorted = new List<IInputElement>(targets.Count); + var queue = new Queue<IInputElement>(targets); + while (queue.Count > 0) + { + var element = queue.Dequeue(); + + // if the element was already added, do nothing + if (sorted.Contains(element)) + continue; + + // add the element itself + sorted.Add(element); + + // if the element is not a potential parent, do nothing + if (element is not ILogical parentElement) + continue; + + // add all descendants of the element + sorted.AddRange(queue + .Where(child => parentElement + .IsLogicalAncestorOf(child as ILogical))); + } + return sorted; + } + + private enum ProcessKeyResult + { + NoMatch, + MoreMatches, + LastMatch + } + + private struct AccessKeyInformation + { + public IInputElement? Target { get; set; } + } + } + + /// <summary> + /// The inputs to an AccessKeyPressedEventHandler + /// </summary> + internal class AccessKeyPressedEventArgs : RoutedEventArgs + { + /// <summary> + /// The constructor for AccessKeyPressed event args + /// </summary> + public AccessKeyPressedEventArgs() + { + RoutedEvent = AccessKeyHandler.AccessKeyPressedEvent; + Key = null; + } + + /// <summary> + /// Constructor for AccessKeyPressed event args + /// </summary> + /// <param name="key"></param> + public AccessKeyPressedEventArgs(string key) : this() + { + RoutedEvent = AccessKeyHandler.AccessKeyPressedEvent; + Key = key; + } + + /// <summary> + /// Target element for the element that raised this event. + /// </summary> + /// <value></value> + public IInputElement? Target { get; set; } + + /// <summary> + /// Key that was pressed + /// </summary> + /// <value></value> + public string? Key { get; } + } + + /// <summary> + /// Information pertaining to when the access key associated with an element is pressed + /// </summary> + internal class AccessKeyEventArgs : RoutedEventArgs + { + /// <summary> + /// Constructor + /// </summary> + internal AccessKeyEventArgs(string key, bool isMultiple) + { + RoutedEvent = AccessKeyHandler.AccessKeyEvent; + + Key = key; + IsMultiple = isMultiple; + } + + /// <summary> + /// The key that was pressed which invoked this access key + /// </summary> + /// <value></value> + public string Key { get; } + + /// <summary> + /// Were there other elements which are also invoked by this key + /// </summary> + /// <value></value> + public bool IsMultiple { get; } + } + + internal class AccessKeyRegistration + { + private readonly WeakReference<IInputElement> _target; + public string Key { get; } + + public AccessKeyRegistration(string key, WeakReference<IInputElement> target) + { + _target = target; + Key = key; + } + + public IInputElement? GetInputElement() => + _target.TryGetTarget(out var target) ? target : null; } } diff --git a/src/Avalonia.Base/Input/InputElement.cs b/src/Avalonia.Base/Input/InputElement.cs index bdb65001687..5da27c68042 100644 --- a/src/Avalonia.Base/Input/InputElement.cs +++ b/src/Avalonia.Base/Input/InputElement.cs @@ -1,17 +1,15 @@ +#nullable enable + using System; using System.Collections.Generic; -using System.Linq; using Avalonia.Controls; using Avalonia.Controls.Metadata; -using Avalonia.Data; using Avalonia.Input.GestureRecognizers; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Reactive; using Avalonia.VisualTree; -#nullable enable - namespace Avalonia.Input { /// <summary> @@ -231,6 +229,10 @@ static InputElement() PointerPressedEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerPressed(e), handledEventsToo: true); PointerReleasedEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerReleased(e), handledEventsToo: true); PointerCaptureLostEvent.AddClassHandler<InputElement>((x, e) => x.OnGesturePointerCaptureLost(e), handledEventsToo: true); + + + // Access Key Handling + AccessKeyHandler.AccessKeyEvent.AddClassHandler<InputElement>((x, e) => x.OnAccessKey(e)); } public InputElement() @@ -282,7 +284,7 @@ public event EventHandler<TextInputEventArgs>? TextInput add { AddHandler(TextInputEvent, value); } remove { RemoveHandler(TextInputEvent, value); } } - + /// <summary> /// Occurs when an input element gains input focus and input method is looking for the corresponding client /// </summary> @@ -346,7 +348,7 @@ public event EventHandler<PointerCaptureLostEventArgs>? PointerCaptureLost add => AddHandler(PointerCaptureLostEvent, value); remove => RemoveHandler(PointerCaptureLostEvent, value); } - + /// <summary> /// Occurs when the mouse is scrolled over the control. /// </summary> @@ -355,7 +357,7 @@ public event EventHandler<PointerWheelEventArgs>? PointerWheelChanged add { AddHandler(PointerWheelChangedEvent, value); } remove { RemoveHandler(PointerWheelChangedEvent, value); } } - + /// <summary> /// Occurs when a tap gesture occurs on the control. /// </summary> @@ -364,7 +366,7 @@ public event EventHandler<TappedEventArgs>? Tapped add { AddHandler(TappedEvent, value); } remove { RemoveHandler(TappedEvent, value); } } - + /// <summary> /// Occurs when a hold gesture occurs on the control. /// </summary> @@ -409,7 +411,7 @@ public Cursor? Cursor get { return GetValue(CursorProperty); } set { SetValue(CursorProperty, value); } } - + /// <summary> /// Gets a value indicating whether keyboard focus is anywhere within the element or its visual tree child elements. /// </summary> @@ -515,6 +517,17 @@ protected override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventAr } } + /// <summary> + /// This method is used to execute the action on an effective IInputElement when a corresponding access key has been invoked. + /// By default, the Focus() method is invoked with the NavigationMethod.Tab to indicate a visual focus adorner. + /// Overwrite this method if other methods or additional functionality is needed when an item should receive the focus. + /// </summary> + /// <param name="e">AccessKeyEventArgs are passed on to indicate if there are multiple matches or not.</param> + protected virtual void OnAccessKey(RoutedEventArgs e) + { + Focus(NavigationMethod.Tab); + } + /// <inheritdoc/> protected override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { diff --git a/src/Avalonia.Controls/Button.cs b/src/Avalonia.Controls/Button.cs index 614847ee4e8..9673eaadf75 100644 --- a/src/Avalonia.Controls/Button.cs +++ b/src/Avalonia.Controls/Button.cs @@ -104,7 +104,7 @@ public class Button : ContentControl, ICommandSource, IClickableControl static Button() { FocusableProperty.OverrideDefaultValue(typeof(Button), true); - AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Button>((lbl, args) => lbl.OnAccessKey(args)); + AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Button>(OnAccessKeyPressed); } /// <summary> @@ -199,7 +199,7 @@ public FlyoutBase? Flyout /// <inheritdoc/> protected override bool IsEnabledCore => base.IsEnabledCore && _commandCanExecute; - + /// <inheritdoc/> protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { @@ -278,7 +278,18 @@ protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs } } - protected virtual void OnAccessKey(RoutedEventArgs e) => OnClick(); + /// <inheritdoc /> + protected override void OnAccessKey(RoutedEventArgs e) + { + if (e is AccessKeyEventArgs { IsMultiple: true }) + { + base.OnAccessKey(e); + } + else + { + OnClick(); + } + } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) @@ -563,6 +574,14 @@ protected override void UpdateDataValidation( internal void PerformClick() => OnClick(); + private static void OnAccessKeyPressed(Button sender, AccessKeyPressedEventArgs e) + { + if (e.Handled || e.Target is not null) + return; + e.Target = sender; + e.Handled = true; + } + /// <summary> /// Called when the <see cref="ICommand.CanExecuteChanged"/> event fires. /// </summary> diff --git a/src/Avalonia.Controls/Label.cs b/src/Avalonia.Controls/Label.cs index 94ea66c4c1b..468c98ffce7 100644 --- a/src/Avalonia.Controls/Label.cs +++ b/src/Avalonia.Controls/Label.cs @@ -28,9 +28,8 @@ public IInputElement? Target static Label() { - AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Label>((lbl, args) => lbl.LabelActivated(args)); - // IsTabStopProperty.OverrideDefaultValue<Label>(false) - FocusableProperty.OverrideDefaultValue<Label>(false); + AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Label>(OnAccessKeyPressed); + IsTabStopProperty.OverrideDefaultValue<Label>(false); } /// <summary> @@ -40,13 +39,11 @@ public Label() { } - /// <summary> - /// Method which focuses <see cref="Target"/> input element - /// </summary> - private void LabelActivated(RoutedEventArgs args) + + /// <inheritdoc /> + protected override void OnAccessKey(RoutedEventArgs e) { - Target?.Focus(); - args.Handled = Target != null; + LabelActivated(e); } /// <summary> @@ -62,9 +59,25 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) base.OnPointerPressed(e); } + /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() { return new LabelAutomationPeer(this); } + + private void LabelActivated(RoutedEventArgs e) + { + Target?.Focus(); + e.Handled = Target != null; + } + + private static void OnAccessKeyPressed(Label label, AccessKeyPressedEventArgs e) + { + if (e is not { Handled: false, Target: null }) + return; + + e.Target = label.Target; + e.Handled = true; + } } } diff --git a/src/Avalonia.Controls/Menu.cs b/src/Avalonia.Controls/Menu.cs index 6a8cf2b5150..56137287a0f 100644 --- a/src/Avalonia.Controls/Menu.cs +++ b/src/Avalonia.Controls/Menu.cs @@ -40,8 +40,9 @@ static Menu() KeyboardNavigationMode.Once); AutomationProperties.AccessibilityViewProperty.OverrideDefaultValue<Menu>(AccessibilityView.Control); AutomationProperties.ControlTypeOverrideProperty.OverrideDefaultValue<Menu>(AutomationControlType.Menu); + AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<Menu>(OnAccessKeyPressed); } - + /// <inheritdoc/> public override void Close() { @@ -104,5 +105,14 @@ protected internal override void PrepareContainerForItemOverride(Control element if ((element as MenuItem)?.ItemContainerTheme == ItemContainerTheme) element.ClearValue(ItemContainerThemeProperty); } + + private static void OnAccessKeyPressed(Menu sender, AccessKeyPressedEventArgs e) + { + if (e.Handled || e.Source is not StyledElement target) + return; + + e.Target = DefaultMenuInteractionHandler.GetMenuItemCore(target); + e.Handled = true; + } } } diff --git a/src/Avalonia.Controls/MenuItem.cs b/src/Avalonia.Controls/MenuItem.cs index 13cd78f2fce..8cfc40bf0f2 100644 --- a/src/Avalonia.Controls/MenuItem.cs +++ b/src/Avalonia.Controls/MenuItem.cs @@ -143,6 +143,7 @@ static MenuItem() ClickEvent.AddClassHandler<MenuItem>((x, e) => x.OnClick(e)); SubmenuOpenedEvent.AddClassHandler<MenuItem>((x, e) => x.OnSubmenuOpened(e)); AutomationProperties.IsOffscreenBehaviorProperty.OverrideDefaultValue<MenuItem>(IsOffscreenBehavior.FromClip); + AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<MenuItem>(OnAccessKeyPressed); } public MenuItem() @@ -565,7 +566,7 @@ protected override void UpdateDataValidation( } } } - + /// <summary> /// Closes all submenus of the menu item. /// </summary> @@ -603,6 +604,15 @@ private static void CommandChanged(AvaloniaPropertyChangedEventArgs e) } } + + private static void OnAccessKeyPressed(MenuItem sender, AccessKeyPressedEventArgs e) + { + if (e is not { Handled: false, Target: null }) + return; + + e.Target = sender; + e.Handled = true; + } /// <summary> /// Called when the <see cref="CommandParameter"/> property changes. diff --git a/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs b/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs index e1e7779f17c..5571773a9de 100644 --- a/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs +++ b/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs @@ -1,82 +1,17 @@ using System; -using System.Collections.Generic; using System.Linq; using Avalonia.Input; -using Avalonia.Interactivity; namespace Avalonia.Controls { /// <summary> /// Handles access keys within a <see cref="MenuItem"/> /// </summary> - internal class MenuItemAccessKeyHandler : IAccessKeyHandler + internal class MenuItemAccessKeyHandler : AccessKeyHandler { - /// <summary> - /// The registered access keys. - /// </summary> - private readonly List<(string AccessKey, IInputElement Element)> _registered = new(); - - /// <summary> - /// The window to which the handler belongs. - /// </summary> - private IInputRoot? _owner; - - /// <summary> - /// Gets or sets the window's main menu. - /// </summary> - /// <remarks> - /// This property is ignored as a menu item cannot have a main menu. - /// </remarks> - public IMainMenu? MainMenu { get; set; } - - /// <summary> - /// Sets the owner of the access key handler. - /// </summary> - /// <param name="owner">The owner.</param> - /// <remarks> - /// This method can only be called once, typically by the owner itself on creation. - /// </remarks> - public void SetOwner(IInputRoot owner) - { - _ = owner ?? throw new ArgumentNullException(nameof(owner)); - - if (_owner != null) - { - throw new InvalidOperationException("AccessKeyHandler owner has already been set."); - } - - _owner = owner; - - _owner.AddHandler(InputElement.TextInputEvent, OnTextInput); - } - - /// <summary> - /// Registers an input element to be associated with an access key. - /// </summary> - /// <param name="accessKey">The access key.</param> - /// <param name="element">The input element.</param> - public void Register(char accessKey, IInputElement element) - { - var existing = _registered.FirstOrDefault(x => x.Item2 == element); - - if (existing != default) - { - _registered.Remove(existing); - } - - _registered.Add((accessKey.ToString().ToUpperInvariant(), element)); - } - - /// <summary> - /// Unregisters the access keys associated with the input element. - /// </summary> - /// <param name="element">The input element.</param> - public void Unregister(IInputElement element) + protected override void OnSetOwner(IInputRoot owner) { - foreach (var i in _registered.Where(x => x.Item2 == element).ToList()) - { - _registered.Remove(i); - } + owner.AddHandler(InputElement.TextInputEvent, OnTextInput); } /// <summary> @@ -86,17 +21,17 @@ public void Unregister(IInputElement element) /// <param name="e">The event args.</param> protected virtual void OnTextInput(object? sender, TextInputEventArgs e) { - if (!string.IsNullOrWhiteSpace(e.Text)) - { - var text = e.Text; - var focus = _registered - .FirstOrDefault(x => string.Equals(x.AccessKey, text, StringComparison.OrdinalIgnoreCase) - && x.Element.IsEffectivelyVisible).Element; - - focus?.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); - - e.Handled = true; - } + if (string.IsNullOrWhiteSpace(e.Text)) + return; + + var key = e.Text; + var registration = Registrations + .FirstOrDefault(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)); + + if (registration == null) + return; + + e.Handled = ProcessKey(key, registration.GetInputElement()); } } } diff --git a/src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs b/src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs index c4ee65ab133..8b699e2df7f 100644 --- a/src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs +++ b/src/Avalonia.Controls/Platform/DefaultMenuInteractionHandler.cs @@ -80,12 +80,16 @@ protected internal virtual void KeyDown(object? sender, KeyEventArgs e) protected internal virtual void AccessKeyPressed(object? sender, RoutedEventArgs e) { var item = GetMenuItemCore(e.Source as Control); + if (item is null) + return; - if (item == null) + if (e is AccessKeyEventArgs { IsMultiple: true }) { + // in case we have multiple matches, only focus item and bail + item.Focus(NavigationMethod.Tab); return; } - + if (item.HasSubMenu && item.IsEffectivelyEnabled) { Open(item, true); @@ -290,7 +294,7 @@ internal void AttachCore(IMenu menu) Menu.KeyDown += KeyDown; Menu.PointerPressed += PointerPressed; Menu.PointerReleased += PointerReleased; - Menu.AddHandler(AccessKeyHandler.AccessKeyPressedEvent, AccessKeyPressed); + Menu.AddHandler(AccessKeyHandler.AccessKeyEvent, AccessKeyPressed); Menu.AddHandler(MenuBase.OpenedEvent, MenuOpened); Menu.AddHandler(MenuItem.PointerEnteredItemEvent, PointerEntered); Menu.AddHandler(MenuItem.PointerExitedItemEvent, PointerExited); @@ -332,7 +336,7 @@ internal void DetachCore(IMenu menu) Menu.KeyDown -= KeyDown; Menu.PointerPressed -= PointerPressed; Menu.PointerReleased -= PointerReleased; - Menu.RemoveHandler(AccessKeyHandler.AccessKeyPressedEvent, AccessKeyPressed); + Menu.RemoveHandler(AccessKeyHandler.AccessKeyEvent, AccessKeyPressed); Menu.RemoveHandler(MenuBase.OpenedEvent, MenuOpened); Menu.RemoveHandler(MenuItem.PointerEnteredItemEvent, PointerEntered); Menu.RemoveHandler(MenuItem.PointerExitedItemEvent, PointerExited); diff --git a/src/Avalonia.Controls/TabItem.cs b/src/Avalonia.Controls/TabItem.cs index 0a0c3f5fc5c..1b2ab6505bc 100644 --- a/src/Avalonia.Controls/TabItem.cs +++ b/src/Avalonia.Controls/TabItem.cs @@ -40,7 +40,7 @@ static TabItem() DataContextProperty.Changed.AddClassHandler<TabItem>((x, e) => x.UpdateHeader(e)); AutomationProperties.ControlTypeOverrideProperty.OverrideDefaultValue<TabItem>(AutomationControlType.TabItem); AutomationProperties.IsOffscreenBehaviorProperty.OverrideDefaultValue<TabItem>(IsOffscreenBehavior.FromClip); - AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<TabItem>((tabItem, args) => tabItem.TabItemActivated(args)); + AccessKeyHandler.AccessKeyPressedEvent.AddClassHandler<TabItem>(OnAccessKeyPressed); } /// <summary> @@ -61,13 +61,31 @@ public bool IsSelected set => SetValue(IsSelectedProperty, value); } + /// <inheritdoc /> + protected override void OnAccessKey(RoutedEventArgs e) + { + Focus(); + SetCurrentValue(IsSelectedProperty, true); + e.Handled = true; + } + protected override AutomationPeer OnCreateAutomationPeer() => new ListItemAutomationPeer(this); + [Obsolete("Owner manages its children properties by itself")] protected void SubscribeToOwnerProperties(AvaloniaObject owner) { } + private static void OnAccessKeyPressed(TabItem tabItem, AccessKeyPressedEventArgs e) + { + if (e.Handled || (e.Target != null && tabItem.IsSelected)) + return; + + e.Target = tabItem; + e.Handled = true; + } + private void UpdateHeader(AvaloniaPropertyChangedEventArgs obj) { if (Header == null) @@ -95,11 +113,5 @@ private void UpdateHeader(AvaloniaPropertyChangedEventArgs obj) } } } - - private void TabItemActivated(RoutedEventArgs args) - { - SetCurrentValue(IsSelectedProperty, true); - args.Handled = true; - } } }
diff --git a/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs b/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs index ed1061e85a9..0fd1e318661 100644 --- a/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs +++ b/tests/Avalonia.Base.UnitTests/Input/AccessKeyHandlerTests.cs @@ -142,68 +142,85 @@ public void Should_Raise_Key_Events_For_Registered_Access_Key() } [Fact] - public void Should_Raise_AccessKeyPressed_For_Registered_Access_Key() + public void Should_Raise_AccessKey_For_Registered_Access_Key() { - var button = new Button(); - var root = new TestRoot(button); - var target = new AccessKeyHandler(); - var raised = 0; + using (UnitTestApplication.Start(TestServices.RealFocus)) + { + var button = new Button(); + var root = new TestRoot(button); + var target = new AccessKeyHandler(); + var raised = 0; - target.SetOwner(root); - target.Register('A', button); - button.AddHandler(AccessKeyHandler.AccessKeyPressedEvent, (s, e) => ++raised); + KeyboardDevice.Instance?.SetFocusedElement(button, NavigationMethod.Unspecified, KeyModifiers.None); - KeyDown(root, Key.LeftAlt); - Assert.Equal(0, raised); + target.SetOwner(root); + target.Register('A', button); + button.AddHandler(AccessKeyHandler.AccessKeyEvent, (s, e) => ++raised); - KeyDown(root, Key.A, KeyModifiers.Alt); - Assert.Equal(1, raised); + KeyDown(root, Key.LeftAlt); + Assert.Equal(0, raised); - KeyUp(root, Key.A, KeyModifiers.Alt); - KeyUp(root, Key.LeftAlt); + KeyDown(root, Key.A, KeyModifiers.Alt); + Assert.Equal(1, raised); - Assert.Equal(1, raised); + KeyUp(root, Key.A, KeyModifiers.Alt); + KeyUp(root, Key.LeftAlt); + + Assert.Equal(1, raised); + } } - [Fact] - public void Should_Not_Raise_AccessKeyPressed_For_Registered_Access_Key_When_Not_Effectively_Enabled() + [Theory] + [InlineData(false, 0)] + [InlineData(true, 1)] + public void Should_Raise_AccessKey_For_Registered_Access_Key_When_Effectively_Enabled(bool enabled, int expected) { - var button = new Button(); - var root = new TestRoot(button) { IsEnabled = false }; - var target = new AccessKeyHandler(); - var raised = 0; - - target.SetOwner(root); - target.Register('A', button); - button.AddHandler(AccessKeyHandler.AccessKeyPressedEvent, (s, e) => ++raised); - - KeyDown(root, Key.LeftAlt); - Assert.Equal(0, raised); - - KeyDown(root, Key.A, KeyModifiers.Alt); - Assert.Equal(0, raised); - - KeyUp(root, Key.A, KeyModifiers.Alt); - KeyUp(root, Key.LeftAlt); - - Assert.Equal(0, raised); + using (UnitTestApplication.Start(TestServices.RealFocus)) + { + var button = new Button(); + var root = new TestRoot(button) { IsEnabled = enabled }; + var target = new AccessKeyHandler(); + var raised = 0; + + KeyboardDevice.Instance?.SetFocusedElement(button, NavigationMethod.Unspecified, KeyModifiers.None); + + target.SetOwner(root); + target.Register('A', button); + button.AddHandler(AccessKeyHandler.AccessKeyEvent, (s, e) => ++raised); + + KeyDown(root, Key.LeftAlt); + Assert.Equal(0, raised); + + KeyDown(root, Key.A, KeyModifiers.Alt); + Assert.Equal(expected, raised); + + KeyUp(root, Key.A, KeyModifiers.Alt); + KeyUp(root, Key.LeftAlt); + Assert.Equal(expected, raised); + } } [Fact] public void Should_Open_MainMenu_On_Alt_KeyUp() { - var root = new TestRoot(); - var target = new AccessKeyHandler(); - var menu = new Mock<IMainMenu>(); - - target.SetOwner(root); - target.MainMenu = menu.Object; - - KeyDown(root, Key.LeftAlt); - menu.Verify(x => x.Open(), Times.Never); - - KeyUp(root, Key.LeftAlt); - menu.Verify(x => x.Open(), Times.Once); + using (UnitTestApplication.Start(TestServices.RealFocus)) + { + var target = new AccessKeyHandler(); + var menu = new FakeMenu(); + var root = new TestRoot(menu); + + KeyboardDevice.Instance?.SetFocusedElement(menu, NavigationMethod.Unspecified, + KeyModifiers.None); + + target.SetOwner(root); + target.MainMenu = menu; + + KeyDown(root, Key.LeftAlt); + Assert.Equal(0, menu.TimesOpenCalled); + + KeyUp(root, Key.LeftAlt); + Assert.Equal(1, menu.TimesOpenCalled); + } } private static void KeyDown(IInputElement target, Key key, KeyModifiers modifiers = KeyModifiers.None) @@ -225,5 +242,15 @@ private static void KeyUp(IInputElement target, Key key, KeyModifiers modifiers KeyModifiers = modifiers, }); } + + class FakeMenu : Menu + { + public int TimesOpenCalled { get; set; } + + public override void Open() + { + TimesOpenCalled++; + } + } } } diff --git a/tests/Avalonia.Base.UnitTests/Input/InputElement_Focus.cs b/tests/Avalonia.Base.UnitTests/Input/InputElement_Focus.cs index 0bc3114665c..85d2be077f9 100644 --- a/tests/Avalonia.Base.UnitTests/Input/InputElement_Focus.cs +++ b/tests/Avalonia.Base.UnitTests/Input/InputElement_Focus.cs @@ -1,7 +1,5 @@ -using System; using Avalonia.Controls; using Avalonia.Input; -using Avalonia.Interactivity; using Avalonia.UnitTests; using Xunit; @@ -177,10 +175,10 @@ public void Focus_Should_Not_Get_Restored_To_Enabled_Control() }; target.Focus(); - target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); + target.RaiseEvent(new AccessKeyEventArgs("b1", false)); Assert.False(target.IsEnabled); Assert.False(target.IsFocused); - target1.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); + target1.RaiseEvent(new AccessKeyEventArgs("b2", false)); Assert.True(target.IsEnabled); Assert.False(target.IsFocused); } diff --git a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs index e3b974491aa..9d4a90a8124 100644 --- a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs @@ -293,9 +293,9 @@ public void Button_Invokes_CanExecute_When_CommandParameter_Changed() var raised = 0; target.Click += (s, e) => ++raised; - - target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); - + + target.RaiseEvent(new AccessKeyEventArgs("b", false)); + Assert.Equal(1, raised); } @@ -304,7 +304,12 @@ public void Raises_Click_When_AccessKey_Raised() { var raised = 0; var ah = new AccessKeyHandler(); - using var app = UnitTestApplication.Start(TestServices.StyledWindow.With(accessKeyHandler: ah)); + var kd = new KeyboardDevice(); + using var app = UnitTestApplication.Start(TestServices.StyledWindow + .With( + accessKeyHandler: ah, + keyboardDevice: () => kd) + ); var impl = CreateMockTopLevelImpl(); var command = new TestCommand(p => p is bool value && value, _ => raised++); @@ -329,6 +334,8 @@ public void Raises_Click_When_AccessKey_Raised() }) }, }; + kd.SetFocusedElement(target, NavigationMethod.Unspecified, KeyModifiers.None); + root.ApplyTemplate(); root.Presenter.UpdateChild(); @@ -349,7 +356,7 @@ public void Raises_Click_When_AccessKey_Raised() RaiseAccessKey(root, accessKey); Assert.Equal(1, raised); - + static FuncControlTemplate<TestTopLevel> CreateTemplate() { return new FuncControlTemplate<TestTopLevel>((x, scope) => @@ -409,7 +416,7 @@ public void Button_Invokes_Doesnt_Execute_When_Button_Disabled() target.IsEnabled = false; target.Click += (s, e) => ++raised; - target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); + target.RaiseEvent(new AccessKeyEventArgs("b", false)); Assert.Equal(0, raised); } diff --git a/tests/Avalonia.Controls.UnitTests/TabControlTests.cs b/tests/Avalonia.Controls.UnitTests/TabControlTests.cs index 4189ecd9de0..a4cc2b4f6b0 100644 --- a/tests/Avalonia.Controls.UnitTests/TabControlTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TabControlTests.cs @@ -724,7 +724,12 @@ public void TabItem_TabStripPlacement_Should_Be_Correctly_Set_For_New_Items() public void Should_TabControl_Recognizes_AccessKey(Key accessKey, int selectedTabIndex) { var ah = new AccessKeyHandler(); - using (UnitTestApplication.Start(TestServices.StyledWindow.With(accessKeyHandler: ah))) + var kd = new KeyboardDevice(); + using (UnitTestApplication.Start(TestServices.StyledWindow + .With( + accessKeyHandler: ah, + keyboardDevice: () => kd) + )) { var impl = CreateMockTopLevelImpl(); @@ -742,7 +747,8 @@ public void Should_TabControl_Recognizes_AccessKey(Key accessKey, int selectedTa new TabItem { Header = "_Disabled", IsEnabled = false }, } }; - + kd.SetFocusedElement((TabItem)tabControl.Items[selectedTabIndex], NavigationMethod.Unspecified, KeyModifiers.None); + var root = new TestTopLevel(impl.Object) { Template = CreateTemplate(), diff --git a/tests/Avalonia.Markup.UnitTests/Data/BindingTests_Method.cs b/tests/Avalonia.Markup.UnitTests/Data/BindingTests_Method.cs index e613a178d5a..4b2c2494af6 100644 --- a/tests/Avalonia.Markup.UnitTests/Data/BindingTests_Method.cs +++ b/tests/Avalonia.Markup.UnitTests/Data/BindingTests_Method.cs @@ -17,7 +17,7 @@ public void Binding_To_Private_Methods_Shouldnt_Work() DataContext = vm, [!Button.CommandProperty] = new Binding("MyMethod"), }; - target.RaiseEvent(new RoutedEventArgs(AccessKeyHandler.AccessKeyPressedEvent)); + target.RaiseEvent(new AccessKeyEventArgs("b", false)); Assert.False(vm.IsSet); }
Duplicate Accelerator Keys don't work for nested MenuItem Headers **Describe the bug** ```xaml <Menu> <MenuItem Header="_File"> <MenuItem Header="_New Project"/> <MenuItem Header="_Open Project"/> <MenuItem Header="_Save Project"/> </MenuItem> <MenuItem Header="_Edit"> <MenuItem Header="_Find"/> <MenuItem Header="_Replace"/> </MenuItem> </Menu> ``` This is a very simple Menu that you can find in most editor-like applications. This is how I expect it to work: ![Rider](https://user-images.githubusercontent.com/16577545/145012338-3b5002dc-b673-489c-82bb-6529e21ef23c.gif) Both `File` and `Find` start with `F` but they are not on the same level, `Find` is nested inside the `Edit` menu meaning you have to do `Alt+E+F` to get to `Find`. Avalonia does not work this way: ![Avalonia](https://user-images.githubusercontent.com/16577545/145012904-45532663-3a1a-4832-8e5f-3f78068ad860.gif) As you can see, if the `Edit` menu is open and I press `F`, I expect it to select the `Find` sub-menu item but instead it goes to `File`. **Desktop (please complete the following information):** - OS: Windows 10 - Version 0.10.10
Looking a bit around in the code I guess you'd have to change the [`MenuItemAccessKeyHandler`](https://github.com/AvaloniaUI/Avalonia/blob/master/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs) and [`AccessText`](https://github.com/AvaloniaUI/Avalonia/blob/master/src/Avalonia.Controls/Primitives/AccessText.cs) to be aware of what parent `MenuItem` they are in as they currently only work with `char accessKey`: https://github.com/AvaloniaUI/Avalonia/blob/0ca2f3d5db0d4c5a5a35782e396d40e2ac98f87a/src/Avalonia.Controls/MenuItemAccessKeyHandler.cs#L58-L68 I noticed that this is still a bug in Avalonia - is there a work-around for this?
2024-10-16T13:02:54Z
0.1
['Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_AccessKey_For_Registered_Access_Key_When_Effectively_Enabled']
['Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Raise_AccessKey_For_Registered_Access_Key', 'Avalonia.Base.UnitTests.Input.AccessKeyHandlerTests.Should_Open_MainMenu_On_Alt_KeyUp', 'Avalonia.Base.UnitTests.Input.InputElement_Focus.Focus_Should_Not_Get_Restored_To_Enabled_Control', 'Avalonia.Controls.UnitTests.ButtonTests.Button_Invokes_CanExecute_When_CommandParameter_Changed', 'Avalonia.Controls.UnitTests.ButtonTests.Raises_Click_When_AccessKey_Raised', 'Avalonia.Controls.UnitTests.ButtonTests.Button_Invokes_Doesnt_Execute_When_Button_Disabled', 'Avalonia.Controls.UnitTests.TabControlTests.Should_TabControl_Recognizes_AccessKey']
AvaloniaUI/Avalonia
avaloniaui__avalonia-17209
d3aa0c21e39a759e358fa7c3a90d3422fb19ecbf
diff --git a/src/Avalonia.Base/Media/TextFormatting/BidiReorderer.cs b/src/Avalonia.Base/Media/TextFormatting/BidiReorderer.cs index 85fea48edb8..0612ecf8e02 100644 --- a/src/Avalonia.Base/Media/TextFormatting/BidiReorderer.cs +++ b/src/Avalonia.Base/Media/TextFormatting/BidiReorderer.cs @@ -169,7 +169,7 @@ private static sbyte GetRunBidiLevel(TextRun run, FlowDirection flowDirection, s if (run is TextEndOfLine) { - return defaultLevel; + return 0; } if(previousLevel is not null)
diff --git a/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextFormatterTests.cs b/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextFormatterTests.cs index 83c5fc377c8..5ff0a45e390 100644 --- a/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextFormatterTests.cs +++ b/tests/Avalonia.Skia.UnitTests/Media/TextFormatting/TextFormatterTests.cs @@ -156,11 +156,15 @@ public void Should_Format_TextLine_With_Non_Text_TextRuns_RightToLeft() Assert.Equal(14, textLine.Length); - var second = textLine.TextRuns[1] as ShapedTextRun; + var first = textLine.TextRuns[0] as ShapedTextRun; - Assert.NotNull(second); + var last = textLine.TextRuns[4] as TextEndOfParagraph; - Assert.Equal("Hello".AsMemory(), second.Text); + Assert.NotNull(first); + + Assert.NotNull(last); + + Assert.Equal("Hello".AsMemory(), first.Text); } }
Wrapped RTL text has extra bottom padding ### Describe the bug ![image](https://github.com/AvaloniaUI/Avalonia/assets/5063478/7fb3ad43-57ee-4609-a371-625a01220e56) Looks like space for one more line is allocated. ### To Reproduce https://github.com/kerams/font2 ### Expected behavior LTR and RTL wrapped text have the same height. ### Avalonia version 11.2.999-cibuild0049152-alpha ### OS Windows, Android ### Additional context _No response_
null
2024-10-07T21:13:28Z
0.1
[]
['Avalonia.Skia.UnitTests.Media.TextFormatting.TextFormatterTests.Should_Format_TextLine_With_Non_Text_TextRuns_RightToLeft']
AvaloniaUI/Avalonia
avaloniaui__avalonia-15498
e38edb258d6fe0855a0643ede0ffc18c2a214960
diff --git a/src/Avalonia.Controls/Selection/ReadOnlySelectionListBase.cs b/src/Avalonia.Controls/Selection/ReadOnlySelectionListBase.cs new file mode 100644 index 00000000000..f603fd81686 --- /dev/null +++ b/src/Avalonia.Controls/Selection/ReadOnlySelectionListBase.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; +using Avalonia.Collections; + +namespace Avalonia.Controls.Selection; + +internal abstract class ReadOnlySelectionListBase<T> : IReadOnlyList<T?>, IList, INotifyCollectionChanged +{ + public abstract T? this[int index] { get; } + public abstract int Count { get; } + + object? IList.this[int index] + { + get => this[index]; + set => ThrowReadOnlyException(); + } + + bool IList.IsFixedSize => false; + bool IList.IsReadOnly => true; + bool ICollection.IsSynchronized => false; + object ICollection.SyncRoot => this; + + public event NotifyCollectionChangedEventHandler? CollectionChanged; + + public abstract IEnumerator<T?> GetEnumerator(); + public void RaiseCollectionReset() => CollectionChanged?.Invoke(this, EventArgsCache.ResetCollectionChanged); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + int IList.Add(object? value) { ThrowReadOnlyException(); return 0; } + void IList.Clear() => ThrowReadOnlyException(); + void IList.Insert(int index, object? value) => ThrowReadOnlyException(); + void IList.Remove(object? value) => ThrowReadOnlyException(); + void IList.RemoveAt(int index) => ThrowReadOnlyException(); + bool IList.Contains(object? value) => Count != 0 && ((IList)this).IndexOf(value) != -1; + + void ICollection.CopyTo(Array array, int index) + { + foreach (var item in this) + array.SetValue(item, index++); + } + + int IList.IndexOf(object? value) + { + for (int i = 0; i < Count; i++) + { + if (Equals(this[i], value)) + return i; + } + + return -1; + } + + [DoesNotReturn] + private static void ThrowReadOnlyException() => throw new NotSupportedException("Collection is read-only."); +} diff --git a/src/Avalonia.Controls/Selection/SelectedIndexes.cs b/src/Avalonia.Controls/Selection/SelectedIndexes.cs index a65f45e64f4..b742d91e218 100644 --- a/src/Avalonia.Controls/Selection/SelectedIndexes.cs +++ b/src/Avalonia.Controls/Selection/SelectedIndexes.cs @@ -5,7 +5,7 @@ namespace Avalonia.Controls.Selection { - internal class SelectedIndexes<T> : IReadOnlyList<int> + internal class SelectedIndexes<T> : ReadOnlySelectionListBase<int> { private readonly SelectionModel<T>? _owner; private readonly IReadOnlyList<IndexRange>? _ranges; @@ -13,7 +13,7 @@ internal class SelectedIndexes<T> : IReadOnlyList<int> public SelectedIndexes(SelectionModel<T> owner) => _owner = owner; public SelectedIndexes(IReadOnlyList<IndexRange> ranges) => _ranges = ranges; - public int this[int index] + public override int this[int index] { get { @@ -33,7 +33,7 @@ public int this[int index] } } - public int Count + public override int Count { get { @@ -50,7 +50,7 @@ public int Count private IReadOnlyList<IndexRange> Ranges => _ranges ?? _owner!.Ranges!; - public IEnumerator<int> GetEnumerator() + public override IEnumerator<int> GetEnumerator() { IEnumerator<int> SingleSelect() { @@ -74,7 +74,5 @@ IEnumerator<int> SingleSelect() { return ranges is object ? new SelectedIndexes<T>(ranges) : null; } - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } diff --git a/src/Avalonia.Controls/Selection/SelectedItems.cs b/src/Avalonia.Controls/Selection/SelectedItems.cs index 74007805cd5..a892876b295 100644 --- a/src/Avalonia.Controls/Selection/SelectedItems.cs +++ b/src/Avalonia.Controls/Selection/SelectedItems.cs @@ -1,11 +1,12 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; +using System.Collections.Specialized; +using Avalonia.Collections; namespace Avalonia.Controls.Selection { - internal class SelectedItems<T> : IReadOnlyList<T?> + internal class SelectedItems<T> : ReadOnlySelectionListBase<T> { private readonly SelectionModel<T>? _owner; private readonly ItemsSourceView<T>? _items; @@ -19,7 +20,7 @@ public SelectedItems(IReadOnlyList<IndexRange> ranges, ItemsSourceView<T>? items _items = items; } - public T? this[int index] + public override T? this[int index] { get { @@ -43,7 +44,7 @@ public T? this[int index] } } - public int Count + public override int Count { get { @@ -61,7 +62,7 @@ public int Count private ItemsSourceView<T>? Items => _items ?? _owner?.ItemsView; private IReadOnlyList<IndexRange>? Ranges => _ranges ?? _owner!.Ranges; - public IEnumerator<T?> GetEnumerator() + public override IEnumerator<T?> GetEnumerator() { if (_owner?.SingleSelect == true) { @@ -84,8 +85,6 @@ public int Count } } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public static SelectedItems<T>? Create( IReadOnlyList<IndexRange>? ranges, ItemsSourceView<T>? items) @@ -93,14 +92,13 @@ public int Count return ranges is object ? new SelectedItems<T>(ranges, items) : null; } - public class Untyped : IReadOnlyList<object?> + public class Untyped : ReadOnlySelectionListBase<object?> { private readonly IReadOnlyList<T?> _source; public Untyped(IReadOnlyList<T?> source) => _source = source; - public object? this[int index] => _source[index]; - public int Count => _source.Count; - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public IEnumerator<object?> GetEnumerator() + public override object? this[int index] => _source[index]; + public override int Count => _source.Count; + public override IEnumerator<object?> GetEnumerator() { foreach (var i in _source) { diff --git a/src/Avalonia.Controls/Selection/SelectionModel.cs b/src/Avalonia.Controls/Selection/SelectionModel.cs index 818308793b9..d191f79801b 100644 --- a/src/Avalonia.Controls/Selection/SelectionModel.cs +++ b/src/Avalonia.Controls/Selection/SelectionModel.cs @@ -710,11 +710,13 @@ private void CommitOperation(Operation operation, bool raisePropertyChanged = tr if (indexesChanged) { RaisePropertyChanged(nameof(SelectedIndexes)); + _selectedIndexes?.RaiseCollectionReset(); } if (indexesChanged || operation.IsSourceUpdate) { RaisePropertyChanged(nameof(SelectedItems)); + _selectedItems?.RaiseCollectionReset(); } }
diff --git a/tests/Avalonia.Controls.UnitTests/Selection/SelectionModelTests_Single.cs b/tests/Avalonia.Controls.UnitTests/Selection/SelectionModelTests_Single.cs index 64236268f8e..f4dbdf54180 100644 --- a/tests/Avalonia.Controls.UnitTests/Selection/SelectionModelTests_Single.cs +++ b/tests/Avalonia.Controls.UnitTests/Selection/SelectionModelTests_Single.cs @@ -516,6 +516,26 @@ public void PropertyChanged_Is_Raised_When_SelectedIndex_Changes() Assert.Equal(1, raised); } + + [Fact] + public void CollectionChanged_Is_Raised_When_SelectedIndex_Changes() + { + var target = CreateTarget(); + var raised = 0; + var incc = Assert.IsAssignableFrom<INotifyCollectionChanged>(target.SelectedIndexes); + + incc.CollectionChanged += (s, e) => + { + // For the moment, for simplicity, we raise a Reset event when the SelectedIndexes + // collection changes - whatever the change. This can be improved later if necessary. + Assert.Equal(NotifyCollectionChangedAction.Reset, e.Action); + ++raised; + }; + + target.SelectedIndex = 1; + + Assert.Equal(1, raised); + } } public class SelectedItems @@ -538,6 +558,26 @@ public void PropertyChanged_Is_Raised_When_SelectedIndex_Changes() Assert.Equal(1, raised); } + + [Fact] + public void CollectionChanged_Is_Raised_When_SelectedIndex_Changes() + { + var target = CreateTarget(); + var raised = 0; + var incc = Assert.IsAssignableFrom<INotifyCollectionChanged>(target.SelectedIndexes); + + incc.CollectionChanged += (s, e) => + { + // For the moment, for simplicity, we raise a Reset event when the SelectedItems + // collection changes - whatever the change. This can be improved later if necessary. + Assert.Equal(NotifyCollectionChangedAction.Reset, e.Action); + ++raised; + }; + + target.SelectedIndex = 1; + + Assert.Equal(1, raised); + } } public class Select
Unable to bind to `SelectionModel.SelectedItems` or `SelectedIndexes` ### Describe the bug Reported by a customer: Binding `ItemsControl.ItemsSource` to `SelectionModel.SelectedItems` or `SelectionModel.SelectedIndexes` does not work. `SelectionModel` raises a `PropertyChanged` event on `SelectedItems` and `SelectedIndexes`, but because the instance of the collection hasn't changed, property system doesn't consider the value to have changed, so consequently the bound `ItemsControl` doesn't register the change. This behaviour comes from WinUI which was the original source of our `SelectionModel` (though they have diverged significantly since the initial port): https://github.com/microsoft/microsoft-ui-xaml/blob/winui3/release/1.4-stable/controls/dev/Repeater/SelectionModel.cpp#L591-L592 I assume that the WinUI `SelectionModel` was written without the expectation that someone would bind to the selected collections on a `SelectionModel`. ### To Reproduce ```xml <Grid ColumnDefinitions="*,*"> <ListBox Name="lb" ItemsSource="{Binding}" SelectionMode="Multiple"/> <ListBox Grid.Column="1" ItemsSource="{Binding #lb.Selection.SelectedIndexes}"/> </Grid> ``` ### Expected behavior `SelectionModel.SelectedItems` or `SelectionModel.SelectedIndexes` and should follow the usual semantics for property and collection changes, not the strange semantics we have inherited from WinUI. ### Avalonia version all ### OS _No response_ ### Additional context _No response_
null
2024-04-24T11:56:47Z
0.1
['Avalonia.Controls.UnitTests.Selection.SelectionModelTests_Single+SelectedIndexes.CollectionChanged_Is_Raised_When_SelectedIndex_Changes', 'Avalonia.Controls.UnitTests.Selection.SelectionModelTests_Single+SelectedItems.CollectionChanged_Is_Raised_When_SelectedIndex_Changes']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-15493
d4339e4b0ad37a03363d6b67a7f0cf4b4f676f38
diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml b/samples/ControlCatalog/Pages/ToolTipPage.xaml index fa40bc1a0fa..8aaed903f36 100644 --- a/samples/ControlCatalog/Pages/ToolTipPage.xaml +++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml @@ -77,12 +77,23 @@ </Button> <Border Grid.Row="3" + Grid.Column="0" Background="{DynamicResource SystemAccentColor}" Margin="5" Padding="50" ToolTip.Tip="Outer tooltip"> <TextBlock Background="{StaticResource SystemAccentColorDark1}" Padding="10" ToolTip.Tip="Inner tooltip" VerticalAlignment="Center">Nested ToolTips</TextBlock> </Border> + + <Border Grid.Row="3" + Grid.Column="1" + Background="{DynamicResource SystemAccentColor}" + Margin="5" + Padding="50" + ToolTip.ToolTipOpening="ToolTipOpening" + ToolTip.Tip="Should never be visible"> + <TextBlock VerticalAlignment="Center">ToolTip replaced on the fly</TextBlock> + </Border> </Grid> </StackPanel> </UserControl> diff --git a/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs b/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs index 202f83aaf19..0e8bf3a181d 100644 --- a/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs +++ b/samples/ControlCatalog/Pages/ToolTipPage.xaml.cs @@ -1,4 +1,5 @@ using Avalonia.Controls; +using Avalonia.Interactivity; using Avalonia.Markup.Xaml; namespace ControlCatalog.Pages @@ -14,5 +15,10 @@ private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } + + private void ToolTipOpening(object? sender, CancelRoutedEventArgs args) + { + ((Control)args.Source!).SetValue(ToolTip.TipProperty, "New tip set from ToolTipOpening."); + } } } diff --git a/src/Avalonia.Controls/ToolTip.cs b/src/Avalonia.Controls/ToolTip.cs index 245b4d74b08..8bf0adedee5 100644 --- a/src/Avalonia.Controls/ToolTip.cs +++ b/src/Avalonia.Controls/ToolTip.cs @@ -3,6 +3,7 @@ using Avalonia.Controls.Diagnostics; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; +using Avalonia.Interactivity; using Avalonia.Reactive; using Avalonia.Styling; @@ -80,6 +81,28 @@ public class ToolTip : ContentControl, IPopupHostProvider internal static readonly AttachedProperty<ToolTip?> ToolTipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, ToolTip?>("ToolTip"); + /// <summary> + /// The event raised when a ToolTip is going to be shown on an element. + /// </summary> + /// <remarks> + /// To prevent a tooltip from appearing in the UI, your handler for ToolTipOpening can mark the event data handled. + /// Otherwise, the tooltip is displayed, using the value of the ToolTip property as the tooltip content. + /// Another possible scenario is that you could write a handler that resets the value of the ToolTip property for the element that is the event source, just before the tooltip is displayed. + /// ToolTipOpening will not be raised if the value of ToolTip is null or otherwise unset. Do not deliberately set ToolTip to null while a tooltip is open or opening; this will not have the effect of closing the tooltip, and will instead create an undesirable visual artifact in the UI. + /// </remarks> + public static readonly RoutedEvent<CancelRoutedEventArgs> ToolTipOpeningEvent = + RoutedEvent.Register<ToolTip, CancelRoutedEventArgs>("ToolTipOpening", RoutingStrategies.Direct); + + /// <summary> + /// The event raised when a ToolTip on an element that was shown should now be hidden. + /// </summary> + /// <remarks> + /// Marking the ToolTipClosing event as handled does not cancel closing the tooltip. + /// Once the tooltip is displayed, closing the tooltip is done only in response to user interaction with the UI. + /// </remarks> + public static readonly RoutedEvent ToolTipClosingEvent = + RoutedEvent.Register<ToolTip, RoutedEventArgs>("ToolTipClosing", RoutingStrategies.Direct); + private Popup? _popup; private Action<IPopupHost?>? _popupHostChangedHandler; private CompositeDisposable? _subscriptions; @@ -92,9 +115,6 @@ static ToolTip() IsOpenProperty.Changed.Subscribe(IsOpenChanged); } - internal Control? AdornedControl { get; private set; } - internal event EventHandler? Closed; - /// <summary> /// Gets the value of the ToolTip.Tip attached property. /// </summary> @@ -275,6 +295,38 @@ public static bool GetServiceEnabled(Control element) => public static void SetServiceEnabled(Control element, bool value) => element.SetValue(ServiceEnabledProperty, value); + /// <summary> + /// Adds a handler for the <see cref="ToolTipOpeningEvent"/> attached event. + /// </summary> + /// <param name="element"><see cref="Control"/> that listens to this event.</param> + /// <param name="handler">Event Handler to be added.</param> + public static void AddToolTipOpeningHandler(Control element, EventHandler<CancelRoutedEventArgs> handler) => + element.AddHandler(ToolTipOpeningEvent, handler); + + /// <summary> + /// Removes a handler for the <see cref="ToolTipOpeningEvent"/> attached event. + /// </summary> + /// <param name="element"><see cref="Control"/> that listens to this event.</param> + /// <param name="handler">Event Handler to be removed.</param> + public static void RemoveToolTipOpeningHandler(Control element, EventHandler<CancelRoutedEventArgs> handler) => + element.RemoveHandler(ToolTipOpeningEvent, handler); + + /// <summary> + /// Adds a handler for the <see cref="ToolTipClosingEvent"/> attached event. + /// </summary> + /// <param name="element"><see cref="Control"/> that listens to this event.</param> + /// <param name="handler">Event Handler to be removed.</param> + public static void AddToolTipClosingHandler(Control element, EventHandler<RoutedEventArgs> handler) => + element.AddHandler(ToolTipClosingEvent, handler); + + /// <summary> + /// Removes a handler for the <see cref="ToolTipClosingEvent"/> attached event. + /// </summary> + /// <param name="element"><see cref="Control"/> that listens to this event.</param> + /// <param name="handler">Event Handler to be removed.</param> + public static void RemoveToolTipClosingHandler(Control element, EventHandler<RoutedEventArgs> handler) => + element.RemoveHandler(ToolTipClosingEvent, handler); + private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; @@ -282,8 +334,20 @@ private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) if (newValue) { + var args = new CancelRoutedEventArgs(ToolTipOpeningEvent); + control.RaiseEvent(args); + if (args.Cancel) + { + control.SetCurrentValue(IsOpenProperty, false); + return; + } + var tip = GetTip(control); - if (tip == null) return; + if (tip == null) + { + control.SetCurrentValue(IsOpenProperty, false); + return; + } var toolTip = control.GetValue(ToolTipProperty); if (toolTip == null || (tip != toolTip && tip != toolTip.Content)) @@ -292,25 +356,23 @@ private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) toolTip = tip as ToolTip ?? new ToolTip { Content = tip }; control.SetValue(ToolTipProperty, toolTip); - toolTip.SetValue(ThemeVariant.RequestedThemeVariantProperty, control.ActualThemeVariant); } toolTip.AdornedControl = control; toolTip.Open(control); - toolTip?.UpdatePseudoClasses(newValue); } else if (control.GetValue(ToolTipProperty) is { } toolTip) { toolTip.AdornedControl = null; toolTip.Close(); - toolTip?.UpdatePseudoClasses(newValue); } } - IPopupHost? IPopupHostProvider.PopupHost => _popup?.Host; - + internal Control? AdornedControl { get; private set; } + internal event EventHandler? Closed; internal IPopupHost? PopupHost => _popup?.Host; + IPopupHost? IPopupHostProvider.PopupHost => _popup?.Host; event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged { add => _popupHostChangedHandler += value; @@ -346,6 +408,13 @@ private void Open(Control control) private void Close() { + if (AdornedControl is { } adornedControl + && GetIsOpen(adornedControl)) + { + var args = new RoutedEventArgs(ToolTipClosingEvent); + adornedControl.RaiseEvent(args); + } + _subscriptions?.Dispose(); if (_popup is not null) @@ -366,12 +435,14 @@ private void OnPopupClosed(object? sender, EventArgs e) } _popupHostChangedHandler?.Invoke(null); + UpdatePseudoClasses(false); Closed?.Invoke(this, EventArgs.Empty); } private void OnPopupOpened(object? sender, EventArgs e) { _popupHostChangedHandler?.Invoke(((Popup)sender!).Host); + UpdatePseudoClasses(true); } private void UpdatePseudoClasses(bool newValue) diff --git a/src/Avalonia.Controls/ToolTipService.cs b/src/Avalonia.Controls/ToolTipService.cs index c3231fcde93..d01114be6fb 100644 --- a/src/Avalonia.Controls/ToolTipService.cs +++ b/src/Avalonia.Controls/ToolTipService.cs @@ -221,7 +221,8 @@ private void Open(Control control) { ToolTip.SetIsOpen(control, true); - if (control.GetValue(ToolTip.ToolTipProperty) is { } tooltip) + // Value can be coerced back to false, need to double check. + if (ToolTip.GetIsOpen(control) && control.GetValue(ToolTip.ToolTipProperty) is { } tooltip) { tooltip.Closed += ToolTipClosed; tooltip.PointerExited += ToolTipPointerExited;
diff --git a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs index 8dafef7e182..6199a208720 100644 --- a/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ToolTipTests.cs @@ -368,6 +368,87 @@ public void New_ToolTip_Replaces_Other_ToolTip_Immediately() Assert.False(ToolTip.GetIsOpen(other)); } + [Fact] + public void ToolTip_Events_Order_Is_Defined() + { + using var app = UnitTestApplication.Start(ConfigureServices(TestServices.FocusableWindow)); + + var tip = new ToolTip() { Content = "Tip" }; + var target = new Decorator() + { + [ToolTip.TipProperty] = tip, + [ToolTip.ShowDelayProperty] = 0 + }; + + var eventsOrder = new List<(string eventName, object sender, object source)>(); + + ToolTip.AddToolTipOpeningHandler(target, + (sender, args) => eventsOrder.Add(("Opening", sender, args.Source))); + ToolTip.AddToolTipClosingHandler(target, + (sender, args) => eventsOrder.Add(("Closing", sender, args.Source))); + + SetupWindowAndActivateToolTip(target); + + Assert.True(ToolTip.GetIsOpen(target)); + + target[ToolTip.TipProperty] = null; + + Assert.False(ToolTip.GetIsOpen(target)); + + Assert.Equal( + new[] + { + ("Opening", (object)target, (object)target), + ("Closing", target, target) + }, + eventsOrder); + } + + [Fact] + public void ToolTip_Is_Not_Opened_If_Opening_Event_Handled() + { + using var app = UnitTestApplication.Start(ConfigureServices(TestServices.FocusableWindow)); + + var tip = new ToolTip() { Content = "Tip" }; + var target = new Decorator() + { + [ToolTip.TipProperty] = tip, + [ToolTip.ShowDelayProperty] = 0 + }; + + ToolTip.AddToolTipOpeningHandler(target, + (sender, args) => args.Cancel = true); + + SetupWindowAndActivateToolTip(target); + + Assert.False(ToolTip.GetIsOpen(target)); + } + + [Fact] + public void ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event() + { + using var app = UnitTestApplication.Start(ConfigureServices(TestServices.FocusableWindow)); + + var tip1 = new ToolTip() { Content = "Hi" }; + var tip2 = new ToolTip() { Content = "Bye" }; + var target = new Decorator() + { + [ToolTip.TipProperty] = tip1, + [ToolTip.ShowDelayProperty] = 0 + }; + + ToolTip.AddToolTipOpeningHandler(target, + (sender, args) => target[ToolTip.TipProperty] = tip2); + + SetupWindowAndActivateToolTip(target); + + Assert.True(ToolTip.GetIsOpen(target)); + + target[ToolTip.TipProperty] = null; + + Assert.False(ToolTip.GetIsOpen(target)); + } + [Fact] public void Should_Close_When_Pointer_Leaves_Window() {
Add Control.ToolTipOpening/ToolTipClosing events ### Is your feature request related to a problem? Please describe. WPF implements attached `ToolTipService.ToolTipOpening` and `ToolTipClosing` events that are `AddOwner`-ed on `FrameworkElement`, thereby adding [FrameworkElement.ToolTipOpening](https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.tooltipopening?view=windowsdesktop-8.0) and [ToolTipClosing](https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.tooltipclosing?view=windowsdesktop-8.0) events and related `OnToolTipXXX` methods on elements. These events are handy, especially the opening one, because it allows a tooltip to be customized prior to display or alternatively canceled. The customization ability is a feature we could use. ### Describe the solution you'd like Make a similar design to WPF, at least in terms of adding the two events on Avalonia's `Control` class so that we can customize or cancel tooltips prior to display. And the ToolTipClosing event is there as well in case people need it for some kind of cleanup. ### Describe alternatives you've considered _No response_ ### Additional context _No response_
null
2024-04-24T04:13:15Z
0.1
['Avalonia.Controls.UnitTests.ToolTipTests_Popup.ToolTip_Events_Order_Is_Defined', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.ToolTip_Events_Order_Is_Defined', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.ToolTip_Is_Not_Opened_If_Opening_Event_Handled', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.ToolTip_Is_Not_Opened_If_Opening_Event_Handled', 'Avalonia.Controls.UnitTests.ToolTipTests_Popup.ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event', 'Avalonia.Controls.UnitTests.ToolTipTests_Overlay.ToolTip_Can_Be_Replaced_On_The_Fly_Via_Opening_Event']
[]
ardalis/CleanArchitecture
ardalis__cleanarchitecture-918
9b93751ebda2b4268847b150fb026bb0fba71b89
diff --git a/Directory.Packages.props b/Directory.Packages.props index 34d88c6f5..f29e23129 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -15,7 +15,6 @@ <PackageVersion Include="FastEndpoints.ApiExplorer" Version="2.2.0" /> <PackageVersion Include="FastEndpoints.Swagger" Version="5.31.0" /> <PackageVersion Include="FastEndpoints.Swagger.Swashbuckle" Version="2.2.0" /> - <PackageVersion Include="FluentAssertions" Version="7.0.0" /> <PackageVersion Include="MailKit" Version="4.9.0" /> <PackageVersion Include="MediatR" Version="12.4.1" /> <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.0" /> @@ -33,6 +32,7 @@ <PackageVersion Include="NSubstitute" Version="5.3.0" /> <PackageVersion Include="ReportGenerator" Version="5.4.1" /> <PackageVersion Include="Serilog.AspNetCore" Version="9.0.0" /> + <PackageVersion Include="Shouldly" Version="4.3.0" /> <PackageVersion Include="SQLite" Version="3.13.0" /> <PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageVersion Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
diff --git a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorGetById.cs b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorGetById.cs index cfe4b05c4..4317d275e 100644 --- a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorGetById.cs +++ b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorGetById.cs @@ -14,8 +14,8 @@ public async Task ReturnsSeedContributorGivenId1() { var result = await _client.GetAndDeserializeAsync<ContributorRecord>(GetContributorByIdRequest.BuildRoute(1)); - Assert.Equal(1, result.Id); - Assert.Equal(SeedData.Contributor1.Name, result.Name); + result.Id.ShouldBe(1); + result.Name.ShouldBe(SeedData.Contributor1.Name); } [Fact] diff --git a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorList.cs b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorList.cs index 4af7769a8..6c4e7458a 100644 --- a/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorList.cs +++ b/tests/Clean.Architecture.FunctionalTests/ApiEndpoints/ContributorList.cs @@ -13,8 +13,8 @@ public async Task ReturnsTwoContributors() { var result = await _client.GetAndDeserializeAsync<ContributorListResponse>("/Contributors"); - Assert.Equal(2, result.Contributors.Count); - Assert.Contains(result.Contributors, i => i.Name == SeedData.Contributor1.Name); - Assert.Contains(result.Contributors, i => i.Name == SeedData.Contributor2.Name); + result.Contributors.Count.ShouldBe(2); + result.Contributors.ShouldContain(contributor => contributor.Name == SeedData.Contributor1.Name); + result.Contributors.ShouldContain(contributor => contributor.Name == SeedData.Contributor2.Name); } } diff --git a/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj b/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj index 8543d2aa7..e2aecb1f8 100644 --- a/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj +++ b/tests/Clean.Architecture.FunctionalTests/Clean.Architecture.FunctionalTests.csproj @@ -2,7 +2,7 @@ <Sdk Name="Microsoft.Build.CentralPackageVersions" Version="2.1.3" /> <ItemGroup> - <PackageReference Include="FluentAssertions" /> + <PackageReference Include="Shouldly" /> <PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="xunit" /> <PackageReference Include="xunit.runner.visualstudio"> diff --git a/tests/Clean.Architecture.FunctionalTests/GlobalUsings.cs b/tests/Clean.Architecture.FunctionalTests/GlobalUsings.cs index 37981f72a..c9b5ce064 100644 --- a/tests/Clean.Architecture.FunctionalTests/GlobalUsings.cs +++ b/tests/Clean.Architecture.FunctionalTests/GlobalUsings.cs @@ -4,4 +4,5 @@ global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; +global using Shouldly; global using Xunit; diff --git a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryAdd.cs b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryAdd.cs index 947a896b8..caa478619 100644 --- a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryAdd.cs +++ b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryAdd.cs @@ -17,8 +17,9 @@ public async Task AddsContributorAndSetsId() var newContributor = (await repository.ListAsync()) .FirstOrDefault(); - Assert.Equal(testContributorName, newContributor?.Name); - Assert.Equal(testContributorStatus, newContributor?.Status); - Assert.True(newContributor?.Id > 0); + newContributor.ShouldNotBeNull(); + testContributorName.ShouldBe(newContributor.Name); + testContributorStatus.ShouldBe(newContributor.Status); + newContributor.Id.ShouldBeGreaterThan(0); } } diff --git a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryDelete.cs b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryDelete.cs index 0c82c924f..f4ac64f10 100644 --- a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryDelete.cs +++ b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryDelete.cs @@ -17,7 +17,6 @@ public async Task DeletesItemAfterAddingIt() await repository.DeleteAsync(Contributor); // verify it's no longer there - Assert.DoesNotContain(await repository.ListAsync(), - Contributor => Contributor.Name == initialName); + (await repository.ListAsync()).ShouldNotContain(Contributor => Contributor.Name == initialName); } } diff --git a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryUpdate.cs b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryUpdate.cs index d99ced265..c854b3b9b 100644 --- a/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryUpdate.cs +++ b/tests/Clean.Architecture.IntegrationTests/Data/EfRepositoryUpdate.cs @@ -1,6 +1,5 @@ using Clean.Architecture.Core.ContributorAggregate; - namespace Clean.Architecture.IntegrationTests.Data; public class EfRepositoryUpdate : BaseEfRepoTestFixture @@ -21,12 +20,9 @@ public async Task UpdatesItemAfterAddingIt() // fetch the item and update its title var newContributor = (await repository.ListAsync()) .FirstOrDefault(Contributor => Contributor.Name == initialName); - if (newContributor == null) - { - Assert.NotNull(newContributor); - return; - } - Assert.NotSame(Contributor, newContributor); + newContributor.ShouldNotBeNull(); + + Contributor.ShouldNotBeSameAs(newContributor); var newName = Guid.NewGuid().ToString(); newContributor.UpdateName(newName); @@ -37,9 +33,9 @@ public async Task UpdatesItemAfterAddingIt() var updatedItem = (await repository.ListAsync()) .FirstOrDefault(Contributor => Contributor.Name == newName); - Assert.NotNull(updatedItem); - Assert.NotEqual(Contributor.Name, updatedItem?.Name); - Assert.Equal(Contributor.Status, updatedItem?.Status); - Assert.Equal(newContributor.Id, updatedItem?.Id); + updatedItem.ShouldNotBeNull(); + Contributor.Name.ShouldNotBe(updatedItem.Name); + Contributor.Status.ShouldBe(updatedItem.Status); + newContributor.Id.ShouldBe(updatedItem.Id); } } diff --git a/tests/Clean.Architecture.IntegrationTests/GlobalUsings.cs b/tests/Clean.Architecture.IntegrationTests/GlobalUsings.cs index 286035c8e..378e7f0b0 100644 --- a/tests/Clean.Architecture.IntegrationTests/GlobalUsings.cs +++ b/tests/Clean.Architecture.IntegrationTests/GlobalUsings.cs @@ -2,4 +2,5 @@ global using Microsoft.EntityFrameworkCore; global using Microsoft.Extensions.DependencyInjection; global using NSubstitute; +global using Shouldly; global using Xunit; diff --git a/tests/Clean.Architecture.UnitTests/Clean.Architecture.UnitTests.csproj b/tests/Clean.Architecture.UnitTests/Clean.Architecture.UnitTests.csproj index 51d83eafb..03fffe7b4 100644 --- a/tests/Clean.Architecture.UnitTests/Clean.Architecture.UnitTests.csproj +++ b/tests/Clean.Architecture.UnitTests/Clean.Architecture.UnitTests.csproj @@ -11,7 +11,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="FluentAssertions" /> + <PackageReference Include="Shouldly" /> <PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="NSubstitute" /> <PackageReference Include="xunit.runner.visualstudio"> diff --git a/tests/Clean.Architecture.UnitTests/Core/ContributorAggregate/ContributorConstructor.cs b/tests/Clean.Architecture.UnitTests/Core/ContributorAggregate/ContributorConstructor.cs index e6f07282a..93d52bc23 100644 --- a/tests/Clean.Architecture.UnitTests/Core/ContributorAggregate/ContributorConstructor.cs +++ b/tests/Clean.Architecture.UnitTests/Core/ContributorAggregate/ContributorConstructor.cs @@ -15,6 +15,6 @@ public void InitializesName() { _testContributor = CreateContributor(); - Assert.Equal(_testName, _testContributor.Name); + _testContributor.Name.ShouldBe(_testName); } } diff --git a/tests/Clean.Architecture.UnitTests/Core/Services/DeleteContributorSevice_DeleteContributor.cs b/tests/Clean.Architecture.UnitTests/Core/Services/DeleteContributorSevice_DeleteContributor.cs index 4c52e1959..51383a7b3 100644 --- a/tests/Clean.Architecture.UnitTests/Core/Services/DeleteContributorSevice_DeleteContributor.cs +++ b/tests/Clean.Architecture.UnitTests/Core/Services/DeleteContributorSevice_DeleteContributor.cs @@ -20,6 +20,6 @@ public async Task ReturnsNotFoundGivenCantFindContributor() { var result = await _service.DeleteContributor(0); - Assert.Equal(Ardalis.Result.ResultStatus.NotFound, result.Status); + result.Status.ShouldBe(Ardalis.Result.ResultStatus.NotFound); } } diff --git a/tests/Clean.Architecture.UnitTests/GlobalUsings.cs b/tests/Clean.Architecture.UnitTests/GlobalUsings.cs index 8164e52ce..2c56b1ff0 100644 --- a/tests/Clean.Architecture.UnitTests/GlobalUsings.cs +++ b/tests/Clean.Architecture.UnitTests/GlobalUsings.cs @@ -2,7 +2,7 @@ global using Ardalis.SharedKernel; global using Clean.Architecture.Core.ContributorAggregate; global using Clean.Architecture.UseCases.Contributors.Create; -global using FluentAssertions; +global using Shouldly; global using MediatR; global using Microsoft.Extensions.Logging; global using NSubstitute; diff --git a/tests/Clean.Architecture.UnitTests/UseCases/Contributors/CreateContributorHandlerHandle.cs b/tests/Clean.Architecture.UnitTests/UseCases/Contributors/CreateContributorHandlerHandle.cs index 126af4fe1..82012ed94 100644 --- a/tests/Clean.Architecture.UnitTests/UseCases/Contributors/CreateContributorHandlerHandle.cs +++ b/tests/Clean.Architecture.UnitTests/UseCases/Contributors/CreateContributorHandlerHandle.cs @@ -23,6 +23,6 @@ public async Task ReturnsSuccessGivenValidName() .Returns(Task.FromResult(CreateContributor())); var result = await _handler.Handle(new CreateContributorCommand(_testName, null), CancellationToken.None); - result.IsSuccess.Should().BeTrue(); + result.IsSuccess.ShouldBeTrue(); } }
Remove FluentAssertions since it's now a commercial product <!-- ⚠️⚠️ Do Not Delete This! feature_request_template ⚠️⚠️ --> <!-- Please search existing issues to avoid creating duplicates. --> <!-- Describe the feature you'd like. -->
Will you replace by what ? Thks Shouldly. It's pretty much a drop in replacement. For those looking to tackle this issue, this blog post might help: https://blog.nimblepros.com/blogs/getting-started-with-shouldly/
2025-02-05T09:56:15Z
0.1
['Clean.Architecture.FunctionalTests.ApiEndpoints.ContributorGetById.ReturnsSeedContributorGivenId1', 'Clean.Architecture.FunctionalTests.ApiEndpoints.ContributorList.ReturnsTwoContributors', 'Clean.Architecture.IntegrationTests.Data.EfRepositoryAdd.AddsContributorAndSetsId', 'Clean.Architecture.IntegrationTests.Data.EfRepositoryDelete.DeletesItemAfterAddingIt', 'Clean.Architecture.IntegrationTests.Data.EfRepositoryUpdate.UpdatesItemAfterAddingIt', 'Clean.Architecture.UnitTests.Core.ContributorAggregate.ContributorConstructor.InitializesName', 'Clean.Architecture.UnitTests.UseCases.Contributors.CreateContributorHandlerHandle.ReturnsSuccessGivenValidName']
[]
JoshClose/CsvHelper
joshclose__csvhelper-2132
9848510ed0fc0980bda687882c5ea123b7d7d3ce
diff --git a/src/CsvHelper.Website/input/examples/configuration/attributes/index.md b/src/CsvHelper.Website/input/examples/configuration/attributes/index.md index 871798f14..41c588d41 100644 --- a/src/CsvHelper.Website/input/examples/configuration/attributes/index.md +++ b/src/CsvHelper.Website/input/examples/configuration/attributes/index.md @@ -5,9 +5,9 @@ Most of the configuration done via class maps can also be done using attributes. ###### Data ``` -Identifier,name,IsBool,Constant -1,one,yes,a -2,two,no,b +Identifier||Amount2|IsBool|Constant +1|1,234|1,234|yes|a +2|1.234|1.234|no|b ``` ###### Example @@ -15,35 +15,54 @@ Identifier,name,IsBool,Constant ```cs void Main() { + CsvConfiguration config = CsvConfiguration.FromType<Foo>(); using (var reader = new StreamReader("path\\to\\file.csv")) - using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) + using (var csv = new CsvReader(reader, config)) { - csv.GetRecords<Foo>().ToList().Dump(); + List<Foo> records = csv.GetRecords<Foo>().ToList(); + + // These all print "True" + + Console.WriteLine(records.Count == 2); + Console.WriteLine(records[0].Id == 1); + Console.WriteLine(records[0].Amount == 1.234m); + Console.WriteLine(records[0].Amount2 == 1234); + Console.WriteLine(records[0].IsBool == true); + Console.WriteLine(records[0].Constant == "bar"); + Console.WriteLine(records[0].Optional == null); + Console.WriteLine(records[0].Ignored == null); + + Console.WriteLine(records[1].Amount == 1234); + Console.WriteLine(records[1].Amount2 == 1.234m); + } } -[Delimiter(",")] -[CultureInfo("")] // Set CultureInfo to InvariantCulture +[Delimiter("|")] +[CultureInfo("de-DE")] public class Foo { [Name("Identifier")] public int Id { get; set; } - + [Index(1)] - public string Name { get; set; } + public decimal Amount { get; set; } + [CultureInfo("InvariantCulture")] + public decimal Amount2 { get; set; } + [BooleanTrueValues("yes")] [BooleanFalseValues("no")] public bool IsBool { get; set; } - + [Constant("bar")] public string Constant { get; set; } - + [Optional] public string Optional { get; set; } - + [Ignore] - public string Ignored { get; set; } + public string Ignored { get; set; } } ``` diff --git a/src/CsvHelper/Configuration/Attributes/AllowCommentsAttribute.cs b/src/CsvHelper/Configuration/Attributes/AllowCommentsAttribute.cs index 1490cc92b..d847026e3 100644 --- a/src/CsvHelper/Configuration/Attributes/AllowCommentsAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/AllowCommentsAttribute.cs @@ -7,21 +7,21 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if comments are allowed. + /// A value indicating whether comments are allowed. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class AllowCommentsAttribute : Attribute, IClassMapper { /// <summary> - /// Gets a value indicating if comments are allowed. + /// Gets a value indicating whether comments are allowed. /// </summary> public bool AllowComments { get; private set; } /// <summary> - /// A value indicating if comments are allowed. + /// A value indicating whether comments are allowed. /// </summary> - /// <param name="allowComments">The value indicating id comments are allowed.</param> - public AllowCommentsAttribute(bool allowComments) + /// <param name="allowComments">The value indicating whether comments are allowed.</param> + public AllowCommentsAttribute(bool allowComments = true) { AllowComments = allowComments; } diff --git a/src/CsvHelper/Configuration/Attributes/CacheFieldsAttribute.cs b/src/CsvHelper/Configuration/Attributes/CacheFieldsAttribute.cs index 1f6b85957..1bf165690 100644 --- a/src/CsvHelper/Configuration/Attributes/CacheFieldsAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/CacheFieldsAttribute.cs @@ -8,7 +8,6 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> /// Cache fields that are created when parsing. - /// Default is false. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class CacheFieldsAttribute : Attribute, IClassMapper @@ -22,7 +21,7 @@ public class CacheFieldsAttribute : Attribute, IClassMapper /// Cache fields that are created when parsing. /// </summary> /// <param name="cacheFields"></param> - public CacheFieldsAttribute(bool cacheFields) + public CacheFieldsAttribute(bool cacheFields = true) { CacheFields = cacheFields; } diff --git a/src/CsvHelper/Configuration/Attributes/CountBytesAttribute.cs b/src/CsvHelper/Configuration/Attributes/CountBytesAttribute.cs index 165784ef4..92bd18c56 100644 --- a/src/CsvHelper/Configuration/Attributes/CountBytesAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/CountBytesAttribute.cs @@ -9,7 +9,7 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> /// A value indicating whether the number of bytes should - /// be counted while parsing. Default is false. This will slow down parsing + /// be counted while parsing. This will slow down parsing /// because it needs to get the byte count of every char for the given encoding. /// The <see cref="Encoding"/> needs to be set correctly for this to be accurate. /// </summary> @@ -18,7 +18,7 @@ public class CountBytesAttribute : Attribute, IClassMapper { /// <summary> /// A value indicating whether the number of bytes should - /// be counted while parsing. Default is false. This will slow down parsing + /// be counted while parsing. This will slow down parsing /// because it needs to get the byte count of every char for the given encoding. /// The <see cref="Encoding"/> needs to be set correctly for this to be accurate. /// </summary> @@ -26,12 +26,12 @@ public class CountBytesAttribute : Attribute, IClassMapper /// <summary> /// A value indicating whether the number of bytes should - /// be counted while parsing. Default is false. This will slow down parsing + /// be counted while parsing. This will slow down parsing /// because it needs to get the byte count of every char for the given encoding. /// The <see cref="Encoding"/> needs to be set correctly for this to be accurate. /// </summary> /// <param name="countBytes"></param> - public CountBytesAttribute(bool countBytes) + public CountBytesAttribute(bool countBytes = true) { CountBytes = countBytes; } diff --git a/src/CsvHelper/Configuration/Attributes/CultureInfoAttribute.cs b/src/CsvHelper/Configuration/Attributes/CultureInfoAttribute.cs index 3ab637f66..5b0809615 100644 --- a/src/CsvHelper/Configuration/Attributes/CultureInfoAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/CultureInfoAttribute.cs @@ -8,11 +8,12 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// The <see cref="CultureInfo"/> used when type converting. - /// This will override the global <see cref="CsvConfiguration.CultureInfo"/> - /// setting. Or set the same if the attribute is specified on class level. + /// When applied to a member, specifies the <see cref="System.Globalization.CultureInfo"/> + /// used when type converting the member. When applied to a type, the value of + /// <see cref="CsvConfiguration.CultureInfo"/> in the <see cref="CsvConfiguration"/> + /// returned by <see cref="CsvConfiguration.FromType{T}()"/> /// </summary> - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class CultureInfoAttribute : Attribute, IMemberMapper, IParameterMapper { /// <summary> @@ -20,15 +21,32 @@ public class CultureInfoAttribute : Attribute, IMemberMapper, IParameterMapper /// </summary> public CultureInfo CultureInfo { get; private set; } - /// <summary> - /// The <see cref="CultureInfo"/> used when type converting. - /// This will override the global <see cref="CsvConfiguration.CultureInfo"/> - /// setting. Or set the same if the attribute is specified on class level. - /// </summary> - /// <param name="culture">The culture.</param> - public CultureInfoAttribute(string culture) + /// <summary><inheritdoc cref="CultureInfoAttribute"/></summary> + /// <param name="name"> + /// The name of a culture (case insensitive), or the literal values <c>"InvariantCulture"</c>, + /// <c>"CurrentCulture"</c>, <c>"CurrentUICulture"</c>, <c>"InstalledUICulture"</c> to use the + /// corresponding static properties on <see cref="System.Globalization.CultureInfo"/>. + /// </param> + public CultureInfoAttribute(string name) { - CultureInfo = CultureInfo.GetCultureInfo(culture); + switch(name) + { + case nameof(CultureInfo.InvariantCulture): + CultureInfo = CultureInfo.InvariantCulture; + break; + case nameof(CultureInfo.CurrentCulture): + CultureInfo = CultureInfo.CurrentCulture; + break; + case nameof(CultureInfo.CurrentUICulture): + CultureInfo = CultureInfo.CurrentUICulture; + break; + case nameof(CultureInfo.InstalledUICulture): + CultureInfo = CultureInfo.InstalledUICulture; + break; + default: + CultureInfo = CultureInfo.GetCultureInfo(name); + break; + } } /// <inheritdoc /> diff --git a/src/CsvHelper/Configuration/Attributes/DetectColumnCountChangesAttribute.cs b/src/CsvHelper/Configuration/Attributes/DetectColumnCountChangesAttribute.cs index f31aaf84a..68485def1 100644 --- a/src/CsvHelper/Configuration/Attributes/DetectColumnCountChangesAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/DetectColumnCountChangesAttribute.cs @@ -8,7 +8,7 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> /// A value indicating whether changes in the column - /// count should be detected. If true, a <see cref="BadDataException"/> + /// count should be detected. If <see langword="true"/>, a <see cref="BadDataException"/> /// will be thrown if a different column count is detected. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] @@ -16,17 +16,17 @@ public class DetectColumnCountChangesAttribute : Attribute, IClassMapper { /// <summary> /// A value indicating whether changes in the column - /// count should be detected. If true, a <see cref="BadDataException"/> + /// count should be detected. If <see langword="true"/>, a <see cref="BadDataException"/> /// will be thrown if a different column count is detected. /// </summary> public bool DetectColumnCountChanges { get; private set; } /// <summary> /// A value indicating whether changes in the column - /// count should be detected. If true, a <see cref="BadDataException"/> + /// count should be detected. If <see langword="true"/>, a <see cref="BadDataException"/> /// will be thrown if a different column count is detected. /// </summary> - public DetectColumnCountChangesAttribute(bool detectColumnCountChanges) + public DetectColumnCountChangesAttribute(bool detectColumnCountChanges = true) { DetectColumnCountChanges = detectColumnCountChanges; } diff --git a/src/CsvHelper/Configuration/Attributes/DetectDelimiterAttribute.cs b/src/CsvHelper/Configuration/Attributes/DetectDelimiterAttribute.cs index 2c7da4563..6cfd2043d 100644 --- a/src/CsvHelper/Configuration/Attributes/DetectDelimiterAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/DetectDelimiterAttribute.cs @@ -8,7 +8,6 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> /// Detect the delimiter instead of using the delimiter from configuration. - /// Default is <c>false</c>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class DetectDelimiterAttribute : Attribute, IClassMapper @@ -21,7 +20,7 @@ public class DetectDelimiterAttribute : Attribute, IClassMapper /// <summary> /// Detect the delimiter instead of using the delimiter from configuration. /// </summary> - public DetectDelimiterAttribute(bool detectDelimiter) + public DetectDelimiterAttribute(bool detectDelimiter = true) { DetectDelimiter = detectDelimiter; } diff --git a/src/CsvHelper/Configuration/Attributes/EncodingAttribute.cs b/src/CsvHelper/Configuration/Attributes/EncodingAttribute.cs index ee378ba94..d24e251fc 100644 --- a/src/CsvHelper/Configuration/Attributes/EncodingAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/EncodingAttribute.cs @@ -18,14 +18,23 @@ public class EncodingAttribute : Attribute, IClassMapper /// </summary> public Encoding Encoding { get; private set; } - /// <summary> - /// The encoding used when counting bytes. - /// </summary> - /// <param name="encoding">The encoding.</param> - public EncodingAttribute(string encoding) + /// <summary> + /// The encoding used when counting bytes. + /// </summary> + /// <param name="name"><inheritdoc cref="Encoding.GetEncoding(string)"/></param> + public EncodingAttribute(string name) { - Encoding = Encoding.GetEncoding(encoding); - } + Encoding = Encoding.GetEncoding(name); + } + + /// <summary> + /// The encoding used when counting bytes. + /// </summary> + /// <param name="codepage"><inheritdoc cref="Encoding.GetEncoding(int)"/></param> + public EncodingAttribute(int codepage) + { + Encoding = Encoding.GetEncoding(codepage); + } /// <inheritdoc /> public void ApplyTo(CsvConfiguration configuration) diff --git a/src/CsvHelper/Configuration/Attributes/EscapeAttribute.cs b/src/CsvHelper/Configuration/Attributes/EscapeAttribute.cs index 0d20d504d..9346484c8 100644 --- a/src/CsvHelper/Configuration/Attributes/EscapeAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/EscapeAttribute.cs @@ -9,7 +9,7 @@ namespace CsvHelper.Configuration.Attributes /// <summary> /// The escape character used to escape a quote inside a field. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class EscapeAttribute : Attribute, IClassMapper { /// <summary> @@ -21,7 +21,7 @@ public class EscapeAttribute : Attribute, IClassMapper /// The escape character used to escape a quote inside a field. /// </summary> /// <param name="escape">The escape character.</param> - public EscapeAttribute( char escape ) + public EscapeAttribute(char escape) { Escape = escape; } diff --git a/src/CsvHelper/Configuration/Attributes/ExceptionMessagesContainRawDataAttribute.cs b/src/CsvHelper/Configuration/Attributes/ExceptionMessagesContainRawDataAttribute.cs index 2cb960824..7d754080f 100644 --- a/src/CsvHelper/Configuration/Attributes/ExceptionMessagesContainRawDataAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/ExceptionMessagesContainRawDataAttribute.cs @@ -7,25 +7,23 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if exception messages contain raw CSV data. - /// <c>true</c> if exception contain raw CSV data, otherwise <c>false</c>. - /// Default is <c>true</c>. + /// A value indicating whether exception messages contain raw CSV data. + /// <see langword="true"/> if exceptions contain raw CSV data, otherwise <see langword="false"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ExceptionMessagesContainRawDataAttribute : Attribute, IClassMapper { /// <summary> - /// A value indicating if exception messages contain raw CSV data. - /// <c>true</c> if exception contain raw CSV data, otherwise <c>false</c>. + /// A value indicating whether exception messages contain raw CSV data. + /// <see langword="true"/> if exceptions contain raw CSV data, otherwise <see langword="false"/>. /// </summary> public bool ExceptionMessagesContainRawData { get; private set; } /// <summary> - /// A value indicating if exception messages contain raw CSV data. - /// <c>true</c> if exception contain raw CSV data, otherwise <c>false</c>. + /// A value indicating whether exception messages contain raw CSV data. + /// <see langword="true"/> if exceptions contain raw CSV data, otherwise <see langword="false"/>. /// </summary> - /// <param name="exceptionMessagesContainRawData"></param> - public ExceptionMessagesContainRawDataAttribute(bool exceptionMessagesContainRawData) + public ExceptionMessagesContainRawDataAttribute(bool exceptionMessagesContainRawData = true) { ExceptionMessagesContainRawData = exceptionMessagesContainRawData; } diff --git a/src/CsvHelper/Configuration/Attributes/HasHeaderRecordAttribute.cs b/src/CsvHelper/Configuration/Attributes/HasHeaderRecordAttribute.cs index b0d93ae86..4c2f0252f 100644 --- a/src/CsvHelper/Configuration/Attributes/HasHeaderRecordAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/HasHeaderRecordAttribute.cs @@ -7,21 +7,21 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if the CSV file has a header record. + /// A value indicating whether the CSV file has a header record. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class HasHeaderRecordAttribute : Attribute, IClassMapper { /// <summary> - /// Gets a value indicating if the CSV file has a header record. + /// Gets a value indicating whether the CSV file has a header record. /// </summary> public bool HasHeaderRecord { get; private set; } /// <summary> - /// A value indicating if the CSV file has a header record. + /// A value indicating whether the CSV file has a header record. /// </summary> - /// <param name="hasHeaderRecord">A value indicating if the CSV file has a header record.</param> - public HasHeaderRecordAttribute( bool hasHeaderRecord ) + /// <param name="hasHeaderRecord">A value indicating whether the CSV file has a header record.</param> + public HasHeaderRecordAttribute(bool hasHeaderRecord = true) { HasHeaderRecord = hasHeaderRecord; } diff --git a/src/CsvHelper/Configuration/Attributes/HeaderPrefixAttribute.cs b/src/CsvHelper/Configuration/Attributes/HeaderPrefixAttribute.cs index 7c28ec79f..b2f30e332 100644 --- a/src/CsvHelper/Configuration/Attributes/HeaderPrefixAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/HeaderPrefixAttribute.cs @@ -18,7 +18,7 @@ public class HeaderPrefixAttribute : Attribute, IMemberReferenceMapper, IParamet public string? Prefix { get; private set; } /// <summary> - /// Gets a value indicating if the prefix should inherit parent prefixes. + /// Gets a value indicating whether the prefix should inherit parent prefixes. /// </summary> public bool Inherit { get; private set; } diff --git a/src/CsvHelper/Configuration/Attributes/IgnoreBlankLinesAttribute.cs b/src/CsvHelper/Configuration/Attributes/IgnoreBlankLinesAttribute.cs index c2705686e..51f2f4f9d 100644 --- a/src/CsvHelper/Configuration/Attributes/IgnoreBlankLinesAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/IgnoreBlankLinesAttribute.cs @@ -7,21 +7,20 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if blank lines should be ignored when reading. + /// A value indicating whether blank lines should be ignored when reading. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class IgnoreBlankLinesAttribute : Attribute, IClassMapper { /// <summary> - /// Gets a value indicating if blank lines should be ignored when reading. + /// Gets a value indicating whether blank lines should be ignored when reading. /// </summary> public bool IgnoreBlankLines { get; private set; } /// <summary> - /// A value indicating if blank lines should be ignored when reading. + /// A value indicating whether blank lines should be ignored when reading. /// </summary> - /// <param name="ignoreBlankLines">The Ignore Blank Lines Flag.</param> - public IgnoreBlankLinesAttribute( bool ignoreBlankLines ) + public IgnoreBlankLinesAttribute(bool ignoreBlankLines = true) { IgnoreBlankLines = ignoreBlankLines; } diff --git a/src/CsvHelper/Configuration/Attributes/IgnoreReferencesAttribute.cs b/src/CsvHelper/Configuration/Attributes/IgnoreReferencesAttribute.cs index 05e7b0e52..86eef9ff6 100644 --- a/src/CsvHelper/Configuration/Attributes/IgnoreReferencesAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/IgnoreReferencesAttribute.cs @@ -8,26 +8,25 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> /// Gets a value indicating whether references - /// should be ignored when auto mapping. <c>true</c> to ignore - /// references, otherwise <c>false</c>. Default is false. + /// should be ignored when auto mapping. <see langword="true"/> to ignore + /// references, otherwise <see langword="false"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class IgnoreReferencesAttribute : Attribute, IClassMapper { /// <summary> /// Gets a value indicating whether references - /// should be ignored when auto mapping. <c>true</c> to ignore - /// references, otherwise <c>false</c>. Default is false. + /// should be ignored when auto mapping. <see langword="true"/> to ignore + /// references, otherwise <see langword="false"/>. /// </summary> public bool IgnoreReferences { get; private set; } /// <summary> /// Gets a value indicating whether references - /// should be ignored when auto mapping. <c>true</c> to ignore - /// references, otherwise <c>false</c>. Default is false. + /// should be ignored when auto mapping. <see langword="true"/> to ignore + /// references, otherwise <see langword="false"/>. /// </summary> - /// <param name="ignoreReferences">Ignore references value.</param> - public IgnoreReferencesAttribute(bool ignoreReferences) + public IgnoreReferencesAttribute(bool ignoreReferences = true) { IgnoreReferences = ignoreReferences; } diff --git a/src/CsvHelper/Configuration/Attributes/IncludePrivateMembersAttribute.cs b/src/CsvHelper/Configuration/Attributes/IncludePrivateMembersAttribute.cs index 92c7c1b2a..55e27d5f9 100644 --- a/src/CsvHelper/Configuration/Attributes/IncludePrivateMembersAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/IncludePrivateMembersAttribute.cs @@ -7,21 +7,20 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if private member should be read from and written to. + /// A value indicating whether private members should be read from and written to. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class IncludePrivateMembersAttribute : Attribute, IClassMapper { /// <summary> - /// Gets a value indicating if private member should be read from and written to. + /// Gets a value indicating whether private members should be read from and written to. /// </summary> public bool IncludePrivateMembers { get; private set; } /// <summary> - /// A value indicating if private member should be read from and written to. + /// A value indicating whether private members should be read from and written to. /// </summary> - /// <param name="includePrivateMembers">The Include Private Members Flag.</param> - public IncludePrivateMembersAttribute( bool includePrivateMembers ) + public IncludePrivateMembersAttribute(bool includePrivateMembers = true) { IncludePrivateMembers = includePrivateMembers; } diff --git a/src/CsvHelper/Configuration/Attributes/IndexAttribute.cs b/src/CsvHelper/Configuration/Attributes/IndexAttribute.cs index 6694aed12..3db1a4241 100644 --- a/src/CsvHelper/Configuration/Attributes/IndexAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/IndexAttribute.cs @@ -12,7 +12,7 @@ namespace CsvHelper.Configuration.Attributes /// will be written in the order of the field /// indexes. /// </summary> - [AttributeUsage( AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class IndexAttribute : Attribute, IMemberMapper, IParameterMapper { /// <summary> @@ -33,7 +33,7 @@ public class IndexAttribute : Attribute, IMemberMapper, IParameterMapper /// </summary> /// <param name="index">The index.</param> /// <param name="indexEnd">The index end.</param> - public IndexAttribute( int index, int indexEnd = -1 ) + public IndexAttribute(int index, int indexEnd = -1) { Index = index; IndexEnd = indexEnd; diff --git a/src/CsvHelper/Configuration/Attributes/InjectionCharactersAttribute.cs b/src/CsvHelper/Configuration/Attributes/InjectionCharactersAttribute.cs index 66f696468..b1ea84a5d 100644 --- a/src/CsvHelper/Configuration/Attributes/InjectionCharactersAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/InjectionCharactersAttribute.cs @@ -11,6 +11,7 @@ namespace CsvHelper.Configuration.Attributes /// <summary> /// Gets the characters that are used for injection attacks. /// </summary> + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class InjectionCharactersAttribute : Attribute, IClassMapper { /// <summary> diff --git a/src/CsvHelper/Configuration/Attributes/LineBreakInQuotedFieldIsBadDataAttribute.cs b/src/CsvHelper/Configuration/Attributes/LineBreakInQuotedFieldIsBadDataAttribute.cs index db95cbcd2..cea3934e1 100644 --- a/src/CsvHelper/Configuration/Attributes/LineBreakInQuotedFieldIsBadDataAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/LineBreakInQuotedFieldIsBadDataAttribute.cs @@ -7,25 +7,23 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// A value indicating if a line break found in a quote field should - /// be considered bad data. <c>true</c> to consider a line break bad data, otherwise <c>false</c>. - /// Defaults to false. + /// A value indicating whether a line break found in a quote field should + /// be considered bad data. <see langword="true"/> to consider a line break bad data, otherwise <see langword="false"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class LineBreakInQuotedFieldIsBadDataAttribute : Attribute, IClassMapper { /// <summary> - /// A value indicating if a line break found in a quote field should - /// be considered bad data. <c>true</c> to consider a line break bad data, otherwise <c>false</c>. + /// A value indicating whether a line break found in a quote field should + /// be considered bad data. <see langword="true"/> to consider a line break bad data, otherwise <see langword="false"/>. /// </summary> public bool LineBreakInQuotedFieldIsBadData { get; private set; } /// <summary> - /// A value indicating if a line break found in a quote field should - /// be considered bad data. <c>true</c> to consider a line break bad data, otherwise <c>false</c>. + /// A value indicating whether a line break found in a quote field should + /// be considered bad data. <see langword="true"/> to consider a line break bad data, otherwise <see langword="false"/>. /// </summary> - /// <param name="lineBreakInQuotedFieldIsBadData"></param> - public LineBreakInQuotedFieldIsBadDataAttribute(bool lineBreakInQuotedFieldIsBadData) + public LineBreakInQuotedFieldIsBadDataAttribute(bool lineBreakInQuotedFieldIsBadData = true) { LineBreakInQuotedFieldIsBadData = lineBreakInQuotedFieldIsBadData; } diff --git a/src/CsvHelper/Configuration/Attributes/QuoteAttribute.cs b/src/CsvHelper/Configuration/Attributes/QuoteAttribute.cs index 93b5887f2..cf66834a2 100644 --- a/src/CsvHelper/Configuration/Attributes/QuoteAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/QuoteAttribute.cs @@ -9,7 +9,7 @@ namespace CsvHelper.Configuration.Attributes /// <summary> /// The character used to quote fields. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class QuoteAttribute : Attribute, IClassMapper { /// <summary> @@ -21,7 +21,7 @@ public class QuoteAttribute : Attribute, IClassMapper /// The character used to quote fields. /// </summary> /// <param name="quote">The quote character.</param> - public QuoteAttribute( char quote ) + public QuoteAttribute(char quote) { Quote = quote; } diff --git a/src/CsvHelper/Configuration/Attributes/TrimOptionsAttribute.cs b/src/CsvHelper/Configuration/Attributes/TrimOptionsAttribute.cs index 1b2f645be..ca8abd52a 100644 --- a/src/CsvHelper/Configuration/Attributes/TrimOptionsAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/TrimOptionsAttribute.cs @@ -9,7 +9,7 @@ namespace CsvHelper.Configuration.Attributes /// <summary> /// The fields trimming options. /// </summary> - [AttributeUsage( AttributeTargets.Class, AllowMultiple = false, Inherited = true )] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class TrimOptionsAttribute : Attribute, IClassMapper { /// <summary> @@ -21,7 +21,7 @@ public class TrimOptionsAttribute : Attribute, IClassMapper /// The fields trimming options. /// </summary> /// <param name="trimOptions">The TrimOptions.</param> - public TrimOptionsAttribute( TrimOptions trimOptions ) + public TrimOptionsAttribute(TrimOptions trimOptions) { TrimOptions = trimOptions; } diff --git a/src/CsvHelper/Configuration/Attributes/UseNewObjectForNullReferenceMembersAttribute.cs b/src/CsvHelper/Configuration/Attributes/UseNewObjectForNullReferenceMembersAttribute.cs index 6bfbf3763..d605b7551 100644 --- a/src/CsvHelper/Configuration/Attributes/UseNewObjectForNullReferenceMembersAttribute.cs +++ b/src/CsvHelper/Configuration/Attributes/UseNewObjectForNullReferenceMembersAttribute.cs @@ -7,33 +7,32 @@ namespace CsvHelper.Configuration.Attributes { /// <summary> - /// Gets a value indicating that during writing if a new - /// object should be created when a reference member is null. - /// True to create a new object and use it's defaults for the - /// fields, or false to leave the fields empty for all the - /// reference member's member. + /// Gets a value indicating that during writing whether a new + /// object should be created when a reference member is <see langword="null"/>. + /// <see langword="true"/> to create a new object and use its defaults for the + /// fields, or <see langword="false"/> to leave the fields empty for all the + /// reference member's members. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class UseNewObjectForNullReferenceMembersAttribute : Attribute, IClassMapper { /// <summary> - /// Gets a value indicating that during writing if a new - /// object should be created when a reference member is null. - /// True to create a new object and use it's defaults for the - /// fields, or false to leave the fields empty for all the - /// reference member's member. + /// Gets a value indicating that during writing whether a new + /// object should be created when a reference member is <see langword="null"/>. + /// <see langword="true"/> to create a new object and use its defaults for the + /// fields, or <see langword="false"/> to leave the fields empty for all the + /// reference member's members. /// </summary> public bool UseNewObjectForNullReferenceMembers { get; private set; } /// <summary> - /// Gets a value indicating that during writing if a new - /// object should be created when a reference member is null. - /// True to create a new object and use it's defaults for the - /// fields, or false to leave the fields empty for all the - /// reference member's member. + /// Gets a value indicating that during writing whether a new + /// object should be created when a reference member is <see langword="null"/>. + /// <see langword="true"/> to create a new object and use its defaults for the + /// fields, or <see langword="false"/> to leave the fields empty for all the + /// reference member's members. /// </summary> - /// <param name="useNewObjectForNullReferenceMembers">The value.</param> - public UseNewObjectForNullReferenceMembersAttribute(bool useNewObjectForNullReferenceMembers) + public UseNewObjectForNullReferenceMembersAttribute(bool useNewObjectForNullReferenceMembers = true) { UseNewObjectForNullReferenceMembers = useNewObjectForNullReferenceMembers; } diff --git a/src/CsvHelper/Configuration/CsvConfiguration.cs b/src/CsvHelper/Configuration/CsvConfiguration.cs index 51636a28e..5c92a50f5 100644 --- a/src/CsvHelper/Configuration/CsvConfiguration.cs +++ b/src/CsvHelper/Configuration/CsvConfiguration.cs @@ -11,7 +11,6 @@ using System.Text; using CsvHelper.Configuration.Attributes; using CsvHelper.Delegates; -using CsvHelper.TypeConversion; namespace CsvHelper.Configuration { @@ -165,21 +164,14 @@ public virtual string NewLine /// <summary> /// Initializes a new instance of the <see cref="CsvConfiguration"/> class /// using the given <see cref="System.Globalization.CultureInfo"/>. Since <see cref="Delimiter"/> - /// uses <see cref="CultureInfo"/> for it's default, the given <see cref="System.Globalization.CultureInfo"/> + /// uses <see cref="CultureInfo"/> for its default, the given <see cref="System.Globalization.CultureInfo"/> /// will be used instead. /// </summary> /// <param name="cultureInfo">The culture information.</param> - /// <param name="attributesType">The type that contains the configuration attributes. - /// This will call <see cref="ApplyAttributes(Type)"/> automatically.</param> - public CsvConfiguration(CultureInfo cultureInfo, Type? attributesType = null) + public CsvConfiguration(CultureInfo cultureInfo) { CultureInfo = cultureInfo; Delimiter = cultureInfo.TextInfo.ListSeparator; - - if (attributesType != null) - { - ApplyAttributes(attributesType); - } } /// <summary> @@ -236,5 +228,87 @@ public CsvConfiguration ApplyAttributes(Type type) return this; } + + /// <summary> + /// Creates a <see cref="CsvConfiguration"/> instance configured using CsvHelper attributes applied + /// to <typeparamref name="T"/> at the type-level. This method requires <typeparamref name="T"/> to + /// be annotated with <see cref="CultureInfoAttribute"/> (or to sub-class a type which is). + /// </summary> + /// <typeparam name="T"> + /// The type whose attributes should be used to configure the <see cref="CsvConfiguration"/> instance. + /// This is normally the type you are intending to map for reading and writing. + /// </typeparam> + /// <returns>A new <see cref="CsvConfiguration"/> instance configured with attributes applied to <typeparamref name="T"/>.</returns> + /// <remarks> + /// CsvHelper attributes applied to members and parameters do not influence the return value of this method. + /// Such attributes do not define values which are used in <see cref="CsvConfiguration"/> and instead influence + /// the maps which are built and used during reading and writing. See <see cref="MemberMap"/> and <see cref="ParameterMap"/>. + /// </remarks> + /// <exception cref="ConfigurationException">If <typeparamref name="T"/> is not annotated with <see cref="CultureInfoAttribute"/>.</exception> + /// <exception cref="ArgumentNullException">If the argument to the <see cref="CultureInfoAttribute"/> is <see langword="null"/>.</exception> + /// <exception cref="CultureNotFoundException">If the argument to the <see cref="CultureInfoAttribute"/> does not specify a supported culture.</exception> + public static CsvConfiguration FromType<T>() + { + return FromType(typeof(T)); + } + + /// <summary> + /// Creates a <see cref="CsvConfiguration"/> instance configured using <paramref name="cultureInfo"/> + /// and CsvHelper attributes applied to <typeparamref name="T"/> at the type-level. + /// This method ignores any <see cref="CultureInfoAttribute"/> applied to <typeparamref name="T"/>. + /// </summary> + /// <typeparam name="T"><inheritdoc cref="FromType{T}()"/></typeparam> + /// <param name="cultureInfo">The <see cref="CultureInfo"/> to configure the returned <see cref="CsvConfiguration"/> with.</param> + /// <returns>A new <see cref="CsvConfiguration"/> instance configured with <paramref name="cultureInfo"/> and attributes applied to <typeparamref name="T"/>.</returns> + /// <remarks><inheritdoc cref="FromType{T}()"/></remarks> + public static CsvConfiguration FromType<T>(CultureInfo cultureInfo) + { + return FromType(typeof(T), cultureInfo); + } + + /// <summary> + /// Creates a <see cref="CsvConfiguration"/> instance configured using CsvHelper attributes applied + /// to <paramref name="type"/> at the type-level. This method requires <paramref name="type"/> to + /// be annotated with <see cref="CultureInfoAttribute"/> (or to sub-class a type which is). + /// </summary> + /// <param name="type"><inheritdoc cref="FromType{T}()" path="/typeparam"/></param> + /// <returns>A new <see cref="CsvConfiguration"/> instance configured with attributes applied to <paramref name="type"/>.</returns> + /// <remarks> + /// CsvHelper attributes applied to members and parameters do not influence the return value of this method. + /// Such attributes do not define values which are used in <see cref="CsvConfiguration"/> and instead influence + /// the maps which are built and used during reading and writing. See <see cref="MemberMap"/> and <see cref="ParameterMap"/>. + /// </remarks> + /// <exception cref="ConfigurationException">If <paramref name="type"/> is not annotated with <see cref="CultureInfoAttribute"/>.</exception> + /// <exception cref="ArgumentNullException">If the argument to the <see cref="CultureInfoAttribute"/> is <see langword="null"/>.</exception> + /// <exception cref="CultureNotFoundException">If the argument to the <see cref="CultureInfoAttribute"/> does not specify a supported culture.</exception> + public static CsvConfiguration FromType(Type type) + { + var cultureInfoAttribute = (CultureInfoAttribute?)Attribute.GetCustomAttribute(type, typeof(CultureInfoAttribute)); + + if (cultureInfoAttribute is null) + { + throw new ConfigurationException($"{type} is not configured with {nameof(CultureInfoAttribute)} at the type level"); + } + + var config = new CsvConfiguration(cultureInfoAttribute.CultureInfo); + config.ApplyAttributes(type); + return config; + } + + /// <summary> + /// Creates a <see cref="CsvConfiguration"/> instance configured using <paramref name="cultureInfo"/> + /// and CsvHelper attributes applied to <paramref name="type"/> at the type-level. + /// This method ignores any <see cref="CultureInfoAttribute"/> applied to <paramref name="type"/>. + /// </summary> + /// <param name="type"><inheritdoc cref="FromType{T}()" path="/typeparam"/></param> + /// <param name="cultureInfo"><inheritdoc cref="FromType{T}(CultureInfo)"/></param> + /// <returns>A new <see cref="CsvConfiguration"/> instance configured with <paramref name="cultureInfo"/> and attributes applied to <paramref name="type"/></returns> + /// <remarks><inheritdoc cref="FromType{T}()"/></remarks> + public static CsvConfiguration FromType(Type type, CultureInfo cultureInfo) + { + var config = new CsvConfiguration(cultureInfo); + config.ApplyAttributes(type); + return config; + } } }
diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/AllowCommentsTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/AllowCommentsTests.cs index e5fb1ebf9..f417c19ba 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/AllowCommentsTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/AllowCommentsTests.cs @@ -14,12 +14,20 @@ public class AllowCommentsTests [Fact] public void AllowCommentsTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(AllowCommentsTestClass)); - Assert.True(config.AllowComments); + Assert.True(CsvConfiguration.FromType<AllowCommentsTrueTestClass>(CultureInfo.InvariantCulture).AllowComments); + Assert.False(CsvConfiguration.FromType<AllowCommentsFalseTestClass>(CultureInfo.InvariantCulture).AllowComments); } - [AllowComments(true)] - private class AllowCommentsTestClass + [AllowComments] + private class AllowCommentsTrueTestClass + { + public int Id { get; set; } + + public string Name { get; set; } + } + + [AllowComments(false)] + private class AllowCommentsFalseTestClass { public int Id { get; set; } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/BufferSizeTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/BufferSizeTests.cs index dd3549819..b6825e2e3 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/BufferSizeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/BufferSizeTests.cs @@ -15,7 +15,7 @@ public class BufferSizeTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(2, config.BufferSize); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/CacheFieldsTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/CacheFieldsTests.cs index bfc1c5232..1badda9d5 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/CacheFieldsTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/CacheFieldsTests.cs @@ -10,11 +10,14 @@ public class CacheFieldsTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.CacheFields); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).CacheFields); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).CacheFields); } - [CacheFields(true)] - private class Foo { } + [CacheFields] + private class FooTrue { } + + [CacheFields(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/CommentTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/CommentTests.cs index 64baf141d..0924bcd2e 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/CommentTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/CommentTests.cs @@ -16,7 +16,7 @@ public class CommentTests [Fact] public void CommentTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(CommentTestClass)); + var config = CsvConfiguration.FromType<CommentTestClass>(CultureInfo.InvariantCulture); Assert.Equal('x', config.Comment); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/CountBytesTest.cs b/tests/CsvHelper.Tests/Mappings/Attribute/CountBytesTest.cs index c4847cdbe..27cd41c23 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/CountBytesTest.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/CountBytesTest.cs @@ -10,11 +10,14 @@ public class CountBytesTest [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.CountBytes); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).CountBytes); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).CountBytes); } - [CountBytes(true)] - private class Foo { } + [CountBytes] + private class FooTrue { } + + [CountBytes(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/DelimiterTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/DelimiterTests.cs index 331512668..2fc7ddeca 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/DelimiterTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/DelimiterTests.cs @@ -16,7 +16,7 @@ public class DelimiterTests [Fact] public void DelimiterReaderTest() { - var configuration = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(DelimiterTestClass)); + var configuration = CsvConfiguration.FromType<DelimiterTestClass>(CultureInfo.InvariantCulture); Assert.Equal("§", configuration.Delimiter); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/DetectColumnCountChangesTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/DetectColumnCountChangesTests.cs index 4fad81642..6da63ba84 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/DetectColumnCountChangesTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/DetectColumnCountChangesTests.cs @@ -10,11 +10,14 @@ public class DetectColumnCountChangesTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.DetectColumnCountChanges); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).DetectColumnCountChanges); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).DetectColumnCountChanges); } - [DetectColumnCountChanges(true)] - private class Foo { } + [DetectColumnCountChanges] + private class FooTrue { } + + [DetectColumnCountChanges(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterTests.cs index 1ccc0fb35..3fd9ef0f7 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterTests.cs @@ -10,11 +10,14 @@ public class DetectDelimiterTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.DetectDelimiter); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).DetectDelimiter); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).DetectDelimiter); } - [DetectDelimiter(true)] - private class Foo { } + [DetectDelimiter] + private class FooTrue { } + + [DetectDelimiter(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterValuesTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterValuesTests.cs index a1600015e..f99822822 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterValuesTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/DetectDelimiterValuesTests.cs @@ -15,7 +15,7 @@ public class DetectDelimiterValuesTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(new[] { "a", "b" }, config.DetectDelimiterValues); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/EncodingTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/EncodingTests.cs index 557775b55..ee4a7c19a 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/EncodingTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/EncodingTests.cs @@ -5,8 +5,6 @@ using CsvHelper.Configuration; using CsvHelper.Configuration.Attributes; using System.Globalization; -using System.IO; -using System.Linq; using System.Text; using Xunit; @@ -17,13 +15,20 @@ public class EncodingTests [Fact] public void EncodingTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(EncodingTestClass)); - - Assert.Equal(Encoding.ASCII, config.Encoding); + Assert.Equal(Encoding.ASCII, CsvConfiguration.FromType<EncodingNameTestClass>(CultureInfo.InvariantCulture).Encoding); + Assert.Equal(Encoding.ASCII, CsvConfiguration.FromType<EncodingCodepageTestClass>(CultureInfo.InvariantCulture).Encoding); } [Encoding("ASCII")] - private class EncodingTestClass + private class EncodingNameTestClass + { + public int Id { get; set; } + + public string Name { get; set; } + } + + [Encoding(20127)] + private class EncodingCodepageTestClass { public int Id { get; set; } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/EscapeTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/EscapeTests.cs index b3c3e7f5b..87c846a8d 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/EscapeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/EscapeTests.cs @@ -16,7 +16,7 @@ public class EscapeTests [Fact] public void EscapeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(EscapeTestClass)); + var config = CsvConfiguration.FromType<EscapeTestClass>(CultureInfo.InvariantCulture); Assert.Equal('x', config.Escape); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/ExceptionMessagesContainRawDataTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/ExceptionMessagesContainRawDataTests.cs index ce3688e33..244ac1759 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/ExceptionMessagesContainRawDataTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/ExceptionMessagesContainRawDataTests.cs @@ -1,11 +1,6 @@ using CsvHelper.Configuration; using CsvHelper.Configuration.Attributes; -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Xunit; namespace CsvHelper.Tests.Mappings.Attribute @@ -15,11 +10,14 @@ public class ExceptionMessagesContainRawDataTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.False(config.ExceptionMessagesContainRawData); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).ExceptionMessagesContainRawData); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).ExceptionMessagesContainRawData); } + [ExceptionMessagesContainRawData] + private class FooTrue { } + [ExceptionMessagesContainRawData(false)] - private class Foo { } + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/HasHeaderRecordTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/HasHeaderRecordTests.cs index 9fae8725b..a534860c5 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/HasHeaderRecordTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/HasHeaderRecordTests.cs @@ -14,13 +14,20 @@ public class HasHeaderRecordTests [Fact] public void HasHeaderRecordTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(HasHeaderRecordTestClass)); + Assert.True(CsvConfiguration.FromType<HasHeaderRecordTrueTestClass>(CultureInfo.InvariantCulture).HasHeaderRecord); + Assert.False(CsvConfiguration.FromType<HasHeaderRecordFalseTestClass>(CultureInfo.InvariantCulture).HasHeaderRecord); + } - Assert.False(config.HasHeaderRecord); + [HasHeaderRecord] + private class HasHeaderRecordTrueTestClass + { + public int Id { get; set; } + + public string Name { get; set; } } [HasHeaderRecord(false)] - private class HasHeaderRecordTestClass + private class HasHeaderRecordFalseTestClass { public int Id { get; set; } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreBlankLinesTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreBlankLinesTests.cs index b2ec8e07f..6b7feee9f 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreBlankLinesTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreBlankLinesTests.cs @@ -2,10 +2,9 @@ // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. // http://csvhelper.com +using CsvHelper.Configuration; using CsvHelper.Configuration.Attributes; using System.Globalization; -using System.IO; -using System.Linq; using Xunit; namespace CsvHelper.Tests.AttributeMapping @@ -15,18 +14,20 @@ public class IgnoreBlankLinesTests [Fact] public void IgnoreBlankLinesTest() { - using (var reader = new StringReader("Id,Name\r\n1,one\r\n")) - using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) - { - var records = csv.GetRecords<IgnoreBlankLinesTestClass>().ToList(); - var actual = csv.Configuration.IgnoreBlankLines; + Assert.True(CsvConfiguration.FromType<IgnoreBlankLinesTrueTestClass>(CultureInfo.InvariantCulture).IgnoreBlankLines); + Assert.False(CsvConfiguration.FromType<IgnoreBlankLinesFalseTestClass>(CultureInfo.InvariantCulture).IgnoreBlankLines); + } - Assert.True(actual); - } + [IgnoreBlankLines] + private class IgnoreBlankLinesTrueTestClass + { + public int Id { get; set; } + + public string Name { get; set; } } - [IgnoreBlankLines(true)] - private class IgnoreBlankLinesTestClass + [IgnoreBlankLines(false)] + private class IgnoreBlankLinesFalseTestClass { public int Id { get; set; } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreReferencesTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreReferencesTests.cs index f2839b6a0..daba9d682 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreReferencesTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/IgnoreReferencesTests.cs @@ -1,11 +1,6 @@ using CsvHelper.Configuration; using CsvHelper.Configuration.Attributes; -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Xunit; namespace CsvHelper.Tests.Mappings.Attribute @@ -15,11 +10,14 @@ public class IgnoreReferencesTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.IgnoreReferences); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).IgnoreReferences); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).IgnoreReferences); } - [IgnoreReferences(true)] - private class Foo { } + [IgnoreReferences] + private class FooTrue { } + + [IgnoreReferences(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/IncludePrivateMembersTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/IncludePrivateMembersTests.cs index 2b219dcb6..fc11e6fba 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/IncludePrivateMembersTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/IncludePrivateMembersTests.cs @@ -12,14 +12,22 @@ namespace CsvHelper.Tests.AttributeMapping public class IncludePrivateMembersTests { [Fact] - public void TrimOptionsTest() + public void IncludePrivateMembersTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(IncludePrivateMembersTestClass)); - Assert.True(config.IncludePrivateMembers); + Assert.True(CsvConfiguration.FromType<IncludePrivateMembersTrueTestClass>(CultureInfo.InvariantCulture).IncludePrivateMembers); + Assert.False(CsvConfiguration.FromType<IncludePrivateMembersFalseTestClass>(CultureInfo.InvariantCulture).IncludePrivateMembers); } - [IncludePrivateMembers(true)] - private class IncludePrivateMembersTestClass + [IncludePrivateMembers] + private class IncludePrivateMembersTrueTestClass + { + public int Id { get; set; } + + public string Name { get; set; } + } + + [IncludePrivateMembers(false)] + private class IncludePrivateMembersFalseTestClass { public int Id { get; set; } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionCharactersTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionCharactersTests.cs index b4fc82cd3..211582343 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionCharactersTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionCharactersTests.cs @@ -15,7 +15,7 @@ public class InjectionCharactersTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(new[] { 'a', 'b' }, config.InjectionCharacters); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionEscapeCharacterTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionEscapeCharacterTests.cs index e118ea23e..697ddbdae 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionEscapeCharacterTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionEscapeCharacterTests.cs @@ -15,7 +15,7 @@ public class InjectionEscapeCharacterTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal('a', config.InjectionEscapeCharacter); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionOptionsTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionOptionsTests.cs index 7a0300355..94cc7d6b8 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/InjectionOptionsTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/InjectionOptionsTests.cs @@ -15,7 +15,7 @@ public class InjectionOptionsTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(InjectionOptions.Escape, config.InjectionOptions); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/LineBreakInQuotedFieldIsBadDataTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/LineBreakInQuotedFieldIsBadDataTests.cs index b9397801e..0e5707553 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/LineBreakInQuotedFieldIsBadDataTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/LineBreakInQuotedFieldIsBadDataTests.cs @@ -1,11 +1,6 @@ using CsvHelper.Configuration; using CsvHelper.Configuration.Attributes; -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Xunit; namespace CsvHelper.Tests.Mappings.Attribute @@ -15,11 +10,14 @@ public class LineBreakInQuotedFieldIsBadDataTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.True(config.LineBreakInQuotedFieldIsBadData); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).LineBreakInQuotedFieldIsBadData); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).LineBreakInQuotedFieldIsBadData); } - [LineBreakInQuotedFieldIsBadData(true)] - private class Foo { } + [LineBreakInQuotedFieldIsBadData] + private class FooTrue { } + + [LineBreakInQuotedFieldIsBadData(false)] + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/MaxFieldSizeTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/MaxFieldSizeTests.cs index b0a923196..3d662182d 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/MaxFieldSizeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/MaxFieldSizeTests.cs @@ -10,7 +10,7 @@ public class MaxFieldSizeTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(2, config.MaxFieldSize); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/MemberTypesTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/MemberTypesTests.cs index be21b325b..0fbc373ee 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/MemberTypesTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/MemberTypesTests.cs @@ -10,7 +10,7 @@ public class MemberTypesTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(MemberTypes.Fields, config.MemberTypes); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/ModeTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/ModeTests.cs index ca3586309..a4ca5cf98 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/ModeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/ModeTests.cs @@ -10,7 +10,7 @@ public class ModeTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(CsvMode.Escape, config.Mode); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/NewLineTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/NewLineTests.cs index 5d9ba80d6..12ac245d2 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/NewLineTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/NewLineTests.cs @@ -10,7 +10,7 @@ public class NewLineTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal("a", config.NewLine); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/ProcessFieldBufferSizeTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/ProcessFieldBufferSizeTests.cs index 63ea4330a..7d1f3bbfb 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/ProcessFieldBufferSizeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/ProcessFieldBufferSizeTests.cs @@ -10,7 +10,7 @@ public class ProcessFieldBufferSizeTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(2, config.ProcessFieldBufferSize); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/QuoteTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/QuoteTests.cs index 3b6fb4175..a72ace8da 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/QuoteTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/QuoteTests.cs @@ -14,7 +14,7 @@ public class QuoteTests [Fact] public void QuoteTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(QuoteTestClass)); + var config = CsvConfiguration.FromType<QuoteTestClass>(CultureInfo.InvariantCulture); Assert.Equal('x', config.Quote); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/TrimOptionsTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/TrimOptionsTests.cs index 6e7595ffc..5fbd73caf 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/TrimOptionsTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/TrimOptionsTests.cs @@ -16,7 +16,7 @@ public class TrimOptionsTests [Fact] public void TrimOptionsTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(TrimOptionsTestClass)); + var config = CsvConfiguration.FromType<TrimOptionsTestClass>(CultureInfo.InvariantCulture); Assert.Equal(TrimOptions.InsideQuotes, config.TrimOptions); } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/UseNewObjectForNullReferenceMembersTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/UseNewObjectForNullReferenceMembersTests.cs index d5608721d..412c6b623 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/UseNewObjectForNullReferenceMembersTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/UseNewObjectForNullReferenceMembersTests.cs @@ -10,11 +10,14 @@ public class UseNewObjectForNullReferenceMembersTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); - Assert.False(config.UseNewObjectForNullReferenceMembers); + Assert.True(CsvConfiguration.FromType<FooTrue>(CultureInfo.InvariantCulture).UseNewObjectForNullReferenceMembers); + Assert.False(CsvConfiguration.FromType<FooFalse>(CultureInfo.InvariantCulture).UseNewObjectForNullReferenceMembers); } + [UseNewObjectForNullReferenceMembers] + private class FooTrue { } + [UseNewObjectForNullReferenceMembers(false)] - private class Foo { } + private class FooFalse { } } } diff --git a/tests/CsvHelper.Tests/Mappings/Attribute/WhiteSpaceCharsTests.cs b/tests/CsvHelper.Tests/Mappings/Attribute/WhiteSpaceCharsTests.cs index 3abb02721..e1dee3efa 100644 --- a/tests/CsvHelper.Tests/Mappings/Attribute/WhiteSpaceCharsTests.cs +++ b/tests/CsvHelper.Tests/Mappings/Attribute/WhiteSpaceCharsTests.cs @@ -10,7 +10,7 @@ public class WhiteSpaceCharsTests [Fact] public void ConstructorAttributeTest() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Foo)); + var config = CsvConfiguration.FromType<Foo>(CultureInfo.InvariantCulture); Assert.Equal(new[] { 'a', 'b' }, config.WhiteSpaceChars); } diff --git a/tests/CsvHelper.Tests/Mappings/ConstructorParameter/CultureInfoAttributeTests.cs b/tests/CsvHelper.Tests/Mappings/ConstructorParameter/CultureInfoAttributeTests.cs index cb9d08dbb..b051e2efd 100644 --- a/tests/CsvHelper.Tests/Mappings/ConstructorParameter/CultureInfoAttributeTests.cs +++ b/tests/CsvHelper.Tests/Mappings/ConstructorParameter/CultureInfoAttributeTests.cs @@ -6,43 +6,54 @@ using CsvHelper.Configuration.Attributes; using CsvHelper.Tests.Mocks; using Xunit; -using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; -using System.Threading.Tasks; -using System.Threading; +using System; namespace CsvHelper.Tests.Mappings.ConstructorParameter { public class CultureInfoAttributeTests { - private const decimal AMOUNT = 123_456.789M; - private const string CULTURE = "fr-FR"; - private readonly string amount = AMOUNT.ToString(new CultureInfo(CULTURE)); - [Fact] public void AutoMap_WithCultureInfoAttributes_ConfiguresParameterMaps() - { - var config = new CsvConfiguration(CultureInfo.InvariantCulture); + { + var config = CsvConfiguration.FromType<Foo>(); var context = new CsvContext(config); var map = context.AutoMap<Foo>(); - Assert.Equal(2, map.ParameterMaps.Count); + Assert.Equal(3, map.ParameterMaps.Count); Assert.Null(map.ParameterMaps[0].Data.TypeConverterOptions.CultureInfo); - Assert.Equal(new CultureInfo(CULTURE), map.ParameterMaps[1].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(new CultureInfo("fr-FR"), map.ParameterMaps[1].Data.TypeConverterOptions.CultureInfo); + Assert.Null(map.ParameterMaps[2].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(CultureInfo.InvariantCulture, context.Configuration.CultureInfo); + } + + [Fact] + public void AutoMap_WithCultureInfoAttributes_ConfiguresMemberMaps() + { + var config = CsvConfiguration.FromType<Foo2>(); + var context = new CsvContext(config); + var map = context.AutoMap<Foo2>(); + + Assert.Equal(4, map.MemberMaps.Count); + Assert.Null(map.MemberMaps[0].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(new CultureInfo("fr-FR"), map.MemberMaps[1].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(CultureInfo.InvariantCulture, map.MemberMaps[2].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(new CultureInfo("ps-AF"), map.MemberMaps[3].Data.TypeConverterOptions.CultureInfo); + Assert.Equal(new CultureInfo("en-GB"), context.Configuration.CultureInfo); } [Fact] - public void GetRecords_WithCultureInfoAttributes_HasHeader_CreatesRecords() + public void GetRecords_WithCultureInfoAttributes_CreatesRecords() { var parser = new ParserMock { - { "id", "amount" }, - { "1", amount }, + { "id", "amount1", "amount2" }, + { "1", "1,234", "1,234" }, }; using (var csv = new CsvReader(parser)) { @@ -50,70 +61,164 @@ public void GetRecords_WithCultureInfoAttributes_HasHeader_CreatesRecords() Assert.Single(records); Assert.Equal(1, records[0].Id); - Assert.Equal(AMOUNT, records[0].Amount); + Assert.Equal(1.234m, records[0].Amount1); + Assert.Equal(1234, records[0].Amount2); } } [Fact] - public void GetRecords_WithCultureInfoAttributes_NoHeader_CreatesRecords() + public void WriteRecords_WithCultureInfoAttributes_DoesntUseParameterMaps() { - var config = new CsvConfiguration(CultureInfo.InvariantCulture) - { - HasHeaderRecord = false, - }; - var parser = new ParserMock(config) + var records = new List<Foo> { - { "1", amount }, + new Foo(1, 1.234m, 1.234m), }; - using (var csv = new CsvReader(parser)) + + using (var writer = new StringWriter()) + using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { - var records = csv.GetRecords<Foo>().ToList(); + csv.WriteRecords(records); - Assert.Single(records); - Assert.Equal(1, records[0].Id); - Assert.Equal(AMOUNT, records[0].Amount); - } + var expected = new StringBuilder(); + expected.Append("Id,Amount1,Amount2\r\n"); + expected.Append("1,1.234,1.234\r\n"); + + Assert.Equal(expected.ToString(), writer.ToString()); + } } [Fact] - public void WriteRecords_WithCultureInfoAttributes_DoesntUseParameterMaps() + public void WriteRecords_WithCultureInfoAttributes_DoesUseMemberMaps() { - var records = new List<Foo> + var records = new List<Foo2> { - new Foo(1, AMOUNT), + new Foo2 + { + Id = 1, + Amount1 = 1.234m, + Amount2 = 1.234m, + Amount3 = 1.234m, + }, }; - var prevCulture = Thread.CurrentThread.CurrentCulture; - try { - Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; - using (var writer = new StringWriter()) - using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) - { - csv.WriteRecords(records); + using (var writer = new StringWriter()) + using (var csv = new CsvWriter(writer, CultureInfo.GetCultureInfo("en-GB"))) + { + csv.WriteRecords(records); - var expected = new StringBuilder(); - expected.Append("Id,Amount\r\n"); - expected.Append($"1,{AMOUNT}\r\n"); + var expected = new StringBuilder(); + expected.Append("Id,Amount1,Amount2,Amount3\r\n"); + expected.Append("1,\"1,234\",1.234,1٫234\r\n"); - Assert.Equal(expected.ToString(), writer.ToString()); - } - } finally { - Thread.CurrentThread.CurrentCulture = prevCulture; - } + Assert.Equal(expected.ToString(), writer.ToString()); + } } - + + [CultureInfo(nameof(CultureInfo.InvariantCulture))] private class Foo { public int Id { get; private set; } - public decimal Amount { get; private set; } + public decimal Amount1 { get; private set; } + + public decimal Amount2 { get; private set; } - public Foo(int id, [CultureInfo(CULTURE)] decimal amount) + public Foo(int id, [CultureInfo("fr-FR")] decimal amount1, decimal amount2) { Id = id; - Amount = amount; + Amount1 = amount1; + Amount2 = amount2; } } + + [CultureInfo("en-GB")] + private class Foo2 + { + public int Id { get; set; } + + [CultureInfo("fr-FR")] + public decimal Amount1 { get; set; } + + [CultureInfo(nameof(CultureInfo.InvariantCulture))] + public decimal Amount2 { get; set; } + + [CultureInfo("ps-AF")] // Pashto (Afghanistan) uses U+066B ARABIC DECIMAL SEPARATOR (٫ instead of ,) + public decimal Amount3 { get; set; } + } + + [Fact] + public void CsvConfiguration_FromTypeWithParameter_IgnoresAttribute() + { + // First just validate we have an attribute to ignore + Assert.Equal(new CultureInfo("en-GB"), ((CultureInfoAttribute)System.Attribute.GetCustomAttribute(typeof(Foo2), typeof(CultureInfoAttribute))).CultureInfo); + + Assert.Equal(new CultureInfo("es-ES"), CsvConfiguration.FromType<Foo2>(CultureInfo.GetCultureInfo("es-ES")).CultureInfo); + } + + [Fact] + public void CsvConfiguration_FromType_NoAttribute_ThrowsConfigurationException() + { + Assert.Throws<ConfigurationException>(CsvConfiguration.FromType<NoAttribute>); + } + + [Fact] + public void CsvConfiguration_FromType_NullAttribute_ThrowsArgumentNullException() + { + Assert.Throws<ArgumentNullException>(CsvConfiguration.FromType<NullAttribute>); + } + + [Fact] + public void CsvConfiguration_FromType_InvalidAttribute_ThrowsCultureNotFoundException() + { + Assert.Throws<CultureNotFoundException>(CsvConfiguration.FromType<InvalidAttribute>); + } + + [Fact] + public void CsvConfiguration_FromType_DerivedNoAttribute_TakesBaseClassValue() + { + Assert.Equal(new CultureInfo("en-GB"), CsvConfiguration.FromType<Foo2DerivedNoAttribute>().CultureInfo); + } + + [Fact] + public void CsvConfiguration_FromType_DerivedWithAttribute_TakesDerviedClassValue() + { + Assert.Equal(CultureInfo.CurrentCulture, CsvConfiguration.FromType<Foo2DerivedWithAttribute>().CultureInfo); + } + private class NoAttribute + { + [CultureInfo("fr-FR")] + public int Id { get; set; } + + [CultureInfo("fr-FR")] + public decimal Amount { get; set; } + } + + [CultureInfo(null)] + private class NullAttribute + { + [CultureInfo("fr-FR")] + public int Id { get; set; } + + [CultureInfo("fr-FR")] + public decimal Amount { get; set; } + } + + [CultureInfo("invalid")] + private class InvalidAttribute + { + [CultureInfo("fr-FR")] + public int Id { get; set; } + + [CultureInfo("fr-FR")] + public decimal Amount { get; set; } + } + + private class Foo2DerivedNoAttribute : Foo2 + { } + + [CultureInfo(nameof(CultureInfo.CurrentCulture))] + private class Foo2DerivedWithAttribute : Foo2 + { } } }
New class level attributes are ignored, e.g. DelimiterAttribute I have been experimenting with the new class level attributes for things like Delimiter, HasHeaderRecord, IgnoreBlankLines, etc. which were introduced in version 30.0.0. However, they don't appear to be working and they are ignored. ```c# [Delimiter("|")] [HasHeaderRecord(false)] [IgnoreBlankLines(true)] [TrimOptions(TrimOptions.Trim)] public class Result { [Index(0)] public string Type { get; set; } [Index(1)] public string Name { get; set; } [Index(3)] public string Ccy { get; set; } } //This works with settings in config file var config = new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ",", HasHeaderRecord = false, IgnoreBlankLines = true, TrimOptions = TrimOptions.Trim, }; using (var reader = new StreamReader(file)) using (var csv = new CsvReader(reader, config)) { results.AddRange(csv.GetRecords<Result>()); } //This does not work with settings as class level attributes on Result class using (var reader = new StreamReader(file)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { results.AddRange(csv.GetRecords<Result>()); } ```
You need to either pass the `Type` into the constructor or call `ApplyAttributes`. ```cs new CsvConfiguration(CultureInfo.InvariantCulture, typeof(Result)); // or new CsvConfiguration(CultureInfo.InvariantCulture).ApplyAttributes<Result>(); // or new CsvConfiguration(CultureInfo.InvariantCulture).ApplyAttributes(typeof(Result)); ``` Maybe it could be called automatically when passed into the `CsvReader` or `CsvWriter` constructor. Great that works, thanks... I ran into the same issue. Maybe [this page](https://joshclose.github.io/CsvHelper/examples/configuration/attributes/) needs to be amended to add the configuration block ? Yes. I'll reopen this and change to documentation.
2023-02-25T15:37:45Z
0.1
['CsvHelper.Tests.AttributeMapping.AllowCommentsTests.AllowCommentsTest', 'CsvHelper.Tests.Mappings.Attribute.CacheFieldsTests.ConstructorAttributeTest', 'CsvHelper.Tests.Mappings.Attribute.CountBytesTest.ConstructorAttributeTest', 'CsvHelper.Tests.Mappings.Attribute.DetectColumnCountChangesTests.ConstructorAttributeTest', 'CsvHelper.Tests.Mappings.Attribute.DetectDelimiterTests.ConstructorAttributeTest', 'CsvHelper.Tests.AttributeMapping.EncodingTests.EncodingTest', 'CsvHelper.Tests.Mappings.Attribute.ExceptionMessagesContainRawDataTests.ConstructorAttributeTest', 'CsvHelper.Tests.AttributeMapping.HasHeaderRecordTests.HasHeaderRecordTest', 'CsvHelper.Tests.AttributeMapping.IgnoreBlankLinesTests.IgnoreBlankLinesTest', 'CsvHelper.Tests.Mappings.Attribute.IgnoreReferencesTests.ConstructorAttributeTest', 'CsvHelper.Tests.AttributeMapping.IncludePrivateMembersTests.IncludePrivateMembersTest', 'CsvHelper.Tests.Mappings.Attribute.LineBreakInQuotedFieldIsBadDataTests.ConstructorAttributeTest', 'CsvHelper.Tests.Mappings.Attribute.UseNewObjectForNullReferenceMembersTests.ConstructorAttributeTest']
['CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.AutoMap_WithCultureInfoAttributes_ConfiguresParameterMaps', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.AutoMap_WithCultureInfoAttributes_ConfiguresMemberMaps', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.GetRecords_WithCultureInfoAttributes_CreatesRecords', 'CsvHelper.Tests.Mappings.ConstructorParameter.FormatAttributeTests.WriteRecords_WithCultureInfoAttributes_DoesntUseParameterMaps', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.WriteRecords_WithCultureInfoAttributes_DoesUseMemberMaps', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.CsvConfiguration_FromTypeWithParameter_IgnoresAttribute', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.CsvConfiguration_FromType_NoAttribute_ThrowsConfigurationException', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.CsvConfiguration_FromType_NullAttribute_ThrowsArgumentNullException', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.CsvConfiguration_FromType_DerivedNoAttribute_TakesBaseClassValue', 'CsvHelper.Tests.Mappings.ConstructorParameter.CultureInfoAttributeTests.CsvConfiguration_FromType_DerivedWithAttribute_TakesDerviedClassValue']
autofac/Autofac
autofac__autofac-1451
07cac9047f4059de2d72834042c9649cbd228085
diff --git a/src/Autofac/Builder/RegistrationData.cs b/src/Autofac/Builder/RegistrationData.cs index f14e6bcfb..4e5ba29bf 100644 --- a/src/Autofac/Builder/RegistrationData.cs +++ b/src/Autofac/Builder/RegistrationData.cs @@ -17,7 +17,7 @@ public class RegistrationData private bool _defaultServiceOverridden; private Service _defaultService; - private readonly ICollection<Service> _services = new HashSet<Service>(); + private readonly HashSet<Service> _services = []; private IComponentLifetime _lifetime = CurrentScopeLifetime.Instance; @@ -43,12 +43,15 @@ public IEnumerable<Service> Services { get { - if (_defaultServiceOverridden) + if (!_defaultServiceOverridden && !_services.Contains(_defaultService)) { - return _services; + yield return _defaultService; } - return _services.DefaultIfEmpty(_defaultService); + foreach (var service in _services) + { + yield return service; + } } } @@ -65,11 +68,15 @@ public void AddServices(IEnumerable<Service> services) throw new ArgumentNullException(nameof(services)); } - _defaultServiceOverridden = true; // important even when services is empty + var empty = true; foreach (var service in services) { + empty = false; AddService(service); } + + // `As([])` clears the default service. + _defaultServiceOverridden = _defaultServiceOverridden || empty; } /// <summary> @@ -83,7 +90,9 @@ public void AddService(Service service) throw new ArgumentNullException(nameof(service)); } - _defaultServiceOverridden = true; + // `AutoActivateService` is internal plumbing; `AutoActivate()` isn't expected to modify user-visible + // services. + _defaultServiceOverridden = _defaultServiceOverridden || service is not AutoActivateService; _services.Add(service); } diff --git a/src/Autofac/RegistrationExtensions.cs b/src/Autofac/RegistrationExtensions.cs index fb0c40b30..55b7e579f 100644 --- a/src/Autofac/RegistrationExtensions.cs +++ b/src/Autofac/RegistrationExtensions.cs @@ -69,6 +69,11 @@ public static IRegistrationBuilder<T, SimpleActivatorData, SingleRegistrationSty rb.SingleInstance(); + // https://github.com/autofac/Autofac/issues/1102 + // Single instance registrations with any custom activation phases (i.e. activation handlers) need to be auto-activated, + // so that other behavior (such as OnRelease) that expects 'normal' object lifetime behavior works as expected. + rb.RegistrationData.AddService(new AutoActivateService()); + rb.RegistrationData.DeferredCallback = builder.RegisterCallback(cr => { if (rb.RegistrationData.Lifetime is not RootScopeLifetime || @@ -79,21 +84,6 @@ public static IRegistrationBuilder<T, SimpleActivatorData, SingleRegistrationSty activator.DisposeInstance = rb.RegistrationData.Ownership == InstanceOwnership.OwnedByLifetimeScope; - // https://github.com/autofac/Autofac/issues/1102 - // Single instance registrations with any custom activation phases (i.e. activation handlers) need to be auto-activated, - // so that other behavior (such as OnRelease) that expects 'normal' object lifetime behavior works as expected. - if (rb.ResolvePipeline.Middleware.Any(s => s.Phase == PipelinePhase.Activation)) - { - var autoStartService = rb.RegistrationData.Services.First(); - - var activationRegistration = new RegistrationBuilder<T, SimpleActivatorData, SingleRegistrationStyle>( - new AutoActivateService(), - new SimpleActivatorData(new DelegateActivator(typeof(T), (c, p) => c.ResolveService(autoStartService))), - new SingleRegistrationStyle()); - - RegistrationBuilder.RegisterSingleComponent(cr, activationRegistration); - } - RegistrationBuilder.RegisterSingleComponent(cr, rb); });
diff --git a/test/Autofac.Specification.Test/Features/StartableTests.cs b/test/Autofac.Specification.Test/Features/StartableTests.cs index ed3b1ee71..e993e9785 100644 --- a/test/Autofac.Specification.Test/Features/StartableTests.cs +++ b/test/Autofac.Specification.Test/Features/StartableTests.cs @@ -168,6 +168,26 @@ public void Startable_WhenTheContainerIsBuilt_StartableComponentsThatDependOnAut Assert.Equal(expectedStartCount, StartableDependency.Count); } + [Fact] + public void AutoActivate_DoesNotHideDefaultSelfService() + { + var builder = new ContainerBuilder(); + builder.RegisterType<MyComponent2>().AutoActivate(); + using var container = builder.Build(); + Assert.True(container.IsRegistered<MyComponent2>()); + } + + [Fact] + public void AutoActivate_RegisterInstanceActivationWorksWhenDefaultServiceOverloaded() + { + var instanceCount = 0; + var builder = new ContainerBuilder(); + builder.RegisterInstance(new MyComponent2()).As<object>().OnActivated(_ => instanceCount++); + builder.RegisterType<object>(); + builder.Build(); + Assert.Equal(1, instanceCount); + } + private class ComponentTakesStartableDependency : IStartable { public ComponentTakesStartableDependency(StartableTakesDependency dependency, bool expectStarted)
`AutoActivate()` hides a registration's default "self" service ## Describe the Bug A registration like `builder.Register<A>()` defaults to exposing the typed service `A` on the component. Adding `AutoActivate()` to the registration hides this default. Since the name `AutoActivate()` doesn't suggest that it has anything to do with exposed services, this seems like a bug or rough edge in the API. ## Steps to Reproduce ```c# public class StartableTests { [Fact] public void AutoActivate_DoesNotHideDefaultSelfService() { var builder = new ContainerBuilder(); builder.RegisterType<MyComponent2>().AutoActivate(); using var container = builder.Build(); Assert.True(container.IsRegistered<MyComponent2>()); } ``` The test can be made to succeed by adding `AsSelf()` to the registration. ## Expected Behavior `AutoActivate()` would not alter the services exposed by the component in a user-visible manner. ## Dependency Versions `develop` branch. ## Additional Info Happy to try to fix this and send a PR, just opening this first to gauge whether it's a known issue or by design. Not in any way blocked on this :-) `AutoActivate()` hides a registration's default "self" service ## Describe the Bug A registration like `builder.Register<A>()` defaults to exposing the typed service `A` on the component. Adding `AutoActivate()` to the registration hides this default. Since the name `AutoActivate()` doesn't suggest that it has anything to do with exposed services, this seems like a bug or rough edge in the API. ## Steps to Reproduce ```c# public class StartableTests { [Fact] public void AutoActivate_DoesNotHideDefaultSelfService() { var builder = new ContainerBuilder(); builder.RegisterType<MyComponent2>().AutoActivate(); using var container = builder.Build(); Assert.True(container.IsRegistered<MyComponent2>()); } ``` The test can be made to succeed by adding `AsSelf()` to the registration. ## Expected Behavior `AutoActivate()` would not alter the services exposed by the component in a user-visible manner. ## Dependency Versions `develop` branch. ## Additional Info Happy to try to fix this and send a PR, just opening this first to gauge whether it's a known issue or by design. Not in any way blocked on this :-)
I don't think it's by design, I'm guessing we just don't have a test for the issue mentioned. It'd be awesome to get a PR for it if you're able. Thanks! I don't think it's by design, I'm guessing we just don't have a test for the issue mentioned. It'd be awesome to get a PR for it if you're able. Thanks!
2025-03-28T01:10:10Z
0.1
['Autofac.Specification.Test.Features.StartableTests.AutoActivate_DoesNotHideDefaultSelfService', 'Autofac.Specification.Test.Features.StartableTests.AutoActivate_RegisterInstanceActivationWorksWhenDefaultServiceOverloaded']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17657
f4633e210c23ff7fbaec3cf402d03deac5315a68
diff --git a/src/Avalonia.Base/Matrix.cs b/src/Avalonia.Base/Matrix.cs index a72710ffd4a..5f5aab4f47f 100644 --- a/src/Avalonia.Base/Matrix.cs +++ b/src/Avalonia.Base/Matrix.cs @@ -214,6 +214,21 @@ public static Matrix CreateRotation(double radians) return new Matrix(cos, sin, -sin, cos, 0, 0); } + /// <summary> + /// Creates a rotation matrix using the given rotation in radians around center point. + /// </summary> + /// <param name="radians">The amount of rotation, in radians. </param> + /// <param name="center">The location of center point. </param> + /// <returns></returns> + public static Matrix CreateRotation(double radians, Point center) + { + var cos = Math.Cos(radians); + var sin = Math.Sin(radians); + var x = center.X; + var y = center.Y; + return new Matrix(cos, sin, -sin, cos, x * (1.0 - cos) + y * sin, y * (1.0 - cos) - x * sin); + } + /// <summary> /// Creates a skew matrix from the given axis skew angles in radians. /// </summary>
diff --git a/tests/Avalonia.Base.UnitTests/MatrixTests.cs b/tests/Avalonia.Base.UnitTests/MatrixTests.cs index d111c142581..9fccdf25fce 100644 --- a/tests/Avalonia.Base.UnitTests/MatrixTests.cs +++ b/tests/Avalonia.Base.UnitTests/MatrixTests.cs @@ -61,6 +61,20 @@ public void Transform_Point_Should_Return_Correct_Value_For_Rotated_Matrix() AssertCoordinatesEqualWithReducedPrecision(expected, actual); } + + [Fact] + public void Transform_Point_Should_Return_Correct_Value_For_Rotate_Matrix_With_Center_Point() + { + var expected = Vector2.Transform( + new Vector2(0, 10), + Matrix3x2.CreateRotation((float)Matrix.ToRadians(30), new Vector2(3, 5))); + + var matrix = Matrix.CreateRotation(Matrix.ToRadians(30), new Point(3, 5)); + var point = new Point(0, 10); + var actual = matrix.Transform(point); + + AssertCoordinatesEqualWithReducedPrecision(expected, actual); + } [Fact] public void Transform_Point_Should_Return_Correct_Value_For_Scaled_Matrix()
Add Matrix.Rotate(angle, x, y) overload ### Is your feature request related to a problem? Please describe. This is not a standard css transformation, but a frequently used in svg. ### Describe the solution you'd like as described. ### Describe alternatives you've considered _No response_ ### Additional context _No response_
null
2024-12-01T07:07:57Z
0.1
['Avalonia.Visuals.UnitTests.MatrixTests.Transform_Point_Should_Return_Correct_Value_For_Rotate_Matrix_With_Center_Point']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17638
1583de3e33459f174b09307baffbaba4f6987116
diff --git a/src/Avalonia.Controls/SelectableTextBlock.cs b/src/Avalonia.Controls/SelectableTextBlock.cs index 8f1248027c5..b0fd78b321e 100644 --- a/src/Avalonia.Controls/SelectableTextBlock.cs +++ b/src/Avalonia.Controls/SelectableTextBlock.cs @@ -224,12 +224,14 @@ protected override TextLayout CreateTextLayout(string? text) textSource = new FormattedTextSource(text ?? "", defaultProperties, textStyleOverrides); } + var maxSize = GetMaxSizeFromConstraint(); + return new TextLayout( textSource, paragraphProperties, TextTrimming, - _constraint.Width, - _constraint.Height, + maxSize.Width, + maxSize.Height, MaxLines); } diff --git a/src/Avalonia.Controls/TextBlock.cs b/src/Avalonia.Controls/TextBlock.cs index 0afafe44b87..f6a0cdbdfdf 100644 --- a/src/Avalonia.Controls/TextBlock.cs +++ b/src/Avalonia.Controls/TextBlock.cs @@ -162,7 +162,7 @@ public class TextBlock : Control, IInlineHost nameof(Inlines), t => t.Inlines, (t, v) => t.Inlines = v); private TextLayout? _textLayout; - protected Size _constraint = Size.Infinity; + protected Size _constraint = new(double.NaN, double.NaN); protected IReadOnlyList<TextRun>? _textRuns; private InlineCollection? _inlines; @@ -366,6 +366,13 @@ public InlineCollection? Inlines internal bool HasComplexContent => Inlines != null && Inlines.Count > 0; + private protected Size GetMaxSizeFromConstraint() + { + var maxWidth = double.IsNaN(_constraint.Width) ? 0.0 : _constraint.Width; + var maxHeight = double.IsNaN(_constraint.Height) ? 0.0 : _constraint.Height; + return new Size(maxWidth, maxHeight); + } + /// <summary> /// The BaselineOffset property provides an adjustment to baseline offset /// </summary> @@ -670,12 +677,14 @@ protected virtual TextLayout CreateTextLayout(string? text) textSource = new SimpleTextSource(text ?? "", defaultProperties); } + var maxSize = GetMaxSizeFromConstraint(); + return new TextLayout( textSource, paragraphProperties, TextTrimming, - _constraint.Width, - _constraint.Height, + maxSize.Width, + maxSize.Height, MaxLines); }
diff --git a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs index 3d7c6e6c1bd..4a7281fae3a 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBlockTests.cs @@ -1,3 +1,4 @@ +using System; using Avalonia.Controls.Documents; using Avalonia.Controls.Templates; using Avalonia.Data; @@ -33,7 +34,9 @@ public void Calling_Measure_Should_Update_TextLayout() { var textBlock = new TestTextBlock { Text = "Hello World" }; - Assert.Equal(Size.Infinity, textBlock.Constraint); + var constraint = textBlock.Constraint; + Assert.True(double.IsNaN(constraint.Width)); + Assert.True(double.IsNaN(constraint.Height)); textBlock.Measure(new Size(100, 100)); @@ -413,6 +416,24 @@ public void TextBlock_TextLines_Should_Be_Empty() } } + [Fact] + public void TextBlock_With_Infinite_Size_Should_Be_Remeasured_After_TextLayout_Created() + { + using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface); + + var target = new TextBlock { Text = "" }; + var layout = target.TextLayout; + + Assert.Equal(0.0, layout.MaxWidth); + Assert.Equal(0.0, layout.MaxHeight); + + target.Text = "foo"; + target.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + + Assert.True(target.DesiredSize.Width > 0); + Assert.True(target.DesiredSize.Height > 0); + } + private class TestTextBlock : TextBlock { public Size Constraint => _constraint;
Changing TextBlock.Text placed inside an infinite-sized invisible container doesn't re-measure the TextBlock ### Describe the bug Inside a container which is infinite on both sides and invisible, changing the `Text` of a `TextBlock`, then making the container visible, doesn't re-measure the TextBlock: the text is effectively still invisible. ### To Reproduce ```xaml <StackPanel> <Button Content="Change Text" Click="Button_OnClick" /> <Grid Name="Grid" RowDefinitions="Auto" ColumnDefinitions="Auto" IsVisible="False"> <TextBlock Name="TextBlock" /> </Grid> </StackPanel> ``` ```csharp private void Button_OnClick(object sender, RoutedEventArgs e) { TextBlock.Text = "Foo"; Grid.IsVisible = true; } ``` Click on the button. ### Expected behavior The text should be visible after clicking the button. ### Avalonia version 11.2.1, 11.2.2 ### OS _No response_ ### Additional context Introduced by #17271 The initial `_constraint` is `Infinite`, which matches the infinite container. If the `TextLayout` gets created for any reason, it won't be properly invalidated.
null
2024-11-28T15:44:21Z
0.1
[]
['Avalonia.Controls.UnitTests.TextBlockTests.TextBlock_TextLines_Should_Be_Empty', 'Avalonia.Controls.UnitTests.TextBlockTests.Calling_Measure_Should_Update_TextLayout', 'Avalonia.Controls.UnitTests.TextBlockTests.DefaultBindingMode_Should_Be_OneWay', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_InlinesCollection_Should_Invalidate_Measure', 'Avalonia.Controls.UnitTests.TextBlockTests.Setting_TextDecorations_Should_Update_Inlines', 'Avalonia.Controls.UnitTests.TextBlockTests.Embedded_Control_Should_Keep_Focus', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Properties_Should_Invalidate_Measure', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Should_Reset_Inlines_Parent', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Should_Reset_InlineUIContainer_VisualParent_On_Measure', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Should_Reset_VisualChildren', 'Avalonia.Controls.UnitTests.TextBlockTests.Calling_Arrange_With_Different_Size_Should_Update_Constraint_And_TextLayout', 'Avalonia.Controls.UnitTests.TextBlockTests.Can_Call_Measure_Without_InvalidateTextLayout', 'Avalonia.Controls.UnitTests.TextBlockTests.Calling_Measure_With_Infinite_Space_Should_Set_DesiredSize', 'Avalonia.Controls.UnitTests.TextBlockTests.Setting_Text_Should_Reset_Inlines', 'Avalonia.Controls.UnitTests.TextBlockTests.InlineUIContainer_Child_Schould_Be_Arranged', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Should_Attach_Embedded_Controls_To_Parents', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_InlineHost_Should_Propagate_To_Nested_Inlines', 'Avalonia.Controls.UnitTests.TextBlockTests.Default_Text_Value_Should_Be_Null', 'Avalonia.Controls.UnitTests.TextBlockTests.Changing_Inlines_Should_Invalidate_Measure']
AvaloniaUI/Avalonia
avaloniaui__avalonia-17465
b35fd5a890f3b1f94bec19f6f9557a255805cc67
diff --git a/src/Avalonia.Controls/CalendarDatePicker/CalendarDatePicker.cs b/src/Avalonia.Controls/CalendarDatePicker/CalendarDatePicker.cs index ec54533f4e1..eaf632039b8 100644 --- a/src/Avalonia.Controls/CalendarDatePicker/CalendarDatePicker.cs +++ b/src/Avalonia.Controls/CalendarDatePicker/CalendarDatePicker.cs @@ -730,7 +730,9 @@ private void OpenDropDown() // the TextParseError event try { - newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetCurrentDateFormat()); + newSelectedDate = SelectedDateFormat == CalendarDatePickerFormat.Custom && !string.IsNullOrEmpty(CustomDateFormatString) ? + DateTime.ParseExact(text, CustomDateFormatString, DateTimeHelper.GetCurrentDateFormat()) : + DateTime.Parse(text, DateTimeHelper.GetCurrentDateFormat()); if (Calendar.IsValidDateSelection(this._calendar!, newSelectedDate)) { @@ -899,6 +901,11 @@ private void SetWaterMarkText() switch (SelectedDateFormat) { + case CalendarDatePickerFormat.Custom: + { + watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, CustomDateFormatString); + break; + } case CalendarDatePickerFormat.Long: { watermarkText = string.Format(CultureInfo.CurrentCulture, watermarkFormat, dtfi.LongDatePattern.ToString()); @@ -911,6 +918,7 @@ private void SetWaterMarkText() break; } } + _textBox.Watermark = watermarkText; } else
diff --git a/tests/Avalonia.Controls.UnitTests/CalendarDatePickerTests.cs b/tests/Avalonia.Controls.UnitTests/CalendarDatePickerTests.cs index c3acf31caa7..013369f102a 100644 --- a/tests/Avalonia.Controls.UnitTests/CalendarDatePickerTests.cs +++ b/tests/Avalonia.Controls.UnitTests/CalendarDatePickerTests.cs @@ -1,17 +1,13 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; +using System; using System.Linq; using Avalonia.Controls.Primitives; -using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; -using Avalonia.Data; -using Avalonia.Markup.Data; +using Avalonia.Input; using Avalonia.Platform; using Avalonia.UnitTests; using Moq; using Xunit; +using System.Globalization; namespace Avalonia.Controls.UnitTests { @@ -73,6 +69,34 @@ public void Adding_Blackout_Dates_Containing_Selected_Date_Should_Throw() } } + [Fact] + public void Setting_Date_Manually_With_CustomDateFormatString_Should_Be_Accepted() + { + CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US"); + using (UnitTestApplication.Start(Services)) + { + CalendarDatePicker datePicker = CreateControl(); + datePicker.SelectedDateFormat = CalendarDatePickerFormat.Custom; + datePicker.CustomDateFormatString = "dd.MM.yyyy"; + + var tb = GetTextBox(datePicker); + + tb.Clear(); + RaiseTextEvent(tb, "17.10.2024"); + RaiseKeyEvent(tb, Key.Enter, KeyModifiers.None); + + Assert.Equal("17.10.2024", datePicker.Text); + Assert.True(CompareDates(datePicker.SelectedDate.Value, new DateTime(2024, 10, 17))); + + tb.Clear(); + RaiseTextEvent(tb, "12.10.2024"); + RaiseKeyEvent(tb, Key.Enter, KeyModifiers.None); + + Assert.Equal("12.10.2024", datePicker.Text); + Assert.True(CompareDates(datePicker.SelectedDate.Value, new DateTime(2024, 10, 12))); + } + } + private static TestServices Services => TestServices.MockThreadingInterface.With( standardCursorFactory: Mock.Of<ICursorFactory>()); @@ -127,5 +151,32 @@ private static IControlTemplate CreateTemplate() }); } + + private TextBox GetTextBox(CalendarDatePicker control) + { + return control.GetTemplateChildren() + .OfType<TextBox>() + .First(); + } + + private static void RaiseKeyEvent(TextBox textBox, Key key, KeyModifiers inputModifiers) + { + textBox.RaiseEvent(new KeyEventArgs + { + RoutedEvent = InputElement.KeyDownEvent, + KeyModifiers = inputModifiers, + Key = key + }); + } + + private static void RaiseTextEvent(TextBox textBox, string text) + { + textBox.RaiseEvent(new TextInputEventArgs + { + RoutedEvent = InputElement.TextInputEvent, + Text = text + }); + } + } }
CustomDateFormatString is not used for text input in CalendarDatePicker ### Describe the bug The CalendarDatePicker with a CustomDateFormatString seems to display the date correctly but ignores the custom date format when the date is entered by keyboard. ### To Reproduce 1. Create a CalendarDatePicker with CustomDateFormatString set to "dd.MM.yyyy" `<CalendarDatePicker SelectedDateFormat="Custom" CustomDateFormatString="dd.MM.yyyy" SelectedDate="{Binding Datum}">` 2. Type in the date "17.10.2024" and press enter => not accepted, the date changes to previous value 3. Type in the date "12.10.2024" and press enter => the date changes to 10.12.2024 ### Expected behavior Type in the date "17.10.2024" and press enter => "17.10.2024" ramains in the textbox Type in the date "12.10.2024" and press enter => "12.10.2024" ramains in the textbox ### Avalonia version 11.1.0 ### OS _No response_ ### Additional context I'm new to avalonia, but looking at the code the problem seems to be in CalendarDatePicker.cs `ParseText(string text) ` in Line 733: ` newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetCurrentDateFormat());` Shouldn't CustomDateFormatString be used here when SelectedDateFormat is set to Custom?
@JokaDev without looking too deep into, I think you may be right. Maybe you can file a PR to fix it? Adding some tests if possible would be great.
2024-11-10T13:23:01Z
0.1
['Avalonia.Controls.UnitTests.CalendarDatePickerTests.Setting_Date_Manually_With_CustomDateFormatString_Should_Be_Accepted']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17462
b46126714b72635b6fb699e679a8f103d5449105
diff --git a/src/Avalonia.Controls/AutoCompleteBox/AutoCompleteBox.cs b/src/Avalonia.Controls/AutoCompleteBox/AutoCompleteBox.cs index 95ea8f9ece2..b142ce5eb2d 100644 --- a/src/Avalonia.Controls/AutoCompleteBox/AutoCompleteBox.cs +++ b/src/Avalonia.Controls/AutoCompleteBox/AutoCompleteBox.cs @@ -812,7 +812,11 @@ private void FocusChanged(bool hasFocus) } _userCalledPopulate = false; - ClearTextBoxSelection(); + + if (ContextMenu is not { IsOpen: true }) + { + ClearTextBoxSelection(); + } } _isFocused = hasFocus;
diff --git a/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs b/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs index 5cc3901cd74..67f55055ec8 100644 --- a/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/AutoCompleteBoxTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls.Primitives; @@ -9,7 +9,10 @@ using Xunit; using System.Collections.ObjectModel; using System.Reactive.Subjects; +using Avalonia.Headless; using Avalonia.Input; +using Avalonia.Platform; +using Moq; namespace Avalonia.Controls.UnitTests { @@ -520,6 +523,42 @@ public void Attempting_To_Open_Without_Items_Does_Not_Prevent_Future_Opening_Wit }); } + [Fact] + public void Opening_Context_Menu_Does_not_Lose_Selection() + { + using (UnitTestApplication.Start(FocusServices)) + { + var target1 = CreateControl(); + target1.ContextMenu = new TestContextMenu(); + var textBox1 = GetTextBox(target1); + textBox1.Text = "1234"; + + var target2 = CreateControl(); + var textBox2 = GetTextBox(target2); + textBox2.Text = "5678"; + + var sp = new StackPanel(); + sp.Children.Add(target1); + sp.Children.Add(target2); + + target1.ApplyTemplate(); + target2.ApplyTemplate(); + + var root = new TestRoot() { Child = sp }; + + textBox1.SelectionStart = 0; + textBox1.SelectionEnd = 3; + + target1.Focus(); + Assert.False(target2.IsFocused); + Assert.True(target1.IsFocused); + + target2.Focus(); + + Assert.Equal("123", textBox1.SelectedText); + } + } + /// <summary> /// Retrieves a defined predicate filter through a new AutoCompleteBox /// control instance. @@ -1198,5 +1237,22 @@ private IControlTemplate CreateTemplate() return panel; }); } + + private static TestServices FocusServices => TestServices.MockThreadingInterface.With( + focusManager: new FocusManager(), + keyboardDevice: () => new KeyboardDevice(), + keyboardNavigation: () => new KeyboardNavigationHandler(), + inputManager: new InputManager(), + standardCursorFactory: Mock.Of<ICursorFactory>(), + textShaperImpl: new HeadlessTextShaperStub(), + fontManagerImpl: new HeadlessFontManagerStub()); + + private class TestContextMenu : ContextMenu + { + public TestContextMenu() + { + IsOpen = true; + } + } } }
AutoCompleteBox loses selection when context menu opened ### Describe the bug Selection of text get lost when context menu opened. Moreover, small part of selection (not empty) is expanded to full selection at first time and lost too. ### To Reproduce 1. Write text in AutoCompleteBox 2. Select part of text (or not) 3. Right click on selection 4. Move pointer over context menu items 5. Cut, Copy items after 4. will be disabled with selection empty Example styles: ```xml <Styles.Resources> ... <MenuFlyout x:Key="testTextBoxContextFlyout" Placement="Bottom"> <MenuItem Header="Cut" Command="{Binding $parent[TextBox].Cut}" IsEnabled="{Binding $parent[TextBox].CanCut}" InputGesture="{x:Static TextBox.CutGesture}"/> <MenuItem Header="Copy" Command="{Binding $parent[TextBox].Copy}" IsEnabled="{Binding $parent[TextBox].CanCopy}" InputGesture="{x:Static TextBox.CopyGesture}"/> <MenuItem Header="Paste" Command="{Binding $parent[TextBox].Paste}" IsEnabled="{Binding $parent[TextBox].CanPaste}" InputGesture="{x:Static TextBox.PasteGesture}"/> </MenuFlyout> ... </Styles.Resources> <Style Selector="TextBox"> <Setter Property="ContextFlyout" Value="{StaticResource testTextBoxContextFlyout}"/> </Style> ``` ### Expected behavior Not lose selection. Not expand not empty selection. ### Avalonia version 11.2.0 ### OS Windows, macOS, Linux ### Additional context The same problem with TextBox was solved: https://github.com/AvaloniaUI/Avalonia/pull/4498
@isergvb if you want to apply a similar fix to that control, a PR is welcome.
2024-11-09T21:50:54Z
0.1
['Avalonia.Controls.UnitTests.AutoCompleteBoxTests.Opening_Context_Menu_Does_not_Lose_Selection']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17178
9d54429c304018540d72eb0a508f79c8088d4182
diff --git a/src/Avalonia.Controls/SplitView/SplitView.cs b/src/Avalonia.Controls/SplitView/SplitView.cs index fed0367d122..fd6fd98de69 100644 --- a/src/Avalonia.Controls/SplitView/SplitView.cs +++ b/src/Avalonia.Controls/SplitView/SplitView.cs @@ -297,6 +297,7 @@ protected override void OnApplyTemplate(TemplateAppliedEventArgs e) _pane = e.NameScope.Find<Panel>("PART_PaneRoot"); UpdateVisualStateForDisplayMode(DisplayMode); + UpdatePaneStatePseudoClass(IsPaneOpen); } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) @@ -331,19 +332,13 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang else if (change.Property == IsPaneOpenProperty) { bool isPaneOpen = change.GetNewValue<bool>(); - + UpdatePaneStatePseudoClass(isPaneOpen); if (isPaneOpen) { - PseudoClasses.Add(pcOpen); - PseudoClasses.Remove(pcClosed); - OnPaneOpened(new RoutedEventArgs(PaneOpenedEvent, this)); } else { - PseudoClasses.Add(pcClosed); - PseudoClasses.Remove(pcOpen); - OnPaneClosed(new RoutedEventArgs(PaneClosedEvent, this)); } } @@ -579,6 +574,20 @@ private void TopLevelBackRequested(object? sender, RoutedEventArgs e) e.Handled = true; } + private void UpdatePaneStatePseudoClass(bool isPaneOpen) + { + if (isPaneOpen) + { + PseudoClasses.Add(pcOpen); + PseudoClasses.Remove(pcClosed); + } + else + { + PseudoClasses.Add(pcClosed); + PseudoClasses.Remove(pcOpen); + } + } + /// <summary> /// Coerces/validates the <see cref="IsPaneOpen"/> property value. /// </summary>
diff --git a/tests/Avalonia.Controls.UnitTests/SplitViewTests.cs b/tests/Avalonia.Controls.UnitTests/SplitViewTests.cs index 9b43c469ba2..47383fa9ad9 100644 --- a/tests/Avalonia.Controls.UnitTests/SplitViewTests.cs +++ b/tests/Avalonia.Controls.UnitTests/SplitViewTests.cs @@ -1,5 +1,7 @@ -using Avalonia.Input; +using Avalonia.Animation; +using Avalonia.Input; using Avalonia.UnitTests; +using Moq; using Xunit; namespace Avalonia.Controls.UnitTests @@ -65,7 +67,8 @@ public void SplitView_Cancel_Close_Should_Prevent_Pane_From_Closing() [Fact] public void SplitView_TemplateSettings_Are_Correct_For_Display_Modes() { - using var app = UnitTestApplication.Start(TestServices.StyledWindow); + using var app = UnitTestApplication.Start(TestServices.StyledWindow + .With(globalClock: new MockGlobalClock())); var wnd = new Window { Width = 1280, @@ -280,5 +283,25 @@ public void Top_Level_Back_Requested_Closes_Light_Dismissable_Pane() Assert.True(splitView.IsPaneOpen); } + + [Fact] + public void With_Default_IsPaneOpen_Value_Should_Have_Closed_Pseudo_Class_Set() + { + // Testing this control Pseudo Classes requires placing the SplitView on a window + // prior to asserting them, because some of the pseudo classes are set either when + // the template is applied or the control is attached to the visual tree + using var app = UnitTestApplication.Start(TestServices.StyledWindow + .With(globalClock: new MockGlobalClock())); + var wnd = new Window + { + Width = 1280, + Height = 720 + }; + var splitView = new SplitView(); + wnd.Content = splitView; + wnd.Show(); + + Assert.Contains(splitView.Classes, ":closed".Equals); + } } }
SplitView ":open"/":closed" pseudoclasses aren't set on control initialization ### Describe the bug SplitView control after it initialized does not have `:open` or `:closed` pseudoclass set. Regardless of the value in the `IsPaneOpen` property. ### To Reproduce Create Window with a SplitView control, set IsPaneOpen to any value (e.g, by binding to ViewModel) Run the application in Debug, open Debug tools In Logical Tree, find SplitView. The SplitView doesn't have `:open` / `:closed` pseudoclass set regardless of the value in the `IsPaneOpen` property. ![image](https://github.com/user-attachments/assets/1a26583e-303c-428b-8bca-3e2ab323dfaa) Pseudoclass is set only after first change of `IsPaneOpen` property ### Expected behavior SplitView control after initialization should have `:open` / `:closed` pseudoclass set depending of the value in the `IsPaneOpen` property ### Avalonia version 11.1.0 ### OS Windows ### Additional context After looking into `SplitView.cs` source code, the problem appears to be that the logic for changing pseudoclass based on `IsPaneOpen` value is present only in `OnPropertyChanged` method. Adding same logic to constructor should fix the issue SplitView ":open"/":closed" pseudoclasses aren't set on control initialization ### Describe the bug SplitView control after it initialized does not have `:open` or `:closed` pseudoclass set. Regardless of the value in the `IsPaneOpen` property. ### To Reproduce Create Window with a SplitView control, set IsPaneOpen to any value (e.g, by binding to ViewModel) Run the application in Debug, open Debug tools In Logical Tree, find SplitView. The SplitView doesn't have `:open` / `:closed` pseudoclass set regardless of the value in the `IsPaneOpen` property. ![image](https://github.com/user-attachments/assets/1a26583e-303c-428b-8bca-3e2ab323dfaa) Pseudoclass is set only after first change of `IsPaneOpen` property ### Expected behavior SplitView control after initialization should have `:open` / `:closed` pseudoclass set depending of the value in the `IsPaneOpen` property ### Avalonia version 11.1.0 ### OS Windows ### Additional context After looking into `SplitView.cs` source code, the problem appears to be that the logic for changing pseudoclass based on `IsPaneOpen` value is present only in `OnPropertyChanged` method. Adding same logic to constructor should fix the issue
@OccVeneficus if you have an idea how to solve it, a PR is welcome. @OccVeneficus if you have an idea how to solve it, a PR is welcome.
2024-10-01T19:21:33Z
0.1
['Avalonia.Controls.UnitTests.SplitViewTests.With_Default_IsPaneOpen_Value_Should_Have_Closed_Pseudo_Class_Set']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17171
b272283e5057d65617246b9ebf64c4e0e281d88b
diff --git a/src/Avalonia.Base/Collections/AvaloniaDictionaryExtensions.cs b/src/Avalonia.Base/Collections/AvaloniaDictionaryExtensions.cs index 8c731c188f4..dfd62259e43 100644 --- a/src/Avalonia.Base/Collections/AvaloniaDictionaryExtensions.cs +++ b/src/Avalonia.Base/Collections/AvaloniaDictionaryExtensions.cs @@ -70,11 +70,6 @@ void Remove(IEnumerable items) case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: Remove(e.OldItems!); - int newIndex = e.NewStartingIndex; - if(newIndex > e.OldStartingIndex) - { - newIndex -= e.OldItems!.Count; - } Add(e.NewItems!); break; diff --git a/src/Avalonia.Base/Collections/AvaloniaList.cs b/src/Avalonia.Base/Collections/AvaloniaList.cs index 84a77810da1..324e33e5aff 100644 --- a/src/Avalonia.Base/Collections/AvaloniaList.cs +++ b/src/Avalonia.Base/Collections/AvaloniaList.cs @@ -466,7 +466,7 @@ public void MoveRange(int oldIndex, int count, int newIndex) if (newIndex > oldIndex) { - modifiedNewIndex -= count; + modifiedNewIndex -= count - 1; } _inner.InsertRange(modifiedNewIndex, items); diff --git a/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs b/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs index 2178577eb71..244788c63e9 100644 --- a/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs +++ b/src/Avalonia.Base/Collections/AvaloniaListExtensions.cs @@ -99,15 +99,30 @@ void Remove(int index, IList items) break; case NotifyCollectionChangedAction.Move: - case NotifyCollectionChangedAction.Replace: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + Remove(e.OldStartingIndex, e.OldItems!); - int newIndex = e.NewStartingIndex; + var newIndex = e.NewStartingIndex; + if(newIndex > e.OldStartingIndex) { - newIndex -= e.OldItems!.Count; + newIndex -= e.OldItems!.Count - 1; } + Add(newIndex, e.NewItems!); break; + case NotifyCollectionChangedAction.Replace: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + + Remove(e.OldStartingIndex, e.OldItems!); + Add(e.NewStartingIndex, e.NewItems!); + break; case NotifyCollectionChangedAction.Remove: Remove(e.OldStartingIndex, e.OldItems!); diff --git a/src/Avalonia.Controls/Presenters/PanelContainerGenerator.cs b/src/Avalonia.Controls/Presenters/PanelContainerGenerator.cs index 4027cd252f0..b0e2af2f3ad 100644 --- a/src/Avalonia.Controls/Presenters/PanelContainerGenerator.cs +++ b/src/Avalonia.Controls/Presenters/PanelContainerGenerator.cs @@ -93,10 +93,30 @@ void Remove(int index, int count) Remove(e.OldStartingIndex, e.OldItems!.Count); break; case NotifyCollectionChangedAction.Replace: - case NotifyCollectionChangedAction.Move: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + Remove(e.OldStartingIndex, e.OldItems!.Count); Add(e.NewStartingIndex, e.NewItems!); break; + case NotifyCollectionChangedAction.Move: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + + Remove(e.OldStartingIndex, e.OldItems!.Count); + var insertIndex = e.NewStartingIndex; + + if (e.NewStartingIndex > e.OldStartingIndex) + { + insertIndex -= e.OldItems.Count - 1; + } + + Add(insertIndex, e.NewItems!); + break; case NotifyCollectionChangedAction.Reset: ClearItemsControlLogicalChildren(); children.Clear(); diff --git a/src/Avalonia.Controls/Selection/SelectionNodeBase.cs b/src/Avalonia.Controls/Selection/SelectionNodeBase.cs index caeff61f074..c50f77830f1 100644 --- a/src/Avalonia.Controls/Selection/SelectionNodeBase.cs +++ b/src/Avalonia.Controls/Selection/SelectionNodeBase.cs @@ -139,13 +139,38 @@ protected virtual void OnSourceCollectionChanged(NotifyCollectionChangedEventArg break; } case NotifyCollectionChangedAction.Replace: - case NotifyCollectionChangedAction.Move: { + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + var removeChange = OnItemsRemoved(e.OldStartingIndex, e.OldItems!); var addChange = OnItemsAdded(e.NewStartingIndex, e.NewItems!); shiftIndex = removeChange.ShiftIndex; shiftDelta = removeChange.ShiftDelta + addChange.ShiftDelta; removed = removeChange.RemovedItems; + break; + } + case NotifyCollectionChangedAction.Move: + { + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + + var removeChange = OnItemsRemoved(e.OldStartingIndex, e.OldItems!); + var insertIndex = e.NewStartingIndex; + + if (e.NewStartingIndex > e.OldStartingIndex) + { + insertIndex -= e.OldItems!.Count - 1; + } + + var addChange = OnItemsAdded(insertIndex, e.NewItems!); + shiftIndex = removeChange.ShiftIndex; + shiftDelta = removeChange.ShiftDelta + addChange.ShiftDelta; + removed = removeChange.RemovedItems; } break; case NotifyCollectionChangedAction.Reset: diff --git a/src/Avalonia.Controls/VirtualizingCarouselPanel.cs b/src/Avalonia.Controls/VirtualizingCarouselPanel.cs index d10ae124c12..8b67f01fb15 100644 --- a/src/Avalonia.Controls/VirtualizingCarouselPanel.cs +++ b/src/Avalonia.Controls/VirtualizingCarouselPanel.cs @@ -236,10 +236,30 @@ void Remove(int index, int count) Remove(e.OldStartingIndex, e.OldItems!.Count); break; case NotifyCollectionChangedAction.Replace: - case NotifyCollectionChangedAction.Move: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + Remove(e.OldStartingIndex, e.OldItems!.Count); Add(e.NewStartingIndex, e.NewItems!.Count); break; + case NotifyCollectionChangedAction.Move: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + + Remove(e.OldStartingIndex, e.OldItems!.Count); + var insertIndex = e.NewStartingIndex; + + if (e.NewStartingIndex > e.OldStartingIndex) + { + insertIndex -= e.OldItems.Count - 1; + } + + Add(insertIndex, e.NewItems!.Count); + break; case NotifyCollectionChangedAction.Reset: if (_realized is not null) { diff --git a/src/Avalonia.Controls/VirtualizingStackPanel.cs b/src/Avalonia.Controls/VirtualizingStackPanel.cs index 7934e0ccc6b..3e08b59c2e3 100644 --- a/src/Avalonia.Controls/VirtualizingStackPanel.cs +++ b/src/Avalonia.Controls/VirtualizingStackPanel.cs @@ -272,8 +272,20 @@ protected override void OnItemsChanged(IReadOnlyList<object?> items, NotifyColle _realizedElements.ItemsReplaced(e.OldStartingIndex, e.OldItems!.Count, _recycleElementOnItemRemoved); break; case NotifyCollectionChangedAction.Move: + if (e.OldStartingIndex < 0) + { + goto case NotifyCollectionChangedAction.Reset; + } + _realizedElements.ItemsRemoved(e.OldStartingIndex, e.OldItems!.Count, _updateElementIndex, _recycleElementOnItemRemoved); - _realizedElements.ItemsInserted(e.NewStartingIndex, e.NewItems!.Count, _updateElementIndex); + var insertIndex = e.NewStartingIndex; + + if (e.NewStartingIndex > e.OldStartingIndex) + { + insertIndex -= e.OldItems.Count - 1; + } + + _realizedElements.ItemsInserted(insertIndex, e.NewItems!.Count, _updateElementIndex); break; case NotifyCollectionChangedAction.Reset: _realizedElements.ItemsReset(_recycleElementOnItemRemoved);
diff --git a/tests/Avalonia.Base.UnitTests/Collections/AvaloniaListTests.cs b/tests/Avalonia.Base.UnitTests/Collections/AvaloniaListTests.cs index b59f272b0cb..82a9885ddce 100644 --- a/tests/Avalonia.Base.UnitTests/Collections/AvaloniaListTests.cs +++ b/tests/Avalonia.Base.UnitTests/Collections/AvaloniaListTests.cs @@ -52,6 +52,22 @@ public void InsertRange_Past_End_Should_Throw_Exception() Assert.Throws<ArgumentOutOfRangeException>(() => target.InsertRange(1, new List<int>() { 1 })); } + [Fact] + public void Move_Should_Move_One_Item() + { + AvaloniaList<int> target = [1, 2, 3]; + + AssertEvent(target, () => target.Move(0, 1), [ + new NotifyCollectionChangedEventArgs( + NotifyCollectionChangedAction.Move, + new[] { 1 }, + 1, + 0) + ]); + + Assert.Equal(new[] { 2, 1, 3 }, target); + } + [Fact] public void Move_Should_Update_Collection() { @@ -75,9 +91,9 @@ public void MoveRange_Should_Update_Collection() [Fact] public void MoveRange_Can_Move_To_End() { - var target = new AvaloniaList<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + AvaloniaList<int> target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - target.MoveRange(0, 5, 10); + target.MoveRange(0, 5, 9); Assert.Equal(new[] { 6, 7, 8, 9, 10, 1, 2, 3, 4, 5 }, target); } @@ -85,25 +101,35 @@ public void MoveRange_Can_Move_To_End() [Fact] public void MoveRange_Raises_Correct_CollectionChanged_Event() { - var target = new AvaloniaList<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - var raised = false; + AvaloniaList<int> target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - target.CollectionChanged += (s, e) => - { - Assert.Equal(NotifyCollectionChangedAction.Move, e.Action); - Assert.Equal(0, e.OldStartingIndex); - Assert.Equal(10, e.NewStartingIndex); - Assert.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, e.OldItems); - Assert.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, e.NewItems); - raised = true; - }; + AssertEvent(target, () => target.MoveRange(0, 9, 9), [ + new NotifyCollectionChangedEventArgs( + NotifyCollectionChangedAction.Move, + new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, + 9, + 0) + ]); - target.MoveRange(0, 9, 10); - - Assert.True(raised); Assert.Equal(new[] { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, target); } + [Fact] + public void MoveRange_Should_Move_One_Item() + { + AvaloniaList<int> target = [1, 2, 3]; + + AssertEvent(target, () => target.MoveRange(0, 1, 1), [ + new NotifyCollectionChangedEventArgs( + NotifyCollectionChangedAction.Move, + new[] { 1 }, + 1, + 0) + ]); + + Assert.Equal(new[] { 2, 1, 3 }, target); + } + [Fact] public void Adding_Item_Should_Raise_CollectionChanged() { @@ -526,5 +552,48 @@ public void RemoveAll_Should_Handle_Empty_List() Assert.Equal(0, raised); } + + /// <summary> + /// Assert that <see cref="items"/> emits <see cref="expectedEvents"/> when performing <see cref="action"/>. + /// </summary> + /// <param name="items">The event source.</param> + /// <param name="action">The action to perform.</param> + /// <param name="expectedEvents">The expected events.</param> + private static void AssertEvent(INotifyCollectionChanged items, Action action, NotifyCollectionChangedEventArgs[] expectedEvents) + { + var callCount = 0; + items.CollectionChanged += OnCollectionChanged; + + Assert.Multiple(() => + { + try + { + action(); + } + finally + { + items.CollectionChanged -= OnCollectionChanged; + } + + Assert.Equal(expectedEvents.Length, callCount); + }); + + return; + + void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs actualEvent) + { + Assert.Multiple(() => + { + Assert.True(callCount < expectedEvents.Length); + Assert.Equal(expectedEvents[callCount].Action, actualEvent.Action); + Assert.Equal(expectedEvents[callCount].NewItems, actualEvent.NewItems); + Assert.Equal(expectedEvents[callCount].NewStartingIndex, actualEvent.NewStartingIndex); + Assert.Equal(expectedEvents[callCount].OldItems, actualEvent.OldItems); + Assert.Equal(expectedEvents[callCount].OldStartingIndex, actualEvent.OldStartingIndex); + }); + + ++callCount; + } + } } } diff --git a/tests/Avalonia.Controls.UnitTests/Presenters/ItemsPresenterTests.cs b/tests/Avalonia.Controls.UnitTests/Presenters/ItemsPresenterTests.cs index ca98991c4b2..24aff3b5664 100644 --- a/tests/Avalonia.Controls.UnitTests/Presenters/ItemsPresenterTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Presenters/ItemsPresenterTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.UnitTests; @@ -91,6 +92,20 @@ public void Updates_Containers_For_Moved_Items() AssertContainers(panel, items); } + [Fact] + public void Updates_Container_For_Moved_Range_Of_Items() + { + using var app = Start(); + AvaloniaList<string> items = ["foo", "bar", "baz"]; + var (target, _, root) = CreateTarget(items); + var panel = Assert.IsType<StackPanel>(target.Panel); + + items.MoveRange(0, 2, 2); + root.LayoutManager.ExecuteLayoutPass(); + + AssertContainers(panel, items); + } + [Fact] public void Updates_Containers_For_Replaced_Items() { diff --git a/tests/Avalonia.Controls.UnitTests/VirtualizingCarouselPanelTests.cs b/tests/Avalonia.Controls.UnitTests/VirtualizingCarouselPanelTests.cs index 4f3b2f588f7..b636c69488c 100644 --- a/tests/Avalonia.Controls.UnitTests/VirtualizingCarouselPanelTests.cs +++ b/tests/Avalonia.Controls.UnitTests/VirtualizingCarouselPanelTests.cs @@ -1,9 +1,11 @@ using System; using System.Collections; using System.Collections.ObjectModel; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Avalonia.Animation; +using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; @@ -110,6 +112,28 @@ public void Handles_Moved_Item() Assert.Equal("bar", container.Content); } + [Fact] + public void Handles_Moved_Item_Range() + { + using var app = Start(); + AvaloniaList<string> items = ["foo", "bar", "baz", "qux", "quux"]; + var (target, carousel) = CreateTarget(items); + var container = Assert.IsType<ContentPresenter>(target.Children[0]); + + carousel.SelectedIndex = 3; + Layout(target); + items.MoveRange(0, 2, 4); + Layout(target); + + Assert.Multiple(() => + { + Assert.Single(target.Children); + Assert.Same(container, target.Children[0]); + Assert.Equal("qux", container.Content); + Assert.Equal(1, carousel.SelectedIndex); + }); + } + public class Transitions { [Fact] diff --git a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs index d1ee1662f05..e0fdb6e4858 100644 --- a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs +++ b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs @@ -197,6 +197,68 @@ public void Creates_Elements_On_Item_Insert_2() Assert.Equal(elements, target.GetRealizedElements()); } + [Fact] + public void Updates_Elements_On_Item_Moved() + { + // Arrange + + using var app = App(); + + var actualItems = new AvaloniaList<string>(Enumerable + .Range(0, 100) + .Select(x => $"Item {x}")); + + var (target, _, itemsControl) = CreateTarget(items: actualItems); + + var expectedRealizedElementContents = new[] { 1, 2, 0, 3, 4, 5, 6, 7, 8, 9 } + .Select(x => $"Item {x}"); + + // Act + + actualItems.Move(0, 2); + Layout(target); + + // Assert + + var actualRealizedElementContents = target + .GetRealizedElements() + .Cast<ContentPresenter>() + .Select(x => x.Content); + + Assert.Equivalent(expectedRealizedElementContents, actualRealizedElementContents); + } + + [Fact] + public void Updates_Elements_On_Item_Range_Moved() + { + // Arrange + + using var app = App(); + + var actualItems = new AvaloniaList<string>(Enumerable + .Range(0, 100) + .Select(x => $"Item {x}")); + + var (target, _, itemsControl) = CreateTarget(items: actualItems); + + var expectedRealizedElementContents = new[] { 2, 0, 1, 3, 4, 5, 6, 7, 8, 9 } + .Select(x => $"Item {x}"); + + // Act + + actualItems.MoveRange(0, 2, 3); + Layout(target); + + // Assert + + var actualRealizedElementContents = target + .GetRealizedElements() + .Cast<ContentPresenter>() + .Select(x => x.Content); + + Assert.Equivalent(expectedRealizedElementContents, actualRealizedElementContents); + } + [Fact] public void Updates_Elements_On_Item_Remove() {
`INotifyCollectionChanged` is implemented inconsistently for `Move` and `Replace` operations. ### Describe the bug Various `INotifyCollectionChanged.CollectionChanged` event handlers in Avalonia have an off-by-one error and / or fail to correctly respond to multi-item change events. For example, the following event handler does not respond to multi-item `Move` or `Replace` operations correctly. https://github.com/AvaloniaUI/Avalonia/blob/981f47f05035b700a3b723653d887f338dfbcc1b/src/Avalonia.Controls/Presenters/PanelContainerGenerator.cs#L95-L99 To correctly implement this type of behavior, we should follow the example of MAUI. https://github.com/dotnet/maui/blob/cc683f0e99547c2ed4875296d7451332ef64ca73/src/Controls/src/Core/Internals/NotifyCollectionChangedEventArgsExtensions.cs#L47-L61 Furthermore, the event publishers are not consistent in their interpretations of `INotifyCollectionChanged`. For example, the `AvaloniaList.Move` and `AvaloniaList.MoveRange` methods produce different events for the same mutation (or, equivalently, the same events for different mutations). See the below unit test reflecting this incongruity. ```csharp [TestFixture] public class Tests { [Test] public void Move() { AvaloniaList<int> items = [1, 2, 3]; using (new AssertionScope()) { AssertEvent(items, () => items.Move(0, 1), new NotifyCollectionChangedEventArgs( action: NotifyCollectionChangedAction.Move, changedItems: new[] { 1 }, index: 1, oldIndex: 0)); items.ToArray().Should().BeEquivalentTo(new[] { 2, 1, 3 }, o => o.WithStrictOrdering()); } } [Test] public void MoveRange() { AvaloniaList<int> items = [1, 2, 3]; using (new AssertionScope()) { AssertEvent(items, () => items.MoveRange(0, 1, 1), new NotifyCollectionChangedEventArgs( action: NotifyCollectionChangedAction.Move, changedItems: new[] { 1 }, index: 1, oldIndex: 0)); items.ToArray().Should().BeEquivalentTo(new[] { 2, 1, 3 }, o => o.WithStrictOrdering()); } } private static void AssertEvent(INotifyCollectionChanged items, Action action, NotifyCollectionChangedEventArgs expectedEvent) { items.CollectionChanged += OnCollectionChanged; try { action(); } finally { items.CollectionChanged -= OnCollectionChanged; } return; void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs actualEvent) { actualEvent.Should().BeEquivalentTo(expectedEvent); } } } ``` ### To Reproduce To reproduce one of these behaviors, call `AvaloniaList.MoveRange` and verify that it successfully mutates the list, but fails to correctly update the `PanelContainerGenerator`. ```csharp [AvaloniaTest] public void MoveRange() { // Arrange AvaloniaList<int> items = [1]; var itemsControl = new ItemsControl { ItemsPanel = new FuncTemplate<Panel?>(() => new Panel()), ItemsSource = items }; var window = new Window { Content = itemsControl, Height = 768, Width = 1024 }; window.Show(); // Act items.MoveRange(0, 1, 1); // Assert var actualContents = itemsControl .ItemsPanelRoot! .GetVisualChildren() .Cast<ContentPresenter>() .Select(x => x.Content); actualContents .Should() .BeEquivalentTo(items, o => o.WithStrictOrdering()); } ``` ### Expected behavior - The `AvaloniaList.Move` and `AvaloniaList.MoveRange` operations should throw exceptions before emitting events that will cause subsequent listeners to throw exceptions due to mismatched indices. - `Move(X, Y)` should have the same meaning as `MoveRange(X, 1, Y)`. - `INotifyCollectionChanged` handlers throughout Avalonia should interpret indices in the same way. ### Avalonia version 11.2.0-beta2 ### OS Windows ### Additional context _No response_
null
2024-09-30T17:18:04Z
0.1
['Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Move_Should_Move_One_Item', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.MoveRange_Should_Move_One_Item']
['Avalonia.Base.UnitTests.Collections.AvaloniaListTests.MoveRange_Can_Move_To_End', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.AddRange_Items_Should_Raise_Correct_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.InsertRange_With_Null_Should_Throw_Exception', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.MoveRange_Raises_Correct_CollectionChanged_Event', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.AddRange_With_Null_Should_Throw_Exception', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Inserting_Items_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Replacing_Item_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.AddRange_IEnumerable_Should_Raise_Count_PropertyChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Adding_Items_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Moving_Item_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.InsertRange_Past_End_Should_Throw_Exception', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Adding_Item_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Clearing_Items_Should_Raise_CollectionChanged_Reset', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Can_CopyTo_Array_Of_Same_Type', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Inserting_Item_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Send_Multiple_Notifications_For_Sequential_Range_With_Nonsequential_Duplicate_Source_Items', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_With_Null_Should_Throw_Exception', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Removing_Item_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.MoveRange_Should_Update_Collection', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Send_Single_Notification_For_Sequential_Range_With_Duplicate_Source_Items', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Move_Should_Update_Collection', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Moving_Items_Should_Raise_CollectionChanged', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Send_Single_Notification_For_Sequential_Range', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Clearing_Items_Should_Raise_CollectionChanged_Remove', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Handle_Empty_List', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Items_Passed_To_Constructor_Should_Appear_In_List', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Send_Multiple_Notifications_For_Non_Sequential_Range', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.Can_CopyTo_Array_Of_Base_Type', 'Avalonia.Base.UnitTests.Collections.AvaloniaListTests.RemoveAll_Should_Not_Send_Notification_For_Items_Not_Present']
AvaloniaUI/Avalonia
avaloniaui__avalonia-17135
432fbe8a9eb2e3c807bf71bed43968efbd5a3dec
diff --git a/src/Avalonia.Controls/VirtualizingStackPanel.cs b/src/Avalonia.Controls/VirtualizingStackPanel.cs index 7934e0ccc6b..b3d61a9b643 100644 --- a/src/Avalonia.Controls/VirtualizingStackPanel.cs +++ b/src/Avalonia.Controls/VirtualizingStackPanel.cs @@ -167,7 +167,7 @@ protected override Size MeasureOverride(Size availableSize) // We handle horizontal and vertical layouts here so X and Y are abstracted to: // - Horizontal layouts: U = horizontal, V = vertical // - Vertical layouts: U = vertical, V = horizontal - var viewport = CalculateMeasureViewport(items); + var viewport = CalculateMeasureViewport(orientation, items); // If the viewport is disjunct then we can recycle everything. if (viewport.viewportIsDisjunct) @@ -465,15 +465,15 @@ protected internal override int IndexFromContainer(Control container) return _realizedElements?.Elements ?? Array.Empty<Control>(); } - private MeasureViewport CalculateMeasureViewport(IReadOnlyList<object?> items) + private MeasureViewport CalculateMeasureViewport(Orientation orientation, IReadOnlyList<object?> items) { Debug.Assert(_realizedElements is not null); var viewport = _viewport; // Get the viewport in the orientation direction. - var viewportStart = Orientation == Orientation.Horizontal ? viewport.X : viewport.Y; - var viewportEnd = Orientation == Orientation.Horizontal ? viewport.Right : viewport.Bottom; + var viewportStart = orientation == Orientation.Horizontal ? viewport.X : viewport.Y; + var viewportEnd = orientation == Orientation.Horizontal ? viewport.Right : viewport.Bottom; // Get or estimate the anchor element from which to start realization. If we are // scrolling to an element, use that as the anchor element. Otherwise, estimate the @@ -484,7 +484,7 @@ private MeasureViewport CalculateMeasureViewport(IReadOnlyList<object?> items) if (_scrollToIndex >= 0 && _scrollToElement is not null) { anchorIndex = _scrollToIndex; - anchorU = _scrollToElement.Bounds.Top; + anchorU = orientation == Orientation.Horizontal ? _scrollToElement.Bounds.Left : _scrollToElement.Bounds.Top; } else {
diff --git a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs index d1ee1662f05..ba7765dabbd 100644 --- a/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs +++ b/tests/Avalonia.Controls.UnitTests/VirtualizingStackPanelTests.cs @@ -30,6 +30,13 @@ public class VirtualizingStackPanelTests : ScopedTestBase [!Layoutable.HeightProperty] = new Binding("Height"), }); + private static FuncDataTemplate<ItemWithWidth> CanvasWithWidthTemplate = new((_, _) => + new Canvas + { + Height = 100, + [!Layoutable.WidthProperty] = new Binding("Width"), + }); + [Fact] public void Creates_Initial_Items() { @@ -45,7 +52,7 @@ public void Creates_Initial_Items() public void Initializes_Initial_Control_Items() { using var app = App(); - var items = Enumerable.Range(0, 100).Select(x => new Button { Width = 25, Height = 10}); + var items = Enumerable.Range(0, 100).Select(x => new Button { Width = 25, Height = 10 }); var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: null); Assert.Equal(1000, scroll.Extent.Height); @@ -492,7 +499,7 @@ public void Resetting_Collection_To_Have_Less_Than_A_Page_Of_Items_When_Scrolled public void NthChild_Selector_Works() { using var app = App(); - + var style = new Style(x => x.OfType<ContentPresenter>().NthChild(5, 0)) { Setters = { new Setter(ListBoxItem.BackgroundProperty, Brushes.Red) }, @@ -500,9 +507,9 @@ public void NthChild_Selector_Works() var (target, _, _) = CreateTarget(styles: new[] { style }); var realized = target.GetRealizedContainers()!.Cast<ContentPresenter>().ToList(); - + Assert.Equal(10, realized.Count); - + for (var i = 0; i < 10; ++i) { var container = realized[i]; @@ -537,7 +544,7 @@ public void NthChild_Selector_Works_For_ItemTemplate_Children() var expectedBackground = (i == 4 || i == 9) ? Brushes.Red : null; Assert.Equal(i, index); - Assert.Equal(expectedBackground, ((Canvas) container.Child!).Background); + Assert.Equal(expectedBackground, ((Canvas)container.Child!).Background); } } @@ -590,7 +597,7 @@ public void NthLastChild_Selector_Works_For_ItemTemplate_Children() var expectedBackground = (i == 0 || i == 5) ? Brushes.Red : null; Assert.Equal(i, index); - Assert.Equal(expectedBackground, ((Canvas) container.Child!).Background); + Assert.Equal(expectedBackground, ((Canvas)container.Child!).Background); } } @@ -762,7 +769,7 @@ public void Scrolling_Down_With_Larger_Element_Does_Not_Cause_Jump_And_Arrives_A Layout(target); Assert.True( - target.FirstRealizedIndex >= index, + target.FirstRealizedIndex >= index, $"{target.FirstRealizedIndex} is not greater or equal to {index}"); if (scroll.Offset.Y + scroll.Viewport.Height == scroll.Extent.Height) @@ -801,7 +808,7 @@ public void Scrolling_Up_To_Larger_Element_Does_Not_Cause_Jump() index = target.FirstRealizedIndex; } } - + [Fact] public void Scrolling_Up_To_Smaller_Element_Does_Not_Cause_Jump() { @@ -828,12 +835,12 @@ public void Scrolling_Up_To_Smaller_Element_Does_Not_Cause_Jump() Layout(target); Assert.True( - target.FirstRealizedIndex <= index, + target.FirstRealizedIndex <= index, $"{target.FirstRealizedIndex} is not less than {index}"); Assert.True( index - target.FirstRealizedIndex <= 1, $"FirstIndex changed from {index} to {target.FirstRealizedIndex}"); - + index = target.FirstRealizedIndex; } } @@ -846,7 +853,7 @@ public void Does_Not_Throw_When_Estimating_Viewport_With_Ancestor_Margin() var (_, _, itemsControl) = CreateUnrootedTarget<ItemsControl>(); var container = new Decorator { Margin = new Thickness(100) }; var root = new TestRoot(true, container); - + root.LayoutManager.ExecuteInitialLayoutPass(); container.Child = itemsControl; @@ -889,7 +896,7 @@ public void Supports_Null_Recycle_Key_When_Clearing_Items() Assert.Null(firstItem.Parent); Assert.Null(firstItem.VisualParent); - Assert.Empty(itemsControl.ItemsPanelRoot!.Children); + Assert.Empty(itemsControl.ItemsPanelRoot!.Children); } [Fact] @@ -1038,7 +1045,7 @@ public void Inserting_Item_Before_Viewport_Preserves_FirstRealizedIndex() public void Can_Bind_Item_IsVisible() { using var app = App(); - var style = CreateIsVisibleBindingStyle(); + var style = CreateIsVisibleBindingStyle(); var items = Enumerable.Range(0, 100).Select(x => new ItemWithIsVisible(x)).ToList(); var (target, scroll, itemsControl) = CreateTarget(items: items, styles: new[] { style }); var container = target.ContainerFromIndex(2)!; @@ -1192,6 +1199,58 @@ public void ScrollIntoView_Correctly_Scrolls_Down_To_A_Page_Of_Larger_Items() AssertRealizedItems(target, itemsControl, 15, 5); } + [Fact] + public void ScrollIntoView_Correctly_Scrolls_Right_To_A_Page_Of_Smaller_Items() + { + using var app = App(); + + // First 10 items have width of 20, next 10 have width of 10. + var items = Enumerable.Range(0, 20).Select(x => new ItemWithWidth(x, ((29 - x) / 10) * 10)); + var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: CanvasWithWidthTemplate, orientation: Orientation.Horizontal); + + // Scroll the last item into view. + target.ScrollIntoView(19); + + // At the time of the scroll, the average item width is 20, so the requested item + // should be placed at 380 (19 * 20) which therefore results in an extent of 390 to + // accommodate the item width of 10. This is obviously not a perfect answer, but + // it's the best we can do without knowing the actual item widths. + var container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(19)); + Assert.Equal(new Rect(380, 0, 10, 100), container.Bounds); + Assert.Equal(new Size(100, 100), scroll.Viewport); + Assert.Equal(new Size(390, 100), scroll.Extent); + Assert.Equal(new Vector(290, 0), scroll.Offset); + + // Items 10-19 should be visible. + AssertRealizedItems(target, itemsControl, 10, 10); + } + + [Fact] + public void ScrollIntoView_Correctly_Scrolls_Right_To_A_Page_Of_Larger_Items() + { + using var app = App(); + + // First 10 items have width of 10, next 10 have width of 20. + var items = Enumerable.Range(0, 20).Select(x => new ItemWithWidth(x, ((x / 10) + 1) * 10)); + var (target, scroll, itemsControl) = CreateTarget(items: items, itemTemplate: CanvasWithWidthTemplate, orientation: Orientation.Horizontal); + + // Scroll the last item into view. + target.ScrollIntoView(19); + + // At the time of the scroll, the average item width is 10, so the requested item + // should be placed at 190 (19 * 10) which therefore results in an extent of 210 to + // accommodate the item width of 20. This is obviously not a perfect answer, but + // it's the best we can do without knowing the actual item widths. + var container = Assert.IsType<ContentPresenter>(target.ContainerFromIndex(19)); + Assert.Equal(new Rect(190, 0, 20, 100), container.Bounds); + Assert.Equal(new Size(100, 100), scroll.Viewport); + Assert.Equal(new Size(210, 100), scroll.Extent); + Assert.Equal(new Vector(110, 0), scroll.Offset); + + // Items 15-19 should be visible. + AssertRealizedItems(target, itemsControl, 15, 5); + } + [Fact] public void Extent_And_Offset_Should_Be_Updated_When_Containers_Resize() { @@ -1348,21 +1407,24 @@ private static void AssertRealizedControlItems<TContainer>( private static (VirtualizingStackPanel, ScrollViewer, ItemsControl) CreateTarget( IEnumerable<object>? items = null, Optional<IDataTemplate?> itemTemplate = default, - IEnumerable<Style>? styles = null) + IEnumerable<Style>? styles = null, + Orientation orientation = Orientation.Vertical) { return CreateTarget<ItemsControl>( - items: items, - itemTemplate: itemTemplate, - styles: styles); + items: items, + itemTemplate: itemTemplate, + styles: styles, + orientation: orientation); } private static (VirtualizingStackPanel, ScrollViewer, T) CreateTarget<T>( IEnumerable<object>? items = null, Optional<IDataTemplate?> itemTemplate = default, - IEnumerable<Style>? styles = null) + IEnumerable<Style>? styles = null, + Orientation orientation = Orientation.Vertical) where T : ItemsControl, new() { - var (target, scroll, itemsControl) = CreateUnrootedTarget<T>(items, itemTemplate); + var (target, scroll, itemsControl) = CreateUnrootedTarget<T>(items, itemTemplate, orientation); var root = CreateRoot(itemsControl, styles: styles); root.LayoutManager.ExecuteInitialLayoutPass(); @@ -1372,10 +1434,14 @@ private static (VirtualizingStackPanel, ScrollViewer, T) CreateTarget<T>( private static (VirtualizingStackPanel, ScrollViewer, T) CreateUnrootedTarget<T>( IEnumerable<object>? items = null, - Optional<IDataTemplate?> itemTemplate = default) + Optional<IDataTemplate?> itemTemplate = default, + Orientation orientation = Orientation.Vertical) where T : ItemsControl, new() { - var target = new VirtualizingStackPanel(); + var target = new VirtualizingStackPanel + { + Orientation = orientation, + }; items ??= new ObservableCollection<string>(Enumerable.Range(0, 100).Select(x => $"Item {x}")); @@ -1388,9 +1454,16 @@ private static (VirtualizingStackPanel, ScrollViewer, T) CreateUnrootedTarget<T> { Name = "PART_ScrollViewer", Content = presenter, - Template = ScrollViewerTemplate(), }; + if (orientation == Orientation.Horizontal) + { + scroll.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; + scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; + } + + scroll.Template = ScrollViewerTemplate(); + var itemsControl = new T { ItemsSource = items, @@ -1403,7 +1476,7 @@ private static (VirtualizingStackPanel, ScrollViewer, T) CreateUnrootedTarget<T> } private static TestRoot CreateRoot( - Control? child, + Control? child, Size? clientSize = null, IEnumerable<Style>? styles = null) { @@ -1469,16 +1542,35 @@ public ItemWithHeight(int index, double height = 10) Caption = $"Item {index}"; Height = height; } - + public string Caption { get; set; } - - public double Height + + public double Height { get => _height; set => SetField(ref _height, value); } } + private class ItemWithWidth : NotifyingBase + { + private double _width; + + public ItemWithWidth(int index, double width = 10) + { + Caption = $"Item {index}"; + Width = width; + } + + public string Caption { get; set; } + + public double Width + { + get => _width; + set => SetField(ref _width, value); + } + } + private class ItemWithIsVisible : NotifyingBase { private bool _isVisible = true;
[Bug] VirtualizingStackPanel (horizontal) issue in ListBox when scrolling using arrow keys [11.0.11 -> now][with repro] ### Describe the bug I noticed a problem in ListBox when selecting items using arrow keys. My ListBox I am pressing Right arrow key. As you can see in the video, once the last items is selected, the listbox scroll by 1 page instead of 1 item. Moreover, it do not end at the last item, but it wrap to the begining. In addition, the scroll bar do not reflect the position in the ScrollView. https://github.com/user-attachments/assets/7466543c-eb0b-4488-951f-3c346176d0e4 And if I use the left arrow, instead of right, it scroll by 1 item at the time, with no wrapping... I checked in 11.0.10 and it work perfectly The video is captured using 11.0.13 => bug 11.0.11 => bug I tested latest version 11.1.3 and 11.2 beta and same problem. ### To Reproduce [AvaloniaListBoxBug.zip](https://github.com/user-attachments/files/17134242/AvaloniaListBoxBug.zip) ### Expected behavior Working perfectly in 11.0.10 https://github.com/user-attachments/assets/1c0488b7-c3b5-46a0-93ca-2db188fa6fce ### Avalonia version 11.0.11 ### OS Windows ### Additional context My ListBox is horizontal ``` <ListBox ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Disabled" Height="150" DockPanel.Dock="Bottom" ItemsSource="{Binding Items}"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel Orientation="Horizontal" /> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemContainerTheme> <ControlTheme BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="ListBoxItem"> <Setter Property="Margin" Value="2" /> <Setter Property="Width" Value="120" /> <Setter Property="Height" Value="120" /> </ControlTheme> </ListBox.ItemContainerTheme> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` It look like the issue is in VirtualizingStackPanel when Orientation is Horizontal, not ListBox. Changes from 11.0.10 to 11.0.11 ![image](https://github.com/user-attachments/assets/d5424615-1e26-4626-97f6-43a793746bd6) EDIT: no problem with StackPanel instead of VirtualizingStackPanel no problem with vertical direction
@grokys May be the bug is here? Missing an Orientation check? ![image](https://github.com/user-attachments/assets/475c60ef-06bd-4b83-925e-ca4f6c57e485) Yeah could be a missing orientation check. Should be easy to add. Can you file a PR for it?
2024-09-26T07:37:49Z
0.1
['Avalonia.Controls.UnitTests.VirtualizingStackPanelTests.ScrollIntoView_Correctly_Scrolls_Right_To_A_Page_Of_Smaller_Items', 'Avalonia.Controls.UnitTests.VirtualizingStackPanelTests.ScrollIntoView_Correctly_Scrolls_Right_To_A_Page_Of_Larger_Items']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-17073
85fff4a2320d87236c3f850b5de87129e6587458
diff --git a/src/Avalonia.Base/Data/Core/BindingExpression.cs b/src/Avalonia.Base/Data/Core/BindingExpression.cs index abf6f6cb887..635fa3e0960 100644 --- a/src/Avalonia.Base/Data/Core/BindingExpression.cs +++ b/src/Avalonia.Base/Data/Core/BindingExpression.cs @@ -512,8 +512,10 @@ private void OnTargetPropertyChanged(object? sender, AvaloniaPropertyChangedEven Debug.Assert(_mode is BindingMode.TwoWay or BindingMode.OneWayToSource); Debug.Assert(UpdateSourceTrigger is UpdateSourceTrigger.PropertyChanged); - if (e.Property == TargetProperty) - WriteValueToSource(e.NewValue); + // The value must be read from the target object instead of using the value from the event + // because the value may have changed again between the time the event was raised and now. + if (e.Property == TargetProperty && TryGetTarget(out var target)) + WriteValueToSource(target.GetValue(TargetProperty)); } private object? ConvertFallback(object? fallback, string fallbackName)
diff --git a/tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs b/tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs index d4a799da6fc..9fb52fee388 100644 --- a/tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs +++ b/tests/Avalonia.Markup.UnitTests/Data/BindingTests.cs @@ -667,6 +667,31 @@ public void OneWayToSource_Binding_Does_Not_Override_TwoWay_Binding() Assert.Equal("TwoWay", source.Foo); } + [Fact] + public void Target_Undoing_Property_Change_During_TwoWay_Binding_Does_Not_Cause_StackOverflow() + { + var source = new TestStackOverflowViewModel { BoolValue = true }; + var target = new TwoWayBindingTest(); + + source.ResetSetterInvokedCount(); + + // The AlwaysFalse property is set to false in the PropertyChanged callback. Ensure + // that binding it to an initial `true` value with a two-way binding does not cause a + // stack overflow. + target.Bind( + TwoWayBindingTest.AlwaysFalseProperty, + new Binding(nameof(TestStackOverflowViewModel.BoolValue)) + { + Mode = BindingMode.TwoWay, + }); + + target.DataContext = source; + + Assert.Equal(1, source.SetterInvokedCount); + Assert.False(source.BoolValue); + Assert.False(target.AlwaysFalse); + } + private class StyledPropertyClass : AvaloniaObject { public static readonly StyledProperty<double> DoubleValueProperty = @@ -725,10 +750,24 @@ private class TestStackOverflowViewModel : INotifyPropertyChanged public const int MaxInvokedCount = 1000; + private bool _boolValue; private double _value; public event PropertyChangedEventHandler PropertyChanged; + public bool BoolValue + { + get => _boolValue; + set + { + if (_boolValue != value) + { + _boolValue = value; + SetterInvokedCount++; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BoolValue))); + } + } } + public double Value { get => _value; @@ -754,20 +793,38 @@ public double Value } } } + + public void ResetSetterInvokedCount() => SetterInvokedCount = 0; } private class TwoWayBindingTest : Control { + public static readonly StyledProperty<bool> AlwaysFalseProperty = + AvaloniaProperty.Register<StyledPropertyClass, bool>(nameof(AlwaysFalse)); public static readonly StyledProperty<string> TwoWayProperty = AvaloniaProperty.Register<TwoWayBindingTest, string>( "TwoWay", defaultBindingMode: BindingMode.TwoWay); + public bool AlwaysFalse + { + get => GetValue(AlwaysFalseProperty); + set => SetValue(AlwaysFalseProperty, value); + } + public string TwoWay { get => GetValue(TwoWayProperty); set => SetValue(TwoWayProperty, value); } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + + if (change.Property == AlwaysFalseProperty) + SetCurrentValue(AlwaysFalseProperty, false); + } } public class Source : INotifyPropertyChanged
stack overflow in binding system ### Describe the bug We are observing a stack overflow, caused by a loop in the binding code. Below are two full iterations of the loop that leads to the stack overflow. ### To Reproduce This issue is very easy to recreate. Adding a MaskedTextBox to a page bound to a string that has an initial value that does not conform to the format of the mask (including null or empty string) will immediately cause a stack overflow when the application starts. ### Expected behavior No stack overflow is expected. ### Avalonia version nightly build 11.2.999-cibuild0051406-alpha last known good version is 11.0.13 ### OS macOS ### Additional context ``` at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.Plugins.DataValidationBase.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.Plugins.ExceptionValidationPlugin+Validator.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.ExpressionNodes.PropertyAccessorNode.WriteValueToSource(System.Object, System.Collections.Generic.IReadOnlyList`1<Avalonia.Data.Core.ExpressionNodes.ExpressionNode>) at Avalonia.Data.Core.BindingExpression.WriteValueToSource(System.Object) at Avalonia.Data.Core.BindingExpression.OnTargetPropertyChanged(System.Object, Avalonia.AvaloniaPropertyChangedEventArgs) at Avalonia.AvaloniaObject.RaisePropertyChanged(Avalonia.AvaloniaProperty`1<System.__Canon>, Avalonia.Data.Optional`1<System.__Canon>, Avalonia.Data.BindingValue`1<System.__Canon>, Avalonia.Data.BindingPriority, Boolean) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(Avalonia.PropertyStore.ValueStore, Avalonia.StyledProperty`1<System.__Canon>, System.__Canon, Avalonia.Data.BindingPriority, Boolean, Boolean) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(Avalonia.PropertyStore.ValueStore, Avalonia.StyledProperty`1<System.__Canon>, System.__Canon) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(Avalonia.PropertyStore.ValueStore, Avalonia.AvaloniaProperty, System.Object) at Avalonia.PropertyStore.ValueStore.SetLocalValue(Avalonia.AvaloniaProperty, System.Object) at Avalonia.PropertyStore.ValueStore.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(Avalonia.Data.Core.UntypedBindingExpressionBase, Boolean, Boolean, System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.BindingExpression.ConvertAndPublishValue(System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.BindingExpression.OnNodeValueChanged(Int32, System.Object, System.Exception) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object, System.Exception) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object) at Avalonia.Data.Core.ExpressionNodes.PropertyAccessorNode.OnValueChanged(System.Object) at Avalonia.Data.Core.Plugins.PropertyAccessorBase.PublishValue(System.Object) at Avalonia.Data.Core.Plugins.DataValidationBase.InnerValueChanged(System.Object) at Avalonia.Data.Core.Plugins.PropertyAccessorBase.PublishValue(System.Object) at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SendCurrentValue() Now the loop starts over.... at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.Plugins.DataValidationBase.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.Plugins.ExceptionValidationPlugin+Validator.SetValue(System.Object, Avalonia.Data.BindingPriority) at Avalonia.Data.Core.ExpressionNodes.PropertyAccessorNode.WriteValueToSource(System.Object, System.Collections.Generic.IReadOnlyList`1<Avalonia.Data.Core.ExpressionNodes.ExpressionNode>) at Avalonia.Data.Core.BindingExpression.WriteValueToSource(System.Object) at Avalonia.Data.Core.BindingExpression.OnTargetPropertyChanged(System.Object, Avalonia.AvaloniaPropertyChangedEventArgs) at Avalonia.AvaloniaObject.RaisePropertyChanged(Avalonia.AvaloniaProperty`1<System.__Canon>, Avalonia.Data.Optional`1<System.__Canon>, Avalonia.Data.BindingValue`1<System.__Canon>, Avalonia.Data.BindingPriority, Boolean) at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(Avalonia.PropertyStore.ValueStore, Avalonia.StyledProperty`1<System.__Canon>, System.__Canon, Avalonia.Data.BindingPriority, Boolean, Boolean) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(Avalonia.PropertyStore.ValueStore, Avalonia.StyledProperty`1<System.__Canon>, System.__Canon) at Avalonia.PropertyStore.EffectiveValue`1.SetLocalValueAndRaise(Avalonia.PropertyStore.ValueStore, Avalonia.AvaloniaProperty, System.Object) at Avalonia.PropertyStore.ValueStore.SetLocalValue(Avalonia.AvaloniaProperty, System.Object) at Avalonia.PropertyStore.ValueStore.Avalonia.Data.Core.IBindingExpressionSink.OnChanged(Avalonia.Data.Core.UntypedBindingExpressionBase, Boolean, Boolean, System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.UntypedBindingExpressionBase.PublishValue(System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.BindingExpression.ConvertAndPublishValue(System.Object, Avalonia.Data.Core.BindingError) at Avalonia.Data.Core.BindingExpression.OnNodeValueChanged(Int32, System.Object, System.Exception) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object, System.Exception) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object) at Avalonia.Data.Core.ExpressionNodes.ExpressionNode.SetValue(System.Object) at Avalonia.Data.Core.ExpressionNodes.PropertyAccessorNode.OnValueChanged(System.Object) at Avalonia.Data.Core.Plugins.PropertyAccessorBase.PublishValue(System.Object) at Avalonia.Data.Core.Plugins.DataValidationBase.InnerValueChanged(System.Object) at Avalonia.Data.Core.Plugins.PropertyAccessorBase.PublishValue(System.Object) at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SendCurrentValue() ``` The loop is kicked off initially by this statement: ` at Avalonia.Markup.Xaml.MarkupExtensions.CompiledBindings.InpcPropertyAccessor.SubscribeCore() `
Interesting. If you disable CompiledBindings for a test, does it disappear? After adding this to my project file, the result is the same. ` <AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault> ` `MaskedTextBox` has not changed very much, so it is doing what it has always done, which is to refresh the Text property in the `OnTextInput` `OnKeyDown` and `OnPropertyChanged` events. If I comment out line 443 in MaskedTextBox.cs, the problem goes away, but of course then the control displays nothing: `SetCurrentValue(TextProperty, provider.ToDisplayString());` The Binding System went though a major refactor (#13970), so I assume that the issue was introduced there. The initial `Text` value is being set to null, the `OnPropertyChanged` event fires, causing a refresh to the `Text` property (again), and the cycle seems to repeat. The docs say the `SetCurrentValue` method is supposed to be used for programmatically setting a bound property, so it makes sense that is the method called during the events. This issue caught my eye, but it did not help to test without the changes. I thought I'd mention it here anyway. **Make bindings react to PropertyChanged even if property hasn't changed** https://github.com/AvaloniaUI/Avalonia/pull/16150 Thanks for testing. I also end up in an infinite cycle with another 3rd party control and can't wrap my head around. So if it was compiled bindings extension, that would have been a good entry point. I'm also certain it has to do with the bindings refractor somehow. /cc @grokys will try to see if I can mange to get this into Sandbox to narrow it down as this is also bugging me ^^ @busitech I can't reproduce this with a simple sample :-( Can you provide a minimal sample for me to test? My ViewModel: ```cs public partial class MainViewModel: ObservableObject { [ObservableProperty] private string? _name; } ``` My MainView: ```xml <MaskedTextBox Text="{Binding Name}" Mask="???" /> ``` Yes, here is my test project. [MaskedTextBoxTest.zip](https://github.com/user-attachments/files/16688845/MaskedTextBoxTest.zip) Hello @timunie, were you able to reproduce with my sample? Another side effect of the binding system changes is that the source property of the Binding on the Text property of the MaskedTextBox is being set to the masked value, even before any user input has been made in the control. At 11.0.13, no changes would be made to the source property until user input occurs. This would be the correct behavior. One input necessary to reproduce this issue is to bind the Text property on the MaskedTextBox to an initial value that does not conform to the mask (including null or empty string). > Hello @timunie, were you able to reproduce with my sample? Guess what? I was able to reproduce it with your sample attached. I added the relevant parts to Sandbox, and the issue was gone. Can't wrap my head around it yet 🤷 I am reproducing with the nightly build 11.2.999-cibuild0051406-alpha, and with my sample directly inside the Avalonia project, using the latest commit. I produced a patch today that takes care of the writing back of the value during the initial subscription, and that took care of the cycle. This is a very simple approach to preventing the stack overflow, by preventing the write-back of the value to the source during publish. [prevent_stack_overflow.patch](https://github.com/user-attachments/files/16707560/prevent_stack_overflow.patch) 👍 could you make a PR of that patch? - Helps to run unit tests - easier for the team to feedback and double-check Today I made a new patch I am more pleased with. It will be the basis of my PR. I ran up against this exception as well. I was using a `MaskedTextBox` in the format of a GUID value, with the exception occurring at init when passing in `string.Empty` ` <MaskedTextBox AsciiOnly="True" Name="AccountIdTextBox" Mask=">AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" Text="{Binding LicenseActivator.AccountIdString}"/> ` Exception occurs when: ``` private string _accountIdString = ""; public string AccountIdString { get => _accountIdString; set => this.RaiseAndSetIfChanged(ref _accountIdString, value); } ``` No exception when: ``` private string _accountIdString = "4A3E0760-09E5-4D73-B5BB-256ED9F8A83F"; public string AccountIdString { get => _accountIdString; set => this.RaiseAndSetIfChanged(ref _accountIdString, value); } ``` And also no exception when using OneWayToSource binding mode. ` <MaskedTextBox AsciiOnly="True" Name="AccountIdTextBox" Mask=">AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA" Text="{Binding LicenseActivator.AccountIdString, Mode=OneWayToSource}"/> ` @EvanHaklar can you try the linked PR as well with your sample? Triggering a property change event for unchanged values should not cause any issues. Sounds like the control relies on some specific behavior. To prevent such issues you usually want to have some internal state that makes sure a computed write back isn't causing an infinite loop. @Gillibald The control, [MaskedTextBox](https://docs.avaloniaui.net/docs/reference/controls/maskedtextbox), is an Avalonia supplied / maintained control. As stated in the attached PR, the binding subsystem is sending obsolete change events containing old values, _after_ those values have already been replaced by newer values, and after events have already been sent to the same subscribers with the most current value. This is the root cause of the endless loop. The MaskedTextBox control relies on this specific behavior: the absence of obsolete and out of sequence events being sent. I believe this would be the correct behavior of the binding system, and not a shortcoming of the control. The control was designed to iterate a couple of times recursively at startup when populated with an empty value, but it did not do so infinitely until the binding system went through an overhaul (that project is referenced above). This caused regression in the MaskedTextBox. I think the binding subsystem lacks loop detection, and also lacks protection from sending stale values in the event of recursion during publication. The write back to source seems to be happening more often, which is also unwanted at times. @timunie Without having a perfect understanding of the entire theory of design behind the binding subsystem, our PR takes a stab at these three major areas, in the hopes of having the additional discussion you mentioned with the team about the items we have identified as root issues.
2024-09-20T10:14:11Z
0.1
['Avalonia.Markup.UnitTests.Data.BindingTests.Target_Undoing_Property_Change_During_TwoWay_Binding_Does_Not_Cause_StackOverflow']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16712
228ecc5003c77dd74d2f037eb69daa4102312015
diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index a627c15765b..b12c23c5975 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -1468,7 +1468,7 @@ protected override void OnKeyDown(KeyEventArgs e) SetCurrentValue(CaretIndexProperty, start); - _presenter.MoveCaretToTextPosition(start, true); + _presenter.MoveCaretToTextPosition(start); } }
diff --git a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs index 1cd42a6c6a1..42e42dd9f6e 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs @@ -1492,6 +1492,43 @@ public void Should_Throw_ArgumentOutOfRange() } } + [Fact] + public void Backspace_Should_Delete_Last_Character_In_Line_And_Keep_Caret_On_Same_Line() + { + using var _ = UnitTestApplication.Start(Services); + + var textBox = new TextBox + { + Template = CreateTemplate(), + Text = "a\nb", + CaretIndex = 3 + }; + textBox.ApplyTemplate(); + + var topLevel = new TestTopLevel(CreateMockTopLevelImpl().Object) + { + Template = CreateTopLevelTemplate(), + Content = textBox + }; + topLevel.ApplyTemplate(); + topLevel.LayoutManager.ExecuteInitialLayoutPass(); + + var textPresenter = textBox.FindDescendantOfType<TextPresenter>(); + Assert.NotNull(textPresenter); + + var oldCaretY = textPresenter.GetCursorRectangle().Top; + Assert.NotEqual(0, oldCaretY); + + RaiseKeyEvent(textBox, Key.Back, KeyModifiers.None); + + Assert.Equal("a\n", textBox.Text); + Assert.Equal(2, textBox.CaretIndex); + Assert.Equal(2, textPresenter.CaretIndex); + + var caretY = textPresenter.GetCursorRectangle().Top; + Assert.Equal(oldCaretY, caretY); + } + private static TestServices FocusServices => TestServices.MockThreadingInterface.With( focusManager: new FocusManager(), keyboardDevice: () => new KeyboardDevice(),
Backspace incorrectly places caret before linebreak when deleting the last character of a line ### Describe the bug The following video is a single Backspace key press followed by an Enter key press: https://github.com/user-attachments/assets/51b7adad-bc45-42ad-b148-7397667311c0 Notice that backspace deletes 'b' and moves the caret to the line before. Only 'b' should be deleted, and the caret moved at the start of the current line. ### To Reproduce Delete the last character of a line in a multi-line textbox. ### Expected behavior The caret should stay on the current line. ### Avalonia version master 228ecc5003c77dd74d2f037eb69daa4102312015 ### OS _No response_ ### Additional context Caused by #16135
null
2024-08-16T14:43:48Z
0.1
['Avalonia.Controls.UnitTests.TextBoxTests.Backspace_Should_Delete_Last_Character_In_Line_And_Keep_Caret_On_Same_Line']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16710
21d8cea26bc0175b3a92399754e0587d3b736e91
diff --git a/src/Avalonia.Controls/TextBoxTextInputMethodClient.cs b/src/Avalonia.Controls/TextBoxTextInputMethodClient.cs index 0ff857985a4..5d35124c69a 100644 --- a/src/Avalonia.Controls/TextBoxTextInputMethodClient.cs +++ b/src/Avalonia.Controls/TextBoxTextInputMethodClient.cs @@ -180,6 +180,11 @@ public override void ShowInputPanel() private static string GetTextLineText(TextLine textLine) { + if (textLine.Length == 0) + { + return string.Empty; + } + var builder = StringBuilderCache.Acquire(textLine.Length); foreach (var run in textLine.TextRuns)
diff --git a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs index 42e42dd9f6e..30f82533cea 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs @@ -9,11 +9,10 @@ using Avalonia.Headless; using Avalonia.Input; using Avalonia.Input.Platform; +using Avalonia.Input.TextInput; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform; -using Avalonia.Rendering; -using Avalonia.Rendering.Composition; using Avalonia.UnitTests; using Avalonia.VisualTree; using Moq; @@ -1492,6 +1491,30 @@ public void Should_Throw_ArgumentOutOfRange() } } + [Fact] + public void InputMethodClient_SurroundingText_Returns_Empty_For_Empty_Line() + { + using var _ = UnitTestApplication.Start(Services); + + var textBox = new TextBox + { + Template = CreateTemplate(), + Text = "", + CaretIndex = 0 + }; + textBox.ApplyTemplate(); + + var eventArgs = new TextInputMethodClientRequestedEventArgs + { + RoutedEvent = InputElement.TextInputMethodClientRequestedEvent + }; + textBox.RaiseEvent(eventArgs); + + var client = eventArgs.Client; + Assert.NotNull(client); + Assert.Equal(string.Empty, client.SurroundingText); + } + [Fact] public void Backspace_Should_Delete_Last_Character_In_Line_And_Keep_Caret_On_Same_Line() {
TextBlock unexpectedly deletes first character when using input method auto-complete ### Describe the bug When using the `auto-complete` feature of an input method (IME) with a `TextBlock` control, the first English character at the beginning of a line is unexpectedly deleted. This behavior occurs consistently and affects the user experience. ### To Reproduce 1. Set up a TextBlock control in your application. 2. Enable an input method that supports auto-complete (e.g., Gboard). 3. Begin typing at the start of a line, using the IME's auto-complete feature. 4. Observe that the first English character is deleted after auto-complete is applied. ### Expected behavior The TextBlock should maintain all characters, including the first one, when using IME `auto-complete`. ### Avalonia version 11.1.2 ### OS Android ### Additional context Code ``` <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Text="Base &lt;TextBox Width=&quot;200&quot; Height=&quot;50&quot; /&gt;"/> <StackPanel Background="Aqua"> <TextBlock Text="Base With Height and Width attributes" /> <TextBox Width="200" Height="50" /> </StackPanel> <StackPanel Background="Chocolate"> <TextBlock Text="TextInputOptions.ReturnKeyType=&quot;Return&quot;" /> <TextBox Width="200" Height="50" TextInputOptions.ReturnKeyType="Return" /> </StackPanel> <StackPanel Background="Crimson"> <TextBlock Text="AcceptsReturn=&quot;True" /> <TextBox Width="200" Height="50" AcceptsReturn="True" /> </StackPanel> <StackPanel Background="DarkOrange"> <TextBlock Text="AcceptsReturn=&quot;True&quot; TextInputOptions.ReturnKeyType=&quot;Return&quot;" /> <TextBox Width="200" Height="50" AcceptsReturn="True" TextInputOptions.ReturnKeyType="Return" /> </StackPanel> </StackPanel> ```
Could you test with https://github.com/AvaloniaUI/Avalonia/pull/16666 > Could you test with #16666 ``<PackageReference Include="Avalonia.Android" Version="11.2.999-cibuild0051177-alpha" />`` ![image](https://github.com/user-attachments/assets/ee0800e2-0ca0-48a3-8485-212d14c9374c) I tested it on my Android 10 device and my first letter still gets eaten. - [x] Solution Cleaned - [x] Packges Download from https://dev.azure.com/AvaloniaUI/AvaloniaUI/_build/results?buildId=51177 try this 11.2.999-cibuild0051149-alpha > Try this 11.2.999-cibuild0051149-alpha I tested it on my Android 10 device`Gboard` and my first letter still gets eaten. But [Sogou Pinyin](https://en.wikipedia.org/wiki/Sogou_Pinyin) works well. I don't know how it can be. But Google develops Gboad, it is more likely to adopt the standard. What's your GBoard version? I've tested many versions across many android versions(OS 6,9, 10, 11, 13, 14), only the AOSP keyboard(not GBoard) on stock Android 10 has an issue with not sending composing regions which is fixed in the linked pr. GBoard itself works fine. > What's your GBoard version? I've tested many versions across many android versions(OS 6,9, 10, 11, 13, 14), only the AOSP keyboard(not GBoard) on stock Android 10 has an issue with not sending composing regions which is fixed in the linked pr. GBoard itself works fine. 14.4.04.646482735-release-arm64-v8a System: Android 10 with MIUI 12.5.1 (MIX2S) I've been able to reproduce the issue. Currently debugging it, and it's a weird issue as it only occurs on the first word. Could you test with this? 11.2.999-cibuild0051267-alpha Fixed, thank you, bro. If needed, I will test it on more devices. The fix isn't merged yet.
2024-08-16T13:10:58Z
0.1
['Avalonia.Controls.UnitTests.TextBoxTests.InputMethodClient_SurroundingText_Returns_Empty_For_Empty_Line']
[]
AvaloniaUI/Avalonia
avaloniaui__avalonia-16619
ec655a9f7e8cb53536890112807ddf5d1caae9da
diff --git a/src/Avalonia.Controls/Button.cs b/src/Avalonia.Controls/Button.cs index dc836a08716..614847ee4e8 100644 --- a/src/Avalonia.Controls/Button.cs +++ b/src/Avalonia.Controls/Button.cs @@ -289,8 +289,9 @@ protected override void OnKeyDown(KeyEventArgs e) OnClick(); e.Handled = true; break; - case Key.Space: + // Avoid handling Space if the button isn't focused: a child TextBox might need it for text input + if (IsFocused) { if (ClickMode == ClickMode.Press) { @@ -299,22 +300,21 @@ protected override void OnKeyDown(KeyEventArgs e) IsPressed = true; e.Handled = true; - break; } - + break; case Key.Escape when Flyout != null: // If Flyout doesn't have focusable content, close the flyout here CloseFlyout(); break; } - base.OnKeyDown(e); } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { - if (e.Key == Key.Space) + // Avoid handling Space if the button isn't focused: a child TextBox might need it for text input + if (e.Key == Key.Space && IsFocused) { if (ClickMode == ClickMode.Release) {
diff --git a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs index 876adcc28fe..e3b974491aa 100644 --- a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs @@ -511,11 +511,39 @@ public void Button_CommandParameter_Does_Not_Change_While_Execution() (target as IClickableControl).RaiseClick(); } + [Fact] + void Should_Not_Fire_Click_Event_On_Space_Key_When_It_Is_Not_Focus() + { + using (UnitTestApplication.Start(TestServices.StyledWindow)) + { + var raised = 0; + var target = new TextBox(); + var button = new Button() + { + Content = target, + }; + + var window = new Window { Content = button }; + window.Show(); + + button.Click += (s, e) => ++raised; + target.Focus(); + target.RaiseEvent(CreateKeyDownEvent(Key.Space)); + target.RaiseEvent(CreateKeyUpEvent(Key.Space)); + Assert.Equal(0, raised); + } + } + private KeyEventArgs CreateKeyDownEvent(Key key, Interactive source = null) { return new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, Source = source }; } + private KeyEventArgs CreateKeyUpEvent(Key key, Interactive source = null) + { + return new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = key, Source = source }; + } + private void RaisePointerPressed(Button button, int clickCount, MouseButton mouseButton, Point position) { _helper.Down(button, mouseButton, position, clickCount: clickCount);
Button should check `RoutedEventArgs.Source` before handling keys ### Describe the bug Reported in https://github.com/amwx/FluentAvalonia/issues/591. Placing a text control into an Expander header does not allow spaces. The cause is the `Button` that is found in the Expander's header (which is part of the template for my SettingsExpander control in the referenced issue) is consuming this event and the TextBox never sees it. I looked at WPF source, they do a check in `ButtonBase` to see if the event source is the button and only handle it in that case - Avalonia should do the same check. https://github.com/dotnet/wpf/blob/0628a7722ccdc47ebe66beb5eb8cee756d05f7d9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/Primitives/ButtonBase.cs#L612-L647 ### To Reproduce Add a TextBox to an Expander and try to type text with spaces. Only the text will be entered, the space key will open/close the expander. ### Expected behavior _No response_ ### Avalonia version 11.1-rc1 ### OS Windows ### Additional context _No response_
null
2024-08-07T16:19:12Z
0.1
['Avalonia.Controls.UnitTests.ButtonTests.Should_Not_Fire_Click_Event_On_Space_Key_When_It_Is_Not_Focus']
[]