Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,30 @@ public async Task<ReconcileResult> 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)
{
Expand All @@ -224,10 +248,20 @@ public async Task<ReconcileResult> 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,
Expand Down Expand Up @@ -685,6 +719,12 @@ public async Task<ReconcileResult> 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++;
Expand Down Expand Up @@ -792,6 +832,11 @@ public async Task<ReconcileResult> 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++;
Expand Down Expand Up @@ -1037,6 +1082,20 @@ private static bool IsAlreadyRegisteredError<T>(ApiResponse<T> response) where T
|| msg.Contains("already registered", StringComparison.Ordinal) || msg.Contains("already exists", StringComparison.Ordinal);
}

/// <summary>
/// Returns true when an unregister call failed only because Unity holds
/// no registration to remove — the outcome the call was after. Mirrors
/// <see cref="IsAlreadyRegisteredError{T}"/>: an unregister repeated
/// after it already ran (a retried request, or a second Finish after a
/// lost response) gets HTTP 404 <c>not_registered</c>, 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 (<c>rest_no_route</c>) or meeting is still an error.
/// </summary>
private static bool IsNotRegisteredError<T>(ApiResponse<T> response) where T : class =>
response.StatusCode == 404
&& string.Equals(response.Error?.Code, "not_registered", StringComparison.Ordinal);

/// <summary>
/// Formats every diagnostic field on an <see cref="ApiResponse{T}"/> into a
/// single string for inclusion in a failure log line. Surfaces the HTTP
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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
Expand Down
36 changes: 34 additions & 2 deletions TheBleedingDeacons.Intergroup.Register.Specs/Steps/MeetingSteps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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)
Expand Down
27 changes: 27 additions & 0 deletions TheBleedingDeacons.Intergroup.Register.Specs/Support/FakeUnity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ public sealed partial class FakeUnity : HttpMessageHandler
/// <summary>The id the next created member is given.</summary>
public int NextMemberId { get; set; } = 900;

/// <summary>
/// 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.
/// </summary>
public int LoseCreateReplies { get; set; }

/// <summary>Members created under each client reference, as Integrity records them.</summary>
private Dictionary<Guid, UnityModels.Member> CreatedByReference { get; } = [];

public int PageSize { get; set; } = 500;

public IEnumerable<Call> Posts(string suffix) =>
Expand Down Expand Up @@ -92,8 +101,26 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
if (route == "members/create")
{
var created = JsonSerializer.Deserialize<UnityModels.CreateMemberRequest>(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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public void Configure(EntityTypeBuilder<Member> 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
Expand Down
10 changes: 10 additions & 0 deletions TheBleedingDeacons.Unity.Intergroup/Entities/Member.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ public class Member
/// </summary>
public int? GdprAcceptancePolicyId { get; set; }

/// <summary>
/// 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.
/// </summary>
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; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
<!-- One reference covers both assemblies: the Models types ship bundled
inside Integrity.Client rather than as a package of their own. -->
<ItemGroup Condition="'$(UseLocalIntegritySharp)' != 'true'">
<PackageReference Include="Integrity.Client" Version="1.10.3" />
<PackageReference Include="Integrity.Client" Version="1.12.0" />
</ItemGroup>

<!-- Both projects must be referenced in local mode. The client marks its own
Expand Down
9 changes: 9 additions & 0 deletions specs/domain-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ sync ─▶ snapshot ─▶ register / accept (local DB + fsync'd log) ─▶ fi
position, and per member. A replay rebuilds the database from them.
- **Temporary id**: a negative id given to a member added at the meeting.
Unity has never seen it, and replaces it on creation.
- **Client reference**: a UUID given to a member added at the meeting, and
sent with every attempt to create them. Unity recognises a create it has
already carried out and returns that member, so a retry after a lost reply
never makes a second one.
- **Reconcile / finishing the meeting**: sending Unity everything that differs
from the snapshot. The order is: new members, changed members, consent,
then attendance.
Expand All @@ -78,6 +82,11 @@ Unity hears about it when the meeting is finished, and receives only what
changed since the snapshot. A new member is created first, so that the
registrations that follow can use the id Unity gives them.

Everything sent at the finish is safe to send twice, because a request can
reach Unity and its reply still be lost. A create carries the member's
client reference; Unity already having a registration counts as registered,
and Unity having none to withdraw counts as withdrawn.

If Unity refuses to create a member, the registrations that depend on that
member are held back. They are not sent under the negative id, which Unity
would reject. The logs are kept, so the next attempt retries both.
Expand Down
Loading