Skip to content

Commit 1c7c56e

Browse files
committed
Merge branch 'develop'
2 parents 6f51819 + 9383c57 commit 1c7c56e

File tree

5 files changed

+29
-42
lines changed

5 files changed

+29
-42
lines changed

Common/Swagger/AttributeFilter.cs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
using Microsoft.AspNetCore.Authorization;
2-
using Microsoft.Net.Http.Headers;
3-
using Microsoft.OpenApi.Any;
42
using Microsoft.OpenApi.Models;
53
using OpenShock.Common.Authentication;
64
using OpenShock.Common.DataAnnotations.Interfaces;
@@ -36,15 +34,6 @@ public void Apply(OpenApiSchema schema, SchemaFilterContext context)
3634

3735
public void Apply(OpenApiOperation operation, OperationFilterContext context)
3836
{
39-
operation.Parameters.Add(new OpenApiParameter
40-
{
41-
Required = false,
42-
In = ParameterLocation.Header,
43-
Name = HeaderNames.UserAgent,
44-
AllowEmptyValue = false,
45-
Example = new OpenApiString("MyApiClient/1.0")
46-
});
47-
4837
// Apply OpenShock Parameter Attributes
4938
foreach (var attribute in context.MethodInfo?.GetCustomAttributes(true).OfType<IOperationAttribute>() ?? [])
5039
{

Common/Websocket/WebsockBaseController.cs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public abstract class WebsocketBaseController<T> : OpenShockControllerBase, IAsy
3434
private CancellationTokenSource? _linkedSource;
3535

3636
protected CancellationToken LinkedToken;
37-
37+
3838
/// <summary>
3939
/// Channel for multithreading thread safety of the websocket, MessageLoop is the only reader for this channel
4040
/// </summary>
@@ -53,7 +53,6 @@ protected WebsocketBaseController(ILogger<WebsocketBaseController<T>> logger)
5353
Logger = logger;
5454
}
5555

56-
5756
/// <inheritdoc />
5857
[NonAction]
5958
public ValueTask QueueMessage(T data)
@@ -210,14 +209,18 @@ protected virtual Task SendWebSocketMessage(T message, WebSocket websocket, Canc
210209

211210
#endregion
212211

212+
private CancellationTokenSource _receiveCancellationTokenSource = new();
213+
213214
/// <summary>
214215
/// Main receiver logic for the websocket
215216
/// </summary>
216217
/// <returns></returns>
217218
[NonAction]
218219
private async Task Logic()
219220
{
220-
while (!LinkedToken.IsCancellationRequested)
221+
using var linkedReceiverToken = CancellationTokenSource.CreateLinkedTokenSource(LinkedToken, _receiveCancellationTokenSource.Token);
222+
223+
while (!linkedReceiverToken.IsCancellationRequested)
221224
{
222225
try
223226
{
@@ -241,7 +244,7 @@ private async Task Logic()
241244
return;
242245
}
243246

244-
if (!await HandleReceive())
247+
if (!await HandleReceive(linkedReceiverToken.Token))
245248
{
246249
// HandleReceive returned false, we will close the connection after this
247250
Logger.LogDebug("HandleReceive returned false, closing connection");
@@ -273,7 +276,18 @@ private async Task Logic()
273276
/// </summary>
274277
/// <returns>True if you want to continue the receiver loop, false if you want to terminate</returns>
275278
[NonAction]
276-
protected abstract Task<bool> HandleReceive();
279+
protected abstract Task<bool> HandleReceive(CancellationToken cancellationToken);
280+
281+
[NonAction]
282+
protected async Task ForceClose(WebSocketCloseStatus closeStatus, string? statusDescription)
283+
{
284+
await _receiveCancellationTokenSource.CancelAsync();
285+
286+
if (WebSocket is { State: WebSocketState.CloseReceived or WebSocketState.Open })
287+
{
288+
await WebSocket.CloseOutputAsync(closeStatus, statusDescription, LinkedToken);
289+
}
290+
}
277291

278292
/// <summary>
279293
/// Send initial data to the client

LiveControlGateway/Controllers/HubControllerBase.cs

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,7 @@ ILogger<FlatbuffersWebsocketBaseController<TIn, TOut>> logger
102102
try
103103
{
104104
Logger.LogInformation("Keep alive timeout reached, closing websocket connection");
105-
106-
if (WebSocket is { State: WebSocketState.Open })
107-
{
108-
await WebSocket!.CloseOutputAsync(WebSocketCloseStatus.ProtocolError, "Keep alive timeout reached",
109-
LinkedToken);
110-
}
111-
105+
await ForceClose(WebSocketCloseStatus.ProtocolError, "Keep alive timeout reached");
112106
WebSocket?.Abort();
113107
}
114108
catch (Exception ex)
@@ -187,14 +181,7 @@ public async Task DisconnectOld()
187181
if (WebSocket == null)
188182
return;
189183

190-
if (WebSocket is { State: WebSocketState.Open })
191-
{
192-
await WebSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure,
193-
"Hub is connecting from a different location",
194-
LinkedToken);
195-
}
196-
197-
WebSocket?.Abort();
184+
await ForceClose(WebSocketCloseStatus.NormalClosure, "Hub is connecting from a different location");
198185
}
199186

200187
private static DateTimeOffset? GetBootedAtFromUptimeMs(ulong uptimeMs)

LiveControlGateway/Controllers/LiveControlController.cs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ await QueueMessage(new LiveControlResponse<LiveResponseType>
255255
}
256256

257257
/// <inheritdoc />
258-
protected override async Task<bool> HandleReceive()
258+
protected override async Task<bool> HandleReceive(CancellationToken cancellationToken)
259259
{
260260
var message =
261261
await JsonWebSocketUtils.ReceiveFullMessageAsyncNonAlloc<BaseRequest<LiveRequestType>>(WebSocket!,
@@ -266,8 +266,7 @@ await JsonWebSocketUtils.ReceiveFullMessageAsyncNonAlloc<BaseRequest<LiveRequest
266266
if (request?.Data == null)
267267
{
268268
Logger.LogWarning("Received null data from client");
269-
await WebSocket!.CloseOutputAsync(WebSocketCloseStatus.InvalidPayloadData,
270-
"Invalid json message received", LinkedToken);
269+
await ForceClose(WebSocketCloseStatus.InvalidPayloadData, "Invalid json message received");
271270
return false;
272271
}
273272

@@ -278,8 +277,7 @@ await JsonWebSocketUtils.ReceiveFullMessageAsyncNonAlloc<BaseRequest<LiveRequest
278277
async failed =>
279278
{
280279
Logger.LogWarning(failed.Exception, "Deserialization failed for websocket message");
281-
await WebSocket!.CloseOutputAsync(WebSocketCloseStatus.InvalidPayloadData,
282-
"Invalid json message received", LinkedToken);
280+
await ForceClose(WebSocketCloseStatus.InvalidPayloadData, "Invalid json message received");
283281
return false;
284282
}, closure =>
285283
{
@@ -550,8 +548,8 @@ await SendWebSocketMessage(new LiveControlResponse<LiveResponseType>
550548
ResponseType = LiveResponseType.DeviceNotConnected,
551549
}, WebSocket!, LinkedToken);
552550

553-
await WebSocket!.CloseOutputAsync(WebSocketCloseStatus.NormalClosure,
554-
"Hub is disconnected", LinkedToken);
551+
552+
await ForceClose(WebSocketCloseStatus.NormalClosure, "Hub is disconnected");
555553
}
556554
catch (Exception e)
557555
{

LiveControlGateway/Websocket/FlatbuffersWebsocketBaseController.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,17 @@ protected override Task
4848
protected abstract Task<bool> Handle(TIn data);
4949

5050
/// <inheritdoc />
51-
protected override async Task<bool> HandleReceive()
51+
protected override async Task<bool> HandleReceive(CancellationToken cancellationToken)
5252
{
5353
var message =
5454
await FlatbufferWebSocketUtils.ReceiveFullMessageAsyncNonAlloc(WebSocket!,
55-
_incomingSerializer, LinkedToken);
55+
_incomingSerializer, cancellationToken);
5656

5757
var continueLoop = await message.Match(
5858
Handle,
5959
async _ =>
6060
{
61-
await WebSocket!.CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "Invalid flatbuffers message",
62-
LinkedToken);
61+
await ForceClose(WebSocketCloseStatus.InvalidPayloadData, "Invalid flatbuffers message");
6362
return false;
6463
},
6564
_ =>

0 commit comments

Comments
 (0)