-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathService.cs
57 lines (48 loc) · 1.92 KB
/
Service.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.Runtime.Serialization;
using MemoryPack;
namespace Samples.MiniRpc;
public interface IChat : IComputeService
{
[ComputeMethod]
Task<List<string>> GetRecentMessages(CancellationToken cancellationToken = default);
[ComputeMethod]
Task<int> GetWordCount(CancellationToken cancellationToken = default);
[CommandHandler]
Task Post(Chat_Post command, CancellationToken cancellationToken);
}
[DataContract, MemoryPackable(GenerateType.VersionTolerant)]
// ReSharper disable once InconsistentNaming
public partial record Chat_Post(
[property: DataMember, MemoryPackOrder(0)] string Message
) : ICommand<Unit>;
public class Chat : IChat
{
private readonly object _lock = new();
private List<string> _posts = new();
public virtual Task<List<string>> GetRecentMessages(CancellationToken cancellationToken = default)
=> Task.FromResult(_posts);
public virtual async Task<int> GetWordCount(CancellationToken cancellationToken = default)
{
// Note that GetRecentMessages call here becomes a dependency of WordCount call,
// and that's why it gets invalidated automatically.
var messages = await GetRecentMessages(cancellationToken).ConfigureAwait(false);
return messages
.Select(m => m.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length)
.Sum();
}
public virtual Task Post(Chat_Post command, CancellationToken cancellationToken)
{
if (Computed.IsInvalidating()) {
_ = GetRecentMessages(default); // No need to invalidate GetWordCount
return Task.CompletedTask;
}
lock (_lock) {
var posts = _posts.ToList(); // We can't update the list itself (it's shared), but can re-create it
posts.Add(command.Message);
if (posts.Count > 10)
posts.RemoveAt(0);
_posts = posts;
}
return Task.CompletedTask;
}
}