markiodev / Networker

A simple to use TCP and UDP networking library for .NET. Compatible with Unity.
MIT License
477 stars 77 forks source link

Packet Handler Decorators #37

Open snarlynarwhal opened 5 years ago

snarlynarwhal commented 5 years ago

What do you think about adding built-in support for Packet Handler Decorators?

We could use an Attribute-based means of assigning Decorators to Packet Handlers and wire them up at startup.

This blog talks about the Command Handler Pattern and has a section about enhancing the pattern with Decorators:

https://blogs.cuttingedge.it/steven/posts/2011/meanwhile-on-the-command-side-of-my-architecture/

The article provides these use case examples:

Here's an example of how you might define custom Decorators for a Handler:

[Decorate(
typeof(LoggingHandlerDecorator),
typeof(AuthorizationHandlerDecorator),
typeof(BackgroundJobHandlerDecorator)]
public class SomePacketHandler : PacketHandlerBase<SomePacket>
{
    ....
}

Having a way to define global or module Decorators could prevent having to add the Decorate attribute to so many Handler classes.

Here's an example of the sort of benefits that Decorators can provide, especially when used with helper Attributes:

[Authorization(30)] // User must have authorization level of 30 for this to succeed
public override Task Process(SomePacket packet, IPacketContext context)
{
    ...
}

For this example, the AuthorizationHandlerDecorator.Process method might look something like this:

public override async Task Process(SomePacket packet, IPacketContext context)
{
    int userAccessLevel = 0; // Get user access level from service
    // Gets from the method's Authorization Attribute
    int requiredAccessLevel = GetRequiredAccessLevel(packet);
    if (userAccessLevel >= requiredAccessLevel) 
    {
        await DecoratedHandler.Process(packet, context);
    }
}

Thoughts?

markiodev commented 5 years ago

Already got some ideas for registering middleware, I'll have a go at this one and share around some docs.

markiodev commented 5 years ago

Moving this to 3.1

snarlynarwhal commented 5 years ago

I made PR #40 let me know what you think