-
Notifications
You must be signed in to change notification settings - Fork 4
/
MessagesController.cs
92 lines (70 loc) · 2.45 KB
/
MessagesController.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Orleans;
namespace MessageApp
{
[ApiController]
[Route("messages")]
public class MessagesController : ControllerBase
{
private readonly IClusterClient _client;
private readonly ILogger<MessagesController> _log;
public MessagesController(IClusterClient client, ILogger<MessagesController> log)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}
if (log == null)
{
throw new ArgumentNullException(nameof(log));
}
_client = client;
_log = log;
}
[HttpGet]
[Route("{actorId}")]
public async Task<string[]> GetMessages(long actorId)
{
Debug.Assert(_log != null);
_log.LogInformation("Getting messages");
Debug.Assert(_client != null);
var actor = GetActor(actorId);
Debug.Assert(actor != null);
var messages = await actor.GetMessages().ConfigureAwait(false);
if (messages == null)
{
throw new InvalidOperationException("Actor failed to return valid list of messages.");
}
return messages.ToArray();
}
[HttpPost]
[Route("{actorId}")]
public async Task AddMessage(long actorId, [FromBody] string message)
{
if (string.IsNullOrWhiteSpace(message))
{
throw new ArgumentException("'Message' argument is not valid.");
}
Debug.Assert(_log != null);
_log.LogInformation("Adding a message");
var actor = GetActor(actorId);
Debug.Assert(actor != null);
await actor.AddMessage(message).ConfigureAwait(false);
}
private IMessageActor GetActor(long actorId)
{
Debug.Assert(_client != null);
var actor = _client.GetGrain<IMessageActor>(actorId);
if (actor == null)
{
throw new InvalidOperationException("Orleans runtime failed to return valid actor instance.");
}
return actor;
}
}
}