Skip to content
Open
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
48 changes: 35 additions & 13 deletions Shared/Cluster/ContractLedger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,13 @@ internal static class ContractLedger
private static readonly Dictionary<long, Unanswered> UnansweredSettlements = new();
private static double m_nextUnansweredRetry;

internal sealed record Acceptance(long Id, long Block, long BlockOwner, long Player);
internal sealed record Acceptance(
long Id,
long Block,
long BlockOwner,
long Player,
Guid Operation = default
);

internal sealed record Settlement(long Id, string Kind, long Player);

Expand All @@ -117,7 +123,8 @@ private sealed record Request(
bool PunishOwner = true,
long FirstOwner = 0,
long[] Owners = null,
bool ConditionFinished = false
bool ConditionFinished = false,
Guid AcceptanceOperation = default
);

private sealed record Result(bool Success, string Reason = null);
Expand Down Expand Up @@ -160,7 +167,7 @@ public static void Install()

// ---- seams, on the node running the vanilla code (game thread) ----

private static bool Accept(MyContract contract, long playerId)
private static bool Accept(MyContract contract, long playerId, Guid operation)
{
if (!ClusterRuntime.IsClustered || contract.Id <= 0)
return true;
Expand All @@ -174,7 +181,8 @@ private static bool Accept(MyContract contract, long playerId)
contract.Id,
contract.StartBlock,
blockOwner,
playerId
playerId,
operation
);
return true;
}
Expand All @@ -188,8 +196,10 @@ private static bool Accept(MyContract contract, long playerId)
Serialize(new[] { builder }),
playerId,
contract.StartBlock,
blockOwner
)
blockOwner,
AcceptanceOperation: operation
),
operation
);
if (result?.Success != true)
{
Expand All @@ -203,7 +213,7 @@ private static bool Accept(MyContract contract, long playerId)
);
// Unanswered, the World Authority may have taken it all the same.
if (result == null)
Send(new Request("Withdraw", contract.Id));
Send(new Request("Withdraw", contract.Id, AcceptanceOperation: operation));
// A stale offer: the block's entry stops carrying it at the next save (ContractOffers.Saving).
else if (result.Reason == AlreadySettled)
{
Expand All @@ -218,19 +228,23 @@ private static bool Accept(MyContract contract, long playerId)
return true;
}

private static void Withdraw(long contractId)
private static void Withdraw(long contractId, Guid operation)
{
if (!ClusterRuntime.IsClustered || contractId <= 0)
return;
if (ClusterRuntime.IsWorldAuthority)
{
lock (Sync)
Accepted.Remove(contractId);
if (
Accepted.TryGetValue(contractId, out var accepted)
&& accepted.Operation == operation
)
Accepted.Remove(contractId);
return;
}
lock (Sync)
AcceptedHere.Remove(contractId);
Send(new Request("Withdraw", contractId));
Send(new Request("Withdraw", contractId, AcceptanceOperation: operation));
}

private static bool TrySettle(MyContract contract, string kind, bool punishOwner)
Expand Down Expand Up @@ -485,7 +499,7 @@ request.Kind is not ("Finish" or "Fail")
Result result = request.Kind switch
{
"Accept" => AcceptHere(request),
"Withdraw" => WithdrawHere(request.ContractId),
"Withdraw" => WithdrawHere(request.ContractId, request.AcceptanceOperation),
"Update" => UpdateHere(request),
"Finish" or "Fail" => Settle(request, origin, ranHere: false),
"BlockGone" => BlockGoneHere(request.Block),
Expand Down Expand Up @@ -549,13 +563,21 @@ private static Result AcceptHere(Request request)
builder.Id,
request.Block,
request.BlockOwner,
request.Player
request.Player,
request.AcceptanceOperation
);
return new Result(true);
}

private static Result WithdrawHere(long contractId)
private static Result WithdrawHere(long contractId, Guid operation)
{
// Both the acceptance and its refusal may lose their replies. Only the winning attempt can undo it.
lock (Sync)
if (
!Accepted.TryGetValue(contractId, out var accepted)
|| accepted.Operation != operation
)
return new Result(false, "different acceptance");
MySessionComponentContractSystem system =
System ?? throw new InvalidOperationException("No contract system");
if (
Expand Down
4 changes: 2 additions & 2 deletions Shared/Cluster/Seams/MyContractSeams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public static class MyContractSeams
// Activate, after the deposit: the World Authority takes the contract into its ledger of accepted contracts
// (contract, accepting player). False refuses the activation. Withdraw (contract id) undoes it when Activate
// does not get as far as the commit.
public static Func<MyContract, long, bool> ClusterAccept;
public static Action<long> ClusterWithdraw;
public static Func<MyContract, long, Guid, bool> ClusterAccept;
public static Action<long, Guid> ClusterWithdraw;

// Finish/Fail: every node holding a copy of a contract could reach a terminal state on its own - a player
// finishing here while the World Authority's timeout fails it there - and each would settle the reward and
Expand Down
22 changes: 13 additions & 9 deletions Shared/Patches/MyContractPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public static class MyContractPatch
private static IDisposable s_deposit;

[ThreadStatic]
private static long s_accepted;
private static (long Contract, Guid Operation) s_accepted;

private static readonly MethodInfo CanActivateInternal = EconomyIl.Required(
AccessTools.Method(typeof(MyContract), "CanActivate_Internal"),
Expand Down Expand Up @@ -129,12 +129,12 @@ MethodBase original
private static void Finalizer()
{
IDisposable scope = s_deposit;
long accepted = s_accepted;
var accepted = s_accepted;
s_deposit = null;
s_accepted = 0;
s_accepted = default;
scope?.Dispose();
if (accepted != 0)
MyContractSeams.ClusterWithdraw?.Invoke(accepted);
if (accepted.Contract != 0)
MyContractSeams.ClusterWithdraw?.Invoke(accepted.Contract, accepted.Operation);
}
}

Expand Down Expand Up @@ -248,16 +248,20 @@ public static bool BeginDeposit(MyContract self, long playerId)
return false;
// A refused acceptance leaves the reserved deposit to the finalizer, which refunds it.
var accept = MyContractSeams.ClusterAccept;
if (accept != null && !accept(self, playerId))
return false;
s_accepted = self.Id;
if (accept != null)
{
Guid operation = Guid.NewGuid();
if (!accept(self, playerId, operation))
return false;
s_accepted = (self.Id, operation);
}
return true;
}

/// <summary>Called from the injected IL of Activate, right after Activate_Internal.</summary>
public static void CommitDeposit()
{
s_accepted = 0;
s_accepted = default;
IDisposable scope = s_deposit;
if (scope != null)
MyContractSeams.ClusterCommitDeposit?.Invoke(scope);
Expand Down
19 changes: 19 additions & 0 deletions Test/ClusterTestPlugin/Source/ContractTestRoutes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using ClusterPlugin;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Common.ObjectBuilders.Definitions;
using Sandbox.Definitions;
Expand Down Expand Up @@ -371,6 +373,23 @@ public static void Register()
);
}
);
TestRoutes.Add(
"POST",
"/contract-test-withdraw-other-attempt",
context =>
{
long contract = TestRoutes.Long(context, "contract");
string payload = JsonSerializer.Serialize(
new
{
Kind = "Withdraw",
ContractId = contract,
AcceptanceOperation = Guid.NewGuid(),
}
);
TestRoutes.Text(context, 200, GlobalStateChannel.SendCommand("contracts", payload));
}
);
// POST /contract-test-rpc?op=accept|finish|abandon&userId=&block=&contract= - the contract block's own server
// request handler for an attached player, as if the player's client had sent it (the client has no contract
// screen to drive headless). Finish names the player's character as the delivering entity.
Expand Down
10 changes: 10 additions & 0 deletions Test/scenarios_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,16 @@ def newest() -> int:
ledger.wa = "wa-2"
ledger.wait_listed("failover: after the World Authority failover every node and wa-2 list the contract", failover, acceptor, True)
away = _other(_all_partitions(bench).get(partition) or "node-1")
# A competing accept that lost both replies may try to undo the winner after failover.
rollback = ledger.node(
away, f"/contract-test-withdraw-other-attempt?contract={failover}", "POST"
)
_require(
bench,
"a different acceptance attempt cannot withdraw the winner after failover",
rollback.get("Success") is False,
json.dumps(rollback),
)
answer = ledger.node(away, f"/contract-test-abandon?contract={failover}&identity={acceptor}", "POST")
bench.record("abandon-after-failover", answer)
bench.check(f"failover: {away}, away from the block, abandoned the contract", answer.get("result") == "Success", json.dumps(answer))
Expand Down