-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMessageServer.cs
228 lines (196 loc) · 7.85 KB
/
MessageServer.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
namespace Menees.Remoting;
#region Using Directives
using Menees.Remoting.Models;
using Menees.Remoting.Pipes;
using Microsoft.Extensions.Logging;
#endregion
/// <summary>
/// Used to receive a <typeparamref name="TIn"/> request from a <see cref="MessageClient{TIn, TOut}"/>
/// process it, and send a <typeparamref name="TOut"/> response.
/// </summary>
/// <typeparam name="TIn">The request message type.</typeparam>
/// <typeparam name="TOut">The response message type.</typeparam>
public sealed class MessageServer<TIn, TOut> : MessageNode<TIn, TOut>, IServer
{
#region Private Data Members
private readonly PipeServer pipe;
private readonly CancellationToken cancellationToken;
private readonly CancellationTokenSource? cancellationTokenSource;
private Func<TIn, CancellationToken, Task<TOut>>? requestHandler;
#endregion
#region Constructors
/// <summary>
/// Creates a new server instance to expose a <typeparamref name="TIn"/> to <typeparamref name="TOut"/>
/// <paramref name="requestHandler"/> implementation to <see cref="MessageClient{TIn, TOut}"/> instances.
/// </summary>
/// <param name="requestHandler">A custom handler to process a <typeparamref name="TIn"/> request message
/// and return a <typeparamref name="TOut"/> response message.
/// </param>
/// <param name="serverPath">The path used to expose the service.</param>
/// <param name="maxListeners">The maximum number of server listener tasks to start.</param>
/// <param name="minListeners">The minimum number of server listener tasks to start.</param>
/// <param name="loggerFactory">An optional factory for creating type-specific server loggers for status information.</param>
public MessageServer(
Func<TIn, Task<TOut>> requestHandler,
string serverPath,
int maxListeners = ServerSettings.MaxAllowedListeners,
int minListeners = 1,
ILoggerFactory? loggerFactory = null)
: this(
requestHandler != null ? (request, _) => requestHandler(request) : throw new ArgumentNullException(nameof(requestHandler)),
serverPath,
maxListeners,
minListeners,
loggerFactory)
{
}
/// <summary>
/// Creates a new server instance to expose a <typeparamref name="TIn"/> to <typeparamref name="TOut"/>
/// <paramref name="requestHandler"/> implementation to <see cref="MessageClient{TIn, TOut}"/> instances.
/// </summary>
/// <param name="requestHandler">A custom handler to process a <typeparamref name="TIn"/> request message
/// and return a <typeparamref name="TOut"/> response message.
/// </param>
/// <param name="serverPath">The path used to expose the service.</param>
/// <param name="maxListeners">The maximum number of server listener tasks to start.</param>
/// <param name="minListeners">The minimum number of server listener tasks to start.</param>
/// <param name="loggerFactory">An optional factory for creating type-specific server loggers for status information.</param>
public MessageServer(
Func<TIn, CancellationToken, Task<TOut>> requestHandler,
string serverPath,
int maxListeners = ServerSettings.MaxAllowedListeners,
int minListeners = 1,
ILoggerFactory? loggerFactory = null)
: this(requestHandler, new ServerSettings(serverPath)
{
MaxListeners = maxListeners,
MinListeners = minListeners,
CreateLogger = loggerFactory != null ? loggerFactory.CreateLogger : null,
})
{
}
/// <summary>
/// Creates a new server instance to expose a <typeparamref name="TIn"/> to <typeparamref name="TOut"/>
/// <paramref name="requestHandler"/> implementation to <see cref="MessageClient{TIn, TOut}"/> instances.
/// </summary>
/// <param name="requestHandler">A custom handler to process a <typeparamref name="TIn"/> request message
/// and return a <typeparamref name="TOut"/> response message.
/// </param>
/// <param name="settings">Parameters used to initialize this instance.</param>
public MessageServer(Func<TIn, Task<TOut>> requestHandler, ServerSettings settings)
: this(
requestHandler != null ? (request, _) => requestHandler(request) : throw new ArgumentNullException(nameof(requestHandler)),
settings)
{
}
/// <summary>
/// Creates a new server instance to expose a <typeparamref name="TIn"/> to <typeparamref name="TOut"/>
/// <paramref name="requestHandler"/> implementation to <see cref="MessageClient{TIn, TOut}"/> instances.
/// </summary>
/// <param name="requestHandler">A custom handler to process a <typeparamref name="TIn"/> request message
/// and return a <typeparamref name="TOut"/> response message.
/// </param>
/// <param name="settings">Parameters used to initialize this instance.</param>
public MessageServer(Func<TIn, CancellationToken, Task<TOut>> requestHandler, ServerSettings settings)
: base(settings)
{
ArgumentNullException.ThrowIfNull(settings);
this.requestHandler = requestHandler ?? throw new ArgumentNullException(nameof(requestHandler));
// Note: The pipe is created with no listeners until we explicitly start them.
this.pipe = new(
settings.ServerPath,
settings.MinListeners,
settings.MaxListeners,
this.ProcessRequestAsync,
this,
this,
(PipeServerSecurity?)settings.Security);
if (settings.CancellationToken != CancellationToken.None)
{
this.cancellationToken = settings.CancellationToken;
}
else
{
// Make our own source so our Dispose method can signal cancellation during dispose.
// This is nice for notifying executing request handlers before we close the pipe out
// from under them. If the caller passed in a cancelable token, then we'll assume they're
// taking care of canceling before disposing the server instance.
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
}
}
#endregion
#region Public Events
/// <inheritdoc/>
public event EventHandler? Stopped
{
add => this.pipe.Stopped += value;
remove => this.pipe.Stopped -= value;
}
#endregion
#region Public Properties
/// <inheritdoc/>
public Action<Exception>? ReportUnhandledException
{
get => this.pipe.ReportUnhandledException;
set => this.pipe.ReportUnhandledException = value;
}
#endregion
#region Public Methods
/// <inheritdoc/>
public void Start() => this.pipe.EnsureMinListeners();
/// <inheritdoc/>
public void Stop() => this.pipe.StopListening();
#endregion
#region Protected Methods
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.requestHandler = null;
this.cancellationTokenSource?.Cancel();
this.cancellationTokenSource?.Dispose();
this.pipe.Dispose();
}
}
#endregion
#region Private Methods
private async Task ProcessRequestAsync(Stream clientStream)
{
await ServerUtility.ProcessRequestAsync(
this,
this,
clientStream,
async (request, cancellation) =>
{
Response response;
Func<TIn, CancellationToken, Task<TOut>>? requestHandler = this.requestHandler;
if (request.MethodSignature != null)
{
response = ServerUtility.CreateResponse(new ArgumentException("A message request should not specify a method signature."));
}
else if (request.Arguments?.Count != 1)
{
response = ServerUtility.CreateResponse(new ArgumentException("A single input message is required."));
}
else if (request.Arguments[0].DeserializeValue(this.UserSerializer) is not TIn inputMessage)
{
response = ServerUtility.CreateResponse(new ArgumentException($"The input message must be of type {typeof(TIn)}."));
}
else if (requestHandler == null)
{
response = ServerUtility.CreateResponse(new ObjectDisposedException(this.GetType().FullName));
}
else
{
TOut outputMessage = await requestHandler(inputMessage, cancellation).ConfigureAwait(false);
response = new Response { Result = new UserSerializedValue(typeof(TOut), outputMessage, this.UserSerializer) };
}
return response;
},
this.cancellationToken).ConfigureAwait(false);
}
#endregion
}