Skip to content

Commit

Permalink
Ensure chatroom message history doesn't grow above 100
Browse files Browse the repository at this point in the history
  • Loading branch information
egil committed Jan 19, 2025
1 parent f315c29 commit 72e7385
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions orleans/ChatRoom/ChatRoom.Service/ChannelGrain.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.Streams;

namespace ChatRoom;

public class ChannelGrain : Grain, IChannelGrain
public sealed class ChannelGrain : Grain, IChannelGrain
{
private readonly List<ChatMsg> _messages = new(100);
private readonly List<string> _onlineMembers = new(10);
private readonly List<ChatMsg> _messages = [];
private readonly List<string> _onlineMembers = [];

private IAsyncStream<ChatMsg> _stream = null!;
// Initialized in OnActivateAsync that runs before
// other methods that uses _stream field can be invoked.
private IAsyncStream<ChatMsg> _stream = default!;

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

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

_stream = streamProvider.GetStream<ChatMsg>(
streamId);
_stream = streamProvider.GetStream<ChatMsg>(streamId);

return base.OnActivateAsync(cancellationToken);
}
Expand All @@ -29,8 +28,8 @@ public async Task<StreamId> Join(string nickname)

await _stream.OnNextAsync(
new ChatMsg(
"System",
$"{nickname} joins the chat '{this.GetPrimaryKeyString()}' ..."));
Author: "System",
Text: $"{nickname} joins the chat '{this.GetPrimaryKeyString()}' ..."));

return _stream.StreamId;
}
Expand All @@ -41,15 +40,17 @@ public async Task<StreamId> Leave(string nickname)

await _stream.OnNextAsync(
new ChatMsg(
"System",
$"{nickname} leaves the chat..."));
Author: "System",
Text: $"{nickname} leaves the chat..."));

return _stream.StreamId;
}

public async Task<bool> Message(ChatMsg msg)
{
_messages.Add(msg);
if (_messages.Count > 100)
_messages.RemoveAt(0);

await _stream.OnNextAsync(msg);

Expand Down

0 comments on commit 72e7385

Please sign in to comment.