diff --git a/TheBleedingDeacons.Intergroup.Register.Core/Services/ReconciliationService.cs b/TheBleedingDeacons.Intergroup.Register.Core/Services/ReconciliationService.cs index 1d3ac44..d5db694 100644 --- a/TheBleedingDeacons.Intergroup.Register.Core/Services/ReconciliationService.cs +++ b/TheBleedingDeacons.Intergroup.Register.Core/Services/ReconciliationService.cs @@ -214,6 +214,30 @@ public async Task ReconcileAsync( Total: newMembers.Count)); } + // Every create names itself with the member's ClientReference, so + // Unity returns the member it already made when a create is sent + // again — after a lost response, a retried batch, or a second + // Finish. The tablet sets the reference when the member is entered; + // one that somehow has none gets it here, saved before anything is + // sent so every later attempt carries the same value. If it can't + // be saved the create is held back: sending it under a reference + // the next attempt won't know is how duplicates are made. + foreach (var member in newMembers.Where(m => m.ClientReference is null)) + { + Guid? reference = Guid.NewGuid(); + try + { + await db.Members + .Where(m => m.Id == member.Id) + .ExecuteUpdateAsync(set => set.SetProperty(m => m.ClientReference, reference), ct); + member.ClientReference = reference; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Logger.Error(ex, "Could not save a client reference for new member {Name} (temp ID {TempId}); holding back its create until the next sync", member.AnonymousName, member.Id); + } + } + int createIndex = 0; foreach (var member in newMembers) { @@ -224,10 +248,20 @@ public async Task ReconcileAsync( Current: createIndex, Total: newMembers.Count)); + if (member.ClientReference is null) + { + // Logged above. Counted as a failed create so the logs are + // kept and its dependent registrations wait with it. + apiErrors++; + failedCreates.Add(member.Id); + continue; + } + try { var request = new CreateMemberRequest { + ClientReference = member.ClientReference, AnonymousName = member.AnonymousName, PersonalEmail = member.PersonalEmail, MobileNumber = member.MobileNumber, @@ -685,6 +719,12 @@ public async Task ReconcileAsync( unregisteredGroups++; Logger.Information("Unregistered group {Name} (ID={Id}) on Unity", group.Name, group.Id); } + else if (IsNotRegisteredError(response)) + { + unregisteredGroups++; + Logger.Information("Group {Name} (ID={Id}) was already unregistered on Unity — treating as success", + group.Name, group.Id); + } else { apiErrors++; @@ -792,6 +832,11 @@ public async Task ReconcileAsync( unregisteredPositions++; Logger.Information("Unregistered officer {Id} on Unity", officerId); } + else if (IsNotRegisteredError(response)) + { + unregisteredPositions++; + Logger.Information("Officer {Id} was already unregistered on Unity — treating as success", officerId); + } else { apiErrors++; @@ -1037,6 +1082,20 @@ private static bool IsAlreadyRegisteredError(ApiResponse response) where T || msg.Contains("already registered", StringComparison.Ordinal) || msg.Contains("already exists", StringComparison.Ordinal); } + /// + /// Returns true when an unregister call failed only because Unity holds + /// no registration to remove — the outcome the call was after. Mirrors + /// : an unregister repeated + /// after it already ran (a retried request, or a second Finish after a + /// lost response) gets HTTP 404 not_registered, and counting that + /// as an error would keep the logs and fail every later attempt the same + /// way. The code is checked as well as the status so that a 404 for a + /// missing route (rest_no_route) or meeting is still an error. + /// + private static bool IsNotRegisteredError(ApiResponse response) where T : class => + response.StatusCode == 404 + && string.Equals(response.Error?.Code, "not_registered", StringComparison.Ordinal); + /// /// Formats every diagnostic field on an into a /// single string for inclusion in a failure log line. Surfaces the HTTP diff --git a/TheBleedingDeacons.Intergroup.Register.Specs/Features/Reconciliation.feature b/TheBleedingDeacons.Intergroup.Register.Specs/Features/Reconciliation.feature index 876f469..6bedca4 100644 --- a/TheBleedingDeacons.Intergroup.Register.Specs/Features/Reconciliation.feature +++ b/TheBleedingDeacons.Intergroup.Register.Specs/Features/Reconciliation.feature @@ -45,6 +45,16 @@ Feature: Finishing the meeting When the meeting is finished Then Unity is told "Wednesday Steps" is no longer attending + Scenario: Unity no longer having a registration to withdraw is not a failure + Given the group "Wednesday Steps", already registered when the meeting started + And "Wil G" is a GSR of "Wednesday Steps" + And the meeting has started + And "Wednesday Steps" has been unregistered + And Unity has no registration to withdraw for groups + When the meeting is finished + Then the meeting finished with 0 errors and 0 warnings + And both logs are cleared + Scenario: Unity already having the registration is not a failure Given "Monday Step" has been registered And Unity already has registrations of groups @@ -68,7 +78,9 @@ Feature: Finishing the meeting A member added on the tablet has a temporary negative id that Unity has never seen. They are created before anything else is sent, and what - follows uses the id Unity gives them. + follows uses the id Unity gives them. Each create carries a reference + the tablet chose for that member, the same on every attempt, so a + create Unity has already carried out is never carried out twice. Scenario: A new GSR is created, and their group registered under the id Unity gave them Given the group "Friday Newcomers" @@ -90,6 +102,28 @@ Feature: Finishing the meeting And the meeting finished with 1 error and 0 warnings And the logs are kept for next time + Scenario: A create whose reply is lost is not made twice + Given the group "Friday Newcomers" + And the meeting has started + And "Fay H" is added at the meeting as a GSR of "Friday Newcomers" + And "Friday Newcomers" has been registered + And Unity creates new members but the first reply is lost + When the meeting is finished + Then Unity has one member called "Fay H" + And Unity is told "Friday Newcomers" attended, represented by member 900 + And the meeting finished with 0 errors and 0 warnings + + Scenario: A new member Unity would not create is sent under the same reference next time + Given the group "Friday Newcomers" + And the meeting has started + And "Fay H" is added at the meeting as a GSR of "Friday Newcomers" + And Unity refuses new members + When the meeting is finished + And Unity accepts new members again + And the meeting is finished + Then every request to create "Fay H" carried the same reference + And Unity has one member called "Fay H" + Rule: Only what changed is sent Scenario: A changed phone number is sent on its own diff --git a/TheBleedingDeacons.Intergroup.Register.Specs/Steps/MeetingSteps.cs b/TheBleedingDeacons.Intergroup.Register.Specs/Steps/MeetingSteps.cs index dcf617e..338dac6 100644 --- a/TheBleedingDeacons.Intergroup.Register.Specs/Steps/MeetingSteps.cs +++ b/TheBleedingDeacons.Intergroup.Register.Specs/Steps/MeetingSteps.cs @@ -37,6 +37,18 @@ public void Unity(string how, string what) => ? (HttpStatusCode.UnprocessableEntity, "rest_invalid_param") : (HttpStatusCode.Conflict, "already_registered"); + [Given(@"^Unity accepts new members again$")] + [When(@"^Unity accepts new members again$")] + public void AcceptsNewMembers() => world.Unity.Refusals.Remove(Routes["new members"]); + + [Given(@"^Unity creates new members but the first reply is lost$")] + public void LosesFirstCreateReply() => world.Unity.LoseCreateReplies = 1; + + [Given(@"^Unity has no registration to withdraw for (groups|officers)$")] + public void NothingToWithdraw(string what) => + world.Unity.Refusals[what == "groups" ? "/unregister-group" : "/unregister-officer"] = + (HttpStatusCode.NotFound, "not_registered"); + [When(@"^""([^""]*)""'s mobile number is changed to ""([^""]*)""$")] public void MobileChanged(string name, string mobile) => world.Change(db => db.Members.Find(world.MemberId(name))!.MobileNumber = mobile); @@ -79,8 +91,28 @@ public void OfficerAttended(string member, string position) } [Then(@"^Unity is asked to create ""([^""]*)""$")] - public void AskedToCreate(string name) => - world.Unity.Posts("/members/create").ShouldHaveSingleItem().Str("anonymous_name").ShouldBe(name); + public void AskedToCreate(string name) + { + var call = world.Unity.Posts("/members/create").ShouldHaveSingleItem(); + call.Str("anonymous_name").ShouldBe(name); + Guid.TryParse(call.Str("client_reference"), out var reference).ShouldBeTrue(); + reference.ShouldNotBe(Guid.Empty); + } + + [Then(@"^every request to create ""([^""]*)"" carried the same reference$")] + public void SameReference(string name) + { + var references = world.Unity.Posts("/members/create") + .Where(c => c.Str("anonymous_name") == name) + .Select(c => c.Str("client_reference")) + .ToList(); + references.Count.ShouldBeGreaterThan(1); + references.Distinct(StringComparer.Ordinal).ShouldHaveSingleItem().ShouldNotBeNullOrEmpty(); + } + + [Then(@"^Unity has one member called ""([^""]*)""$")] + public void OneMemberCalled(string name) => + world.Unity.Members.Count(m => m.AnonymousName == name).ShouldBe(1); [Then(@"^Unity is not told about ""([^""]*)""$")] public void NotTold(string group) diff --git a/TheBleedingDeacons.Intergroup.Register.Specs/Support/FakeUnity.cs b/TheBleedingDeacons.Intergroup.Register.Specs/Support/FakeUnity.cs index 67fe1a1..987eb8c 100644 --- a/TheBleedingDeacons.Intergroup.Register.Specs/Support/FakeUnity.cs +++ b/TheBleedingDeacons.Intergroup.Register.Specs/Support/FakeUnity.cs @@ -55,6 +55,15 @@ public sealed partial class FakeUnity : HttpMessageHandler /// The id the next created member is given. public int NextMemberId { get; set; } = 900; + /// + /// How many creates to carry out and then answer with a 502, as a + /// proxy does when the site's reply is lost on the way back. + /// + public int LoseCreateReplies { get; set; } + + /// Members created under each client reference, as Integrity records them. + private Dictionary CreatedByReference { get; } = []; + public int PageSize { get; set; } = 500; public IEnumerable Posts(string suffix) => @@ -92,8 +101,26 @@ protected override async Task SendAsync(HttpRequestMessage if (route == "members/create") { var created = JsonSerializer.Deserialize(body!, Json)!; + + // A repeat of a create Integrity has seen returns that member. + if (created.ClientReference is { } seen && CreatedByReference.TryGetValue(seen, out var existing)) + { + return Ok(existing); + } + var member = new UnityModels.Member { Id = NextMemberId++, AnonymousName = created.AnonymousName }; Members.Add(member); + if (created.ClientReference is { } reference) + { + CreatedByReference[reference] = member; + } + + if (LoseCreateReplies > 0) + { + LoseCreateReplies--; + return Error(HttpStatusCode.BadGateway, "bad_gateway"); + } + return Ok(member); } diff --git a/TheBleedingDeacons.Intergroup.Register/ViewModels/EditGroupViewModel.cs b/TheBleedingDeacons.Intergroup.Register/ViewModels/EditGroupViewModel.cs index 86052ed..683c97e 100644 --- a/TheBleedingDeacons.Intergroup.Register/ViewModels/EditGroupViewModel.cs +++ b/TheBleedingDeacons.Intergroup.Register/ViewModels/EditGroupViewModel.cs @@ -402,6 +402,9 @@ private async Task SaveMember() var newMember = new Member { Id = TemporaryIdGenerator.Next(), + // Fixed now, so every attempt to create this member on + // Unity names the same create and a retry can't duplicate it. + ClientReference = Guid.NewGuid(), HomeGroupId = _group.Id, AnonymousName = EditName?.Trim() ?? string.Empty, MobileNumber = EditPhone?.Trim(), diff --git a/TheBleedingDeacons.Intergroup.Register/ViewModels/PositionEditViewModel.cs b/TheBleedingDeacons.Intergroup.Register/ViewModels/PositionEditViewModel.cs index fa91fc3..2bb9034 100644 --- a/TheBleedingDeacons.Intergroup.Register/ViewModels/PositionEditViewModel.cs +++ b/TheBleedingDeacons.Intergroup.Register/ViewModels/PositionEditViewModel.cs @@ -464,6 +464,9 @@ private async Task SaveMember() var newMember = new Member { Id = TemporaryIdGenerator.Next(), + // Fixed now, so every attempt to create this member on + // Unity names the same create and a retry can't duplicate it. + ClientReference = Guid.NewGuid(), IntergroupPositionId = _position.Id, AnonymousName = EditName?.Trim() ?? string.Empty, MobileNumber = EditPhone?.Trim(), diff --git a/TheBleedingDeacons.Unity.Intergroup/Data/Configurations/MemberConfiguration.cs b/TheBleedingDeacons.Unity.Intergroup/Data/Configurations/MemberConfiguration.cs index aacc471..27995fd 100644 --- a/TheBleedingDeacons.Unity.Intergroup/Data/Configurations/MemberConfiguration.cs +++ b/TheBleedingDeacons.Unity.Intergroup/Data/Configurations/MemberConfiguration.cs @@ -59,6 +59,9 @@ public void Configure(EntityTypeBuilder builder) // the other GDPR fields and shows up in EF model snapshots. builder.Property(m => m.GdprAcceptancePolicyId); + // Set only on members created on the tablet; see Member.ClientReference. + builder.Property(m => m.ClientReference); + // HomeGroup FK is configured from GroupConfiguration (WithOne → HasForeignKey) // Many-to-one: multiple members can hold the same position diff --git a/TheBleedingDeacons.Unity.Intergroup/Entities/Member.cs b/TheBleedingDeacons.Unity.Intergroup/Entities/Member.cs index 1a84b2f..b6373f5 100644 --- a/TheBleedingDeacons.Unity.Intergroup/Entities/Member.cs +++ b/TheBleedingDeacons.Unity.Intergroup/Entities/Member.cs @@ -75,6 +75,16 @@ public class Member /// public int? GdprAcceptancePolicyId { get; set; } + /// + /// A reference this tablet gave a member it created locally, sent with + /// the create so that Unity can recognise a repeat of it. A create that + /// is retried — on its own, inside a retried batch, or by a second + /// Finish after a response that never arrived — returns the member made + /// the first time instead of a duplicate. Null for members synced from + /// Unity, which already exist there. + /// + public Guid? ClientReference { get; set; } + // FK to the member's home group (nullable — some members may not have a home group) public int? HomeGroupId { get; set; } public Group? HomeGroup { get; set; } diff --git a/TheBleedingDeacons.Unity.Intergroup/TheBleedingDeacons.Unity.Intergroup.csproj b/TheBleedingDeacons.Unity.Intergroup/TheBleedingDeacons.Unity.Intergroup.csproj index 554c99e..a7b394c 100644 --- a/TheBleedingDeacons.Unity.Intergroup/TheBleedingDeacons.Unity.Intergroup.csproj +++ b/TheBleedingDeacons.Unity.Intergroup/TheBleedingDeacons.Unity.Intergroup.csproj @@ -67,7 +67,7 @@ - +