Skip to content

Commit

Permalink
Refactored pipelines to separate class, updated middleware definition…
Browse files Browse the repository at this point in the history
…s and invocation model, added DisconnectionMiddleware and ExceptionMiddleware.
  • Loading branch information
dicky authored and dicky committed Jul 30, 2017
1 parent 6d5453e commit 25a4c81
Showing 14 changed files with 424 additions and 191 deletions.
20 changes: 7 additions & 13 deletions DotNetifyLib.Core/VMController.cs
Original file line number Diff line number Diff line change
@@ -56,18 +56,11 @@ public class UnresolvedVMUpdateException : Exception { }
public delegate object CreateInstanceDelegate(Type type, object[] args);

/// <summary>
/// Delegate to provide interception hook when requesting a view model.
/// Delegate to provide interception hook for a view model action.
/// </summary>
/// <param name="vm">View model.</param>
/// <param name="vmArg">Optional view model initialization argument.</param>
public delegate void RequestingVMHookDelegate(string vmId, BaseVM vm, ref object vmArg);

/// <summary>
/// Delegate to provide interception hook when updating a view model.
/// </summary>
/// <param name="vm">View model.</param>
/// <param name="data">Data provided to the view model.</param>
public delegate void UpdatingVMHookDelegate(string vmId, BaseVM vm, ref Dictionary<string, object> data);
/// <param name="data">Data being passed to the view model.</param>
public delegate void FilterDelegate(string vmId, BaseVM vm, ref object data);

#endregion

@@ -124,12 +117,12 @@ protected internal class VMInfo
/// <summary>
/// Interception hook for requesting a view model.
/// </summary>
public RequestingVMHookDelegate RequestingVM { get; set; }
public FilterDelegate RequestingVM { get; set; }

/// <summary>
/// Interception hook for updating a view model.
/// </summary>
public UpdatingVMHookDelegate UpdatingVM { get; set; }
public FilterDelegate UpdatingVM { get; set; }

// Default constructor.
public VMController()
@@ -256,7 +249,8 @@ public virtual void OnUpdateVM(string connectionId, string vmId, Dictionary<stri
var vmInstance = _activeVMs[vmId].Instance;

// Invoke the interception delegate.
UpdatingVM?.Invoke(vmId, vmInstance, ref data);
object dataObject = data;
UpdatingVM?.Invoke(vmId, vmInstance, ref dataObject);

lock (vmInstance)
{
69 changes: 69 additions & 0 deletions DotNetifyLib.SignalR/DeveloperLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
Copyright 2017 Dicky Suryadi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Threading.Tasks;
using DotNetify;
using Microsoft.AspNetCore.SignalR.Hubs;
using Newtonsoft.Json;

namespace WebApplication.Core.React
{
public delegate void LogTraceDelegate(string log);

public class DeveloperLoggingMiddleware : IMiddleware, IDisconnectionMiddleware, IExceptionMiddleware
{
private readonly LogTraceDelegate _trace;

public DeveloperLoggingMiddleware(LogTraceDelegate trace)
{
_trace = trace;
}

public Task Invoke(DotNetifyHubContext hubContext, NextDelegate next)
{
_trace($@"[dotNetify] connId={hubContext.CallerContext.ConnectionId} type={hubContext.CallType}
vmId={hubContext.VMId}
data={JsonConvert.SerializeObject(hubContext.Data ?? string.Empty)}
headers={JsonConvert.SerializeObject(hubContext.Headers ?? string.Empty)}");

return next(hubContext);
}

public Task OnDisconnected(HubCallerContext context)
{
_trace($"[dotNetify] connId={context.ConnectionId} type=OnDisconnected");
return Task.CompletedTask;
}

public Task<Exception> OnException(HubCallerContext context, Exception exception)
{
_trace($"[dotNetify] connId={context.ConnectionId} {exception.GetType().Name}={exception.Message}");
return Task.FromResult(exception);
}
}

/// <summary>
/// Method extension to specify parameter type for the middleware.
/// </summary>
public static class DeveloperLoggingMiddlewareExtensions
{
public static void UseDeveloperLogging(this IDotNetifyConfiguration config, LogTraceDelegate logTraceDelegate)
{
config.UseMiddleware<DeveloperLoggingMiddleware>(logTraceDelegate);
}
}
}
182 changes: 37 additions & 145 deletions DotNetifyLib.SignalR/DotNetifyHub.cs
Original file line number Diff line number Diff line change
@@ -17,14 +17,11 @@ limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using DotNetify.Security;

namespace DotNetify
@@ -36,13 +33,7 @@ public class DotNetifyHub : Hub
{
private readonly IVMControllerFactory _vmControllerFactory;
private readonly IPrincipalAccessor _principalAccessor;
private readonly IList<Func<IMiddleware>> _middlewareFactories;
private readonly IDictionary<Type, Func<IVMFilter>> _vmFilterFactories;
private readonly IMemoryCache _headersCache;
private readonly Func<string, string> _headersKey = (string connectionId) => JTOKEN_HEADERS + connectionId;

private const string JTOKEN_VMARG = "$vmArg";
private const string JTOKEN_HEADERS = "$headers";
private readonly IHubPipeline _hubPipeline;

private IPrincipal _principal;

@@ -64,31 +55,17 @@ private VMController VMController
}
}

/// <summary>
/// Request headers of the current connection.
/// </summary>
private object Headers
{
get { return _headersCache.Get(_headersKey(Context.ConnectionId)); }
set { _headersCache.Set(_headersKey(Context.ConnectionId), value); }
}

/// <summary>
/// Constructor for dependency injection.
/// </summary>
/// <param name="vmControllerFactory">Factory of view model controllers.</param>
/// <param name="principalAccessor">Allow to pass the hub principal.</param>
/// <param name="middlewareFactories">Middlewares to intercept incoming view model requests and updates.</param>
public DotNetifyHub(IVMControllerFactory vmControllerFactory, IPrincipalAccessor principalAccessor, IMemoryCache headersCache,
IList<Func<IMiddleware>> middlewareFactories, IDictionary<Type, Func<IVMFilter>> vmFilterFactories)
public DotNetifyHub(IVMControllerFactory vmControllerFactory, IPrincipalAccessor principalAccessor, IHubPipeline hubPipeline)
{
_vmControllerFactory = vmControllerFactory;
_vmControllerFactory.ResponseDelegate = SendResponse;

_principalAccessor = principalAccessor;
_middlewareFactories = middlewareFactories;
_vmFilterFactories = vmFilterFactories;
_headersCache = headersCache;
_hubPipeline = hubPipeline;
}

/// <summary>
@@ -101,7 +78,10 @@ public override Task OnDisconnected(bool stopCalled)
{
// Remove the controller on disconnection.
_vmControllerFactory.Remove(Context.ConnectionId);
_headersCache.Remove(_headersKey(Context.ConnectionId));

// Allow middlewares to hook to the event.
_hubPipeline.RunDisconnectionMiddlewares(Context);

return base.OnDisconnected(stopCalled);
}

@@ -115,12 +95,11 @@ public void SendResponse(string connectionId, string vmId, string vmData)
{
try
{
vmData = RunMiddlewares(nameof(Response_VM), vmId, vmData, false);
Response_VM(connectionId, vmId, vmData);
}
catch (OperationCanceledException ex)
{
Trace.WriteLine(ex.Message);
_hubPipeline.RunMiddlewares(Context, nameof(Response_VM), vmId, vmData, ctx =>
{
Response_VM(connectionId, ctx.VMId, ctx.Data as string);
return Task.CompletedTask;
});
}
catch (Exception ex)
{
@@ -139,23 +118,18 @@ public void Request_VM(string vmId, object vmArg)
{
try
{
vmArg = ExtractHeaders(vmArg);
vmArg = RunMiddlewares(nameof(Request_VM), vmId, vmArg);
_hubPipeline.RunMiddlewares(Context, nameof(Request_VM), vmId, vmArg, ctx =>
{
_principal = ctx.Principal;
VMController.OnRequestVM(Context.ConnectionId, ctx.VMId, ctx.Data);
return Task.CompletedTask;
});

Trace.WriteLine($"[dotNetify] Request_VM: {vmId} {Context.ConnectionId}");
VMController.OnRequestVM(Context.ConnectionId, vmId, vmArg);
}
catch (OperationCanceledException ex)
{
Trace.WriteLine(ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Response_VM(Context.ConnectionId, vmId, SerializeException(ex));
}
catch (Exception ex)
{
Trace.Fail(ex.ToString());
var finalEx = _hubPipeline.RunExceptionMiddleware(Context, ex);
Response_VM(Context.ConnectionId, vmId, SerializeException(finalEx));
}
}

@@ -168,26 +142,16 @@ public void Update_VM(string vmId, Dictionary<string, object> vmData)
{
try
{
// If this method is called only to refresh the connection request headers, leave as soon as the headers were extracted.
if ((vmData = ExtractHeaders(vmData)).Count == 0)
return;

vmData = RunMiddlewares(nameof(Update_VM), vmId, vmData) as Dictionary<string, object>;

Trace.WriteLine($"[dotNetify] Update_VM: {vmId} {Context.ConnectionId} {JsonConvert.SerializeObject(vmData)}");
VMController.OnUpdateVM(Context.ConnectionId, vmId, vmData);
}
catch (OperationCanceledException ex)
{
Trace.WriteLine(ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Response_VM(Context.ConnectionId, vmId, SerializeException(ex));
_hubPipeline.RunMiddlewares(Context, nameof(Update_VM), vmId, vmData, ctx =>
{
_principal = ctx.Principal;
VMController.OnUpdateVM(ctx.CallerContext.ConnectionId, ctx.VMId, ctx.Data as Dictionary<string, object>);
return Task.CompletedTask;
});
}
catch (Exception ex)
{
Trace.Fail(ex.ToString());
Response_VM(Context.ConnectionId, vmId, SerializeException(ex));
}
}

@@ -219,111 +183,39 @@ public void Dispose_VM(string vmId)
/// <param name="vmData">View model data in serialized JSON.</param>
internal void Response_VM(string connectionId, string vmId, string vmData)
{
Trace.WriteLine($"[dotNetify] Response_VM: {vmId} {connectionId} {vmData}");
if (_vmControllerFactory.GetInstance(connectionId) != null) // Touch the factory to push the timeout.
Clients.Client(connectionId).Response_VM(vmId, vmData);
}

#endregion

/// <summary>
/// Extract headers from the given argument.
/// </summary>
/// <param name="data">Data that comes from Request_VM or Update_VM.</param>
/// <returns>The input argument sans headers.</returns>
private T ExtractHeaders<T>(T data) where T : class
{
if (typeof(T) == typeof(Dictionary<string, object>))
{
var vmData = data as Dictionary<string, object>;
if (vmData.ContainsKey(JTOKEN_HEADERS))
{
Headers = vmData[JTOKEN_HEADERS];
vmData.Remove(JTOKEN_HEADERS);
}
return vmData as T;
}
else
{
JObject arg = data as JObject;
if (arg.Property(JTOKEN_HEADERS) != null)
Headers = arg[JTOKEN_HEADERS];
if (arg.Property(JTOKEN_VMARG) != null)
data = arg[JTOKEN_VMARG] as T;
return data;
}
}

/// <summary>
/// Run the middlewares on the data.
/// Runs the view model filter.
/// </summary>
/// <param name="callType">Call type: Request_VM, Update_VM or Response_VM.</param>
/// <param name="vmId">Identifies the view model.</param>
/// <param name="data">Call data.</param>
/// <param name="exceptionSent">Whether the exception should be sent to the client.</param>
/// <returns>Hub context data.</returns>
private T RunMiddlewares<T>(string callType, string vmId, T data, bool exceptionSent = true) where T : class
/// <param name="vm">View model instance.</param>
/// <param name="vmArg">Optional view model argument.</param>
private void RunVMFilters(string callType, string vmId, BaseVM vm, ref object vmArg)
{
try
{
var hubContext = new DotNetifyHubContext(Context, callType, vmId, data, Headers, _principal);
_middlewareFactories?.ToList().ForEach(factory => factory().Invoke(hubContext));
_principal = hubContext.Principal;
return hubContext.Data as T;
_hubPipeline.RunVMFilters(Context, callType, vmId, vm, ref vmArg, _principal);
}
catch (Exception ex)
catch (TargetInvocationException ex)
{
if (exceptionSent)
Response_VM(Context.ConnectionId, vmId, SerializeException(ex));
throw new OperationCanceledException($"Middleware threw {ex.GetType().Name}: {ex.Message}", ex);
throw ex.InnerException;
}
}

/// <summary>
/// Runs the view model filter.
/// Runs the filter before the view model is requested.
/// </summary>
/// <param name="vmId">Identifies the view model.</param>
/// <param name="vm">View model instance.</param>
/// <param name="vmArg">Optional view model argument.</param>
private void RunRequestingVMFilters(string vmId, BaseVM vm, ref object vmArg) => RunVMFilters(nameof(Request_VM), vmId, vm, ref vmArg);

/// <summary>
/// Runs the view model filter.
/// </summary>
/// <param name="vmId">Identifies the view model.</param>
/// <param name="vm">View model instance.</param>
/// <param name="data">Update data for the view model.</param>
private void RunUpdatingVMFilters(string vmId, BaseVM vm, ref Dictionary<string, object> data) => RunVMFilters(nameof(Update_VM), vmId, vm, ref data);

/// <summary>
/// Runs the view model filter.
/// Runs the filter before the view model is updated.
/// </summary>
/// <param name="callType">Call type: Request_VM, Update_VM or Response_VM.</param>
/// <param name="vmId">Identifies the view model.</param>
/// <param name="vm">View model instance.</param>
/// <param name="data">Call data.</param>
private void RunVMFilters<T>(string callType, string vmId, BaseVM vm, ref T data) where T : class
{
try
{
var vmContext = new VMContext(new DotNetifyHubContext(Context, callType, vmId, data, Headers, _principal), vm);
foreach (var attr in vm.GetType().GetTypeInfo().GetCustomAttributes())
{
var vmFilterType = typeof(IVMFilter<>).MakeGenericType(attr.GetType());
if (_vmFilterFactories.Keys.Any(t => vmFilterType.IsAssignableFrom(t)))
{
var vmFilter = _vmFilterFactories.FirstOrDefault(kvp => vmFilterType.IsAssignableFrom(kvp.Key)).Value();
vmFilterType.GetMethod("Invoke")?.Invoke(vmFilter, new object[] { attr, vmContext });
data = vmContext.HubContext.Data as T;
}
}
}
catch (Exception ex)
{
Response_VM(Context.ConnectionId, vmId, SerializeException(ex.InnerException));
throw new OperationCanceledException($"Filter threw {ex.GetType().Name}: {ex.Message}", ex);
}
}
private void RunUpdatingVMFilters(string vmId, BaseVM vm, ref object vmArg) => RunVMFilters(nameof(Update_VM), vmId, vm, ref vmArg);

/// <summary>
/// Serializes an exception.
Loading

0 comments on commit 25a4c81

Please sign in to comment.