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 'Chat Room' sample #8126

Merged
merged 3 commits into from
Nov 17, 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
12 changes: 7 additions & 5 deletions samples/ChatRoom/ChatRoom.Client/ChatRoom.Client.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
Expand All @@ -17,10 +17,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Orleans.Client" Version="3.6.0" />
<PackageReference Include="Spectre.Console" Version="0.43.0" />
<PackageReference Include="Spectre.Console.ImageSharp" Version="0.43.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.Streaming" Version="7.0.0" />
<PackageReference Include="Spectre.Console" Version="0.45.0" />
<PackageReference Include="Spectre.Console.ImageSharp" Version="0.45.0" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 0 additions & 2 deletions samples/ChatRoom/ChatRoom.Client/ClientContext.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Orleans;

internal readonly record struct ClientContext(
IClusterClient Client,
string? UserName = null,
Expand Down
75 changes: 37 additions & 38 deletions samples/ChatRoom/ChatRoom.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,42 +1,38 @@
using System.Reflection;
using ChatRoom;
using Orleans;
using Orleans.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Orleans.Runtime;
using Spectre.Console;

var client = new ClientBuilder()
.UseLocalhostClustering()
.ConfigureApplicationParts(
parts => parts.AddApplicationPart(typeof(IChannelGrain).Assembly).WithReferences())
.AddSimpleMessageStreamProvider("chat")
using var host = new HostBuilder()
.UseOrleansClient(clientBuilder =>
{
clientBuilder.UseLocalhostClustering()
.AddMemoryStreams("chat");
})
.Build();

PrintUsage();

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

ClientContext context = new(client);
await StartAsync(context);
await StartAsync(host);
context = context with
{
UserName = AnsiConsole.Ask<string>("What is your [aqua]name[/]?")
};
await ProcessLoopAsync(context);
await StopAsync(context);
await StopAsync(host);

static Task StartAsync(ClientContext context) =>
static Task StartAsync(IHost host) =>
AnsiConsole.Status().StartAsync("Connecting to server", async ctx =>
{
ctx.Spinner(Spinner.Known.Dots);
ctx.Status = "Connecting...";

await context.Client.Connect(async error =>
{
AnsiConsole.MarkupLine("[bold red]Error:[/] error connecting to server!");
AnsiConsole.WriteException(error);
ctx.Status = "Waiting to retry...";
await Task.Delay(TimeSpan.FromSeconds(2));
ctx.Status = "Retrying connection...";
return true;
});
await host.StartAsync();

ctx.Status = "Connected!";
});
Expand Down Expand Up @@ -68,22 +64,22 @@ static async Task ProcessLoopAsync(ClientContext context)
}

if (firstTwoCharacters switch
{
"/j" => JoinChannel(context, input.Replace("/j", "").Trim()),
"/l" => LeaveChannel(context),
_ => null
} is Task<ClientContext> cxtTask)
{
"/j" => JoinChannel(context, input.Replace("/j", "").Trim()),
"/l" => LeaveChannel(context),
_ => null
} is Task<ClientContext> cxtTask)
{
context = await cxtTask;
continue;
}

if (firstTwoCharacters switch
{
"/h" => ShowCurrentChannelHistory(context),
"/m" => ShowChannelMembers(context),
_ => null
} is Task task)
{
"/h" => ShowCurrentChannelHistory(context),
"/m" => ShowChannelMembers(context),
_ => null
} is Task task)
{
await task;
continue;
Expand All @@ -93,11 +89,11 @@ static async Task ProcessLoopAsync(ClientContext context)
} while (input is not "/exit");
}

static Task StopAsync(ClientContext context) =>
static Task StopAsync(IHost host) =>
AnsiConsole.Status().StartAsync("Disconnecting...", async ctx =>
{
ctx.Spinner(Spinner.Known.Dots);
await context.Client.Close();
await host.StopAsync();
});

static void PrintUsage()
Expand Down Expand Up @@ -225,13 +221,14 @@ static async Task<ClientContext> JoinChannel(
await AnsiConsole.Status().StartAsync("Joining channel...", async ctx =>
{
var room = context.Client.GetGrain<IChannelGrain>(context.CurrentChannel);
var streamId = await room.Join(context.UserName!);
await room.Join(context.UserName!);
var streamId = StreamId.Create("ChatRoom", context.CurrentChannel!);
var stream =
context.Client
.GetStreamProvider("chat")
.GetStream<ChatMsg>(streamId, "default");
.GetStream<ChatMsg>(streamId);

//subscribe to the stream to receive furthur messages sent to the chatroom
// Subscribe to the stream to receive furthur messages sent to the chatroom
await stream.SubscribeAsync(new StreamObserver(channelName));
});
AnsiConsole.MarkupLine("[bold aqua]Joined channel [/]{0}", context.CurrentChannel!);
Expand All @@ -247,14 +244,15 @@ static async Task<ClientContext> LeaveChannel(ClientContext context)
await AnsiConsole.Status().StartAsync("Leaving channel...", async ctx =>
{
var room = context.Client.GetGrain<IChannelGrain>(context.CurrentChannel);
var streamId = await room.Leave(context.UserName!);
await room.Leave(context.UserName!);
var streamId = StreamId.Create("ChatRoom", context.CurrentChannel!);
var stream =
context.Client
.GetStreamProvider("chat")
.GetStream<ChatMsg>(streamId, "default");
.GetStream<ChatMsg>(streamId);

//unsubscribe from the channel/stream since client left, so that client won't
//receive future messages from this channel/stream
// Unsubscribe from the channel/stream since client left, so that client won't
// receive future messages from this channel/stream.
var subscriptionHandles = await stream.GetAllSubscriptionHandles();
foreach (var handle in subscriptionHandles)
{
Expand All @@ -263,5 +261,6 @@ await AnsiConsole.Status().StartAsync("Leaving channel...", async ctx =>
});

AnsiConsole.MarkupLine("[bold olive]Left channel [/]{0}", context.CurrentChannel!);

return context with { CurrentChannel = null };
}
2 changes: 1 addition & 1 deletion samples/ChatRoom/ChatRoom.Client/StreamObserver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace ChatRoom;

public class StreamObserver : IAsyncObserver<ChatMsg>
public sealed class StreamObserver : IAsyncObserver<ChatMsg>
{
private readonly string _roomName;

Expand Down
10 changes: 7 additions & 3 deletions samples/ChatRoom/ChatRoom.Common/ChatMsg.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
namespace ChatRoom;

[Serializable]
public record class ChatMsg(string? Author, string Text)
[GenerateSerializer]
public record class ChatMsg(
string? Author,
string Text)
{
[Id(2)]
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
public string Author { get; init; } = Author ?? "Alexey";

public DateTimeOffset Created { get; init; } = DateTimeOffset.Now;
[Id(3)]
public DateTimeOffset Created { get; init; } = DateTimeOffset.Now;
}
11 changes: 4 additions & 7 deletions samples/ChatRoom/ChatRoom.Common/ChatRoom.Common.csproj
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<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</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Orleans.Sdk" Version="7.0.0" />
<PackageReference Include="Microsoft.Orleans.Streaming" Version="7.0.0" />
</ItemGroup>

</Project>
6 changes: 3 additions & 3 deletions samples/ChatRoom/ChatRoom.Common/IChannelGrain.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using Orleans;
using Orleans.Runtime;

namespace ChatRoom;

public interface IChannelGrain : IGrainWithStringKey
{
Task<Guid> Join(string nickname);
Task<Guid> Leave(string nickname);
Task<StreamId> Join(string nickname);
Task<StreamId> Leave(string nickname);
Task<bool> Message(ChatMsg msg);
Task<ChatMsg[]> ReadHistory(int numberOfMessages);
Task<string[]> GetMembers();
Expand Down
21 changes: 12 additions & 9 deletions samples/ChatRoom/ChatRoom.Service/ChannelGrain.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;

namespace ChatRoom;
Expand All @@ -10,17 +10,20 @@ public class ChannelGrain : Grain, IChannelGrain

private IAsyncStream<ChatMsg> _stream = null!;

public override Task OnActivateAsync()
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
var streamProvider = GetStreamProvider("chat");
var streamProvider = this.GetStreamProvider("chat");

var streamId = StreamId.Create(
"ChatRoom", this.GetPrimaryKeyString());

_stream = streamProvider.GetStream<ChatMsg>(
Guid.NewGuid(), "default");
streamId);

return base.OnActivateAsync();
return base.OnActivateAsync(cancellationToken);
}

public async Task<Guid> Join(string nickname)
public async Task<StreamId> Join(string nickname)
{
_onlineMembers.Add(nickname);

Expand All @@ -29,10 +32,10 @@ await _stream.OnNextAsync(
"System",
$"{nickname} joins the chat '{this.GetPrimaryKeyString()}' ..."));

return _stream.Guid;
return _stream.StreamId;
}

public async Task<Guid> Leave(string nickname)
public async Task<StreamId> Leave(string nickname)
{
_onlineMembers.Remove(nickname);

Expand All @@ -41,7 +44,7 @@ await _stream.OnNextAsync(
"System",
$"{nickname} leaves the chat..."));

return _stream.Guid;
return _stream.StreamId;
}

public async Task<bool> Message(ChatMsg msg)
Expand Down
13 changes: 5 additions & 8 deletions samples/ChatRoom/ChatRoom.Service/ChatRoom.Service.csproj
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<ServerGarbageCollection>true</ServerGarbageCollection>
</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.CodeGenerator.MSBuild" Version="3.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<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.Streaming" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
7 changes: 1 addition & 6 deletions samples/ChatRoom/ChatRoom.Service/Program.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
using Microsoft.Extensions.Hosting;
using Orleans;
using Orleans.Hosting;

await Host.CreateDefaultBuilder(args)
.UseOrleans(siloBuilder =>
{
siloBuilder
.UseLocalhostClustering()
.AddMemoryGrainStorage("PubSubStore")
.AddSimpleMessageStreamProvider("chat", options =>
{
options.FireAndForgetDelivery = true;
});
.AddMemoryStreams("chat");
})
.RunConsoleAsync();