Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade 'Bank Account' sample #8119

Merged
merged 4 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 9 additions & 7 deletions samples/BankAccount/AccountTransfer.Grains/AccountGrain.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
using AccountTransfer.Interfaces;
using Orleans;
using Orleans.Concurrency;
using Orleans.Transactions.Abstractions;

namespace AccountTransfer.Grains;

[Serializable]
[GenerateSerializer]
public record class Balance
{
public uint Value { get; set; } = 1_000;
[Id(0)]
public int Value { get; set; } = 1_000;
}

public class AccountGrain : Grain, IAccountGrain
[Reentrant]
public sealed class AccountGrain : Grain, IAccountGrain
{
private readonly ITransactionalState<Balance> _balance;

public AccountGrain(
[TransactionalState("balance")] ITransactionalState<Balance> balance) =>
_balance = balance ?? throw new ArgumentNullException(nameof(balance));

public Task Deposit(uint amount) =>
public Task Deposit(int amount) =>
_balance.PerformUpdate(
balance => balance.Value += amount);

public Task Withdraw(uint amount) =>
public Task Withdraw(int amount) =>
_balance.PerformUpdate(balance =>
{
if (balance.Value < amount)
Expand All @@ -36,6 +38,6 @@ public Task Withdraw(uint amount) =>
balance.Value -= amount;
});

public Task<uint> GetBalance() =>
public Task<int> GetBalance() =>
_balance.PerformRead(balance => balance.Value);
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Orleans.Core.Abstractions" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.CodeGenerator.MSBuild" Version="3.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Orleans.Transactions" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AccountTransfer.Interfaces\AccountTransfer.Interfaces.csproj" />
Expand Down
3 changes: 1 addition & 2 deletions samples/BankAccount/AccountTransfer.Grains/AtmGrain.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using AccountTransfer.Interfaces;
using Orleans;
using Orleans.Concurrency;

namespace AccountTransfer.Grains;
Expand All @@ -10,7 +9,7 @@ public class AtmGrain : Grain, IAtmGrain
public Task Transfer(
IAccountGrain fromAccount,
IAccountGrain toAccount,
uint amountToTransfer) =>
int amountToTransfer) =>
Task.WhenAll(
fromAccount.Withdraw(amountToTransfer),
toAccount.Deposit(amountToTransfer));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Orleans.Core.Abstractions" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.CodeGenerator.MSBuild" Version="3.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Orleans.Transactions" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.0.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
using Orleans;

namespace AccountTransfer.Interfaces;

public interface IAccountGrain : IGrainWithStringKey
{
[Transaction(TransactionOption.Join)]
Task Withdraw(uint amount);
Task Withdraw(int amount);

[Transaction(TransactionOption.Join)]
Task Deposit(uint amount);
Task Deposit(int amount);

[Transaction(TransactionOption.CreateOrJoin)]
Task<uint> GetBalance();
Task<int> GetBalance();
}
4 changes: 1 addition & 3 deletions samples/BankAccount/AccountTransfer.Interfaces/IAtmGrain.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Orleans;

namespace AccountTransfer.Interfaces;

public interface IAtmGrain : IGrainWithIntegerKey
Expand All @@ -8,5 +6,5 @@ public interface IAtmGrain : IGrainWithIntegerKey
Task Transfer(
IAccountGrain fromAccount,
IAccountGrain toAccount,
uint amountToTransfer);
int amountToTransfer);
}
9 changes: 5 additions & 4 deletions samples/BankAccount/BankClient/BankClient.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Orleans.Core" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="3.6.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Client" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
60 changes: 36 additions & 24 deletions samples/BankAccount/BankClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,64 @@
using AccountTransfer.Interfaces;
using Microsoft.Extensions.Logging;
using Orleans;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using var client = new ClientBuilder()
.UseLocalhostClustering()
.ConfigureLogging(logging => logging.AddConsole())
using IHost host = Host.CreateDefaultBuilder(args)
.UseOrleansClient(client =>
{
client.UseLocalhostClustering()
.UseTransactions();
})
.Build();

await client.Connect();
await host.StartAsync();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the host be stopped (explicitely) after the loop too?
More or less for completeness and to show good behavior.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you're right, it should

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, we should change this to use the host lifecycle (which should be the console lifecycle). I'll push an update.


var client = host.Services.GetRequiredService<IClusterClient>();
var transactionClient = host.Services.GetRequiredService<ITransactionClient>();

var accountNames = new[] { "Xaawo", "Pasqualino", "Derick", "Ida", "Stacy", "Xiao" };
var random = Random.Shared;

while (!Console.KeyAvailable)
{
var atm = client.GetGrain<IAtmGrain>(0);

// Choose some random accounts to exchange money
var fromId = random.Next(accountNames.Length);
var toId = random.Next(accountNames.Length);
while (toId == fromId)
var fromIndex = random.Next(accountNames.Length);
var toIndex = random.Next(accountNames.Length);
while (toIndex == fromIndex)
{
// Avoid transfering to/from the same account, since it would be meaningless
toId = (toId + 1) % accountNames.Length;
// Avoid transferring to/from the same account, since it would be meaningless
toIndex = (toIndex + 1) % accountNames.Length;
}

var fromName = accountNames[fromId];
var toName = accountNames[toId];
var from = client.GetGrain<IAccountGrain>(fromName);
var to = client.GetGrain<IAccountGrain>(toName);
var fromKey = accountNames[fromIndex];
var toKey = accountNames[toIndex];
var fromAccount = client.GetGrain<IAccountGrain>(fromKey);
var toAccount = client.GetGrain<IAccountGrain>(toKey);

// Perform the transfer and query the results
try
{
await atm.Transfer(from, to, 100);
var transferAmount = random.Next(200);

await transactionClient.RunTransaction(
TransactionOption.Create,
async () =>
{
await fromAccount.Withdraw(transferAmount);
await toAccount.Deposit(transferAmount);
});

var fromBalance = await from.GetBalance();
var toBalance = await to.GetBalance();
var fromBalance = await fromAccount.GetBalance();
var toBalance = await toAccount.GetBalance();

Console.WriteLine(
$"We transfered 100 credits from {fromName} to " +
$"{toName}.\n{fromName} balance: {fromBalance}\n{toName} balance: {toBalance}\n");
$"We transferred {transferAmount} credits from {fromKey} to " +
$"{toKey}.\n{fromKey} balance: {fromBalance}\n{toKey} balance: {toBalance}\n");
}
catch (Exception exception)
{
Console.WriteLine(
$"Error transfering 100 credits from "+
$"{fromName} to {toName}: {exception.Message}");
$"Error transferring credits from " +
$"{fromKey} to {toKey}: {exception.Message}");

if (exception.InnerException is { } inner)
{
Expand Down
11 changes: 5 additions & 6 deletions samples/BankAccount/BankServer/BankServer.csproj
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Orleans.Server" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.OrleansProviders" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="3.6.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Server" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 0 additions & 2 deletions samples/BankAccount/BankServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Microsoft.Extensions.Hosting;
using Orleans;
using Orleans.Hosting;

await Host.CreateDefaultBuilder()
.UseOrleans(siloBuilder =>
Expand Down