Message Routing System

Message Routing System

The Matrix Communication Framework provides a declarative message routing system that enables hierarchical communication between distributed services.

Core Concepts

public class MessageRouter : CommunicationElement
{
    public static readonly DependencyProperty RoutingStrategyProperty =
        DependencyProperty.RegisterAttached(
            "RoutingStrategy",
            typeof(RoutingStrategy),
            typeof(MessageRouter),
            new CommunicationPropertyMetadata(
                RoutingStrategy.Default,
                OnRoutingStrategyChanged,
                CoerceRoutingStrategy
            )
        );

    public static void SetRoutingStrategy(CommunicationElement element, RoutingStrategy value)
        => element.SetValue(RoutingStrategyProperty, value);

    public static RoutingStrategy GetRoutingStrategy(CommunicationElement element)
        => (RoutingStrategy)element.GetValue(RoutingStrategyProperty);
}

Message Flow Definition

<CommunicationTree xmlns="http://schemas.matrix.com/network/2024">
    <ServiceNode Name="AuthenticationService">
        <RoutingProperties.Strategy>Bubble</RoutingProperties.Strategy>
        
        <ServiceNode Name="UserManagement">
            <RoutingProperties.Strategy>Tunnel</RoutingProperties.Strategy>
            
            <!-- Messages tunnel down to specific endpoints -->
            <EndpointNode Path="/users/verify" />
            <EndpointNode Path="/users/authorize" />
        </ServiceNode>
        
        <ServiceNode Name="SessionManagement">
            <!-- Messages bubble up through service hierarchy -->
            <EndpointNode Path="/sessions/validate" />
            <EndpointNode Path="/sessions/refresh" />
        </ServiceNode>
    </ServiceNode>
</CommunicationTree>

## Message Routing Implementation

```csharp
public class MessageRoutingContext
{
    public ServiceNode SourceNode { get; }
    public ServiceNode TargetNode { get; }
    public IEnumerable<ServiceNode> RoutingPath { get; }
    public RoutingDirection Direction { get; }
    public MessagePriority Priority { get; }
}

public class ServiceMessage
{
    public string MessageId { get; }
    public object Content { get; }
    public MessageRoutingContext RoutingContext { get; }
    public IDictionary<string, object> Properties { get; }
}

public interface IMessageRouter
{
    Task RouteMessageAsync(ServiceMessage message);
    IObservable<ServiceMessage> ObserveMessages(MessageFilter filter);
    void RegisterHandler(string path, Func<ServiceMessage, Task> handler);
}

public class ServiceNodeRouter : IMessageRouter
{
    private readonly ServiceNode _node;
    private readonly IMessageDispatcher _dispatcher;
    private readonly ConcurrentDictionary<string, List<Func<ServiceMessage, Task>>> _handlers;

    public async Task RouteMessageAsync(ServiceMessage message)
    {
        var context = message.RoutingContext;
        var path = CalculateRoutingPath(context);

        foreach (var node in path)
        {
            if (await ShouldRouteThrough(node, message))
            {
                await _dispatcher.DispatchAsync(node, message);
            }
        }
    }

    private async Task<bool> ShouldRouteThrough(ServiceNode node, ServiceMessage message)
    {
        var strategy = MessageRouter.GetRoutingStrategy(node);
        var direction = message.RoutingContext.Direction;

        return strategy switch
        {
            RoutingStrategy.Bubble when direction == RoutingDirection.Up => true,
            RoutingStrategy.Tunnel when direction == RoutingDirection.Down => true,
            RoutingStrategy.Direct => node == message.RoutingContext.TargetNode,
            _ => false
        };
    }
}

## Service Communication Patterns

```csharp
// Define a service communication pattern
public class AuthenticationPattern : CommunicationPattern
{
    public override async Task<ServiceMessage> ProcessMessageAsync(ServiceMessage message)
    {
        // Pattern implementation for authentication flow
        switch (message.Content)
        {
            case VerifyUserRequest verify:
                return await TunnelToUserManagement(verify);
                
            case ValidateSessionRequest validate:
                return await BubbleToSessionManagement(validate);
                
            default:
                return await base.ProcessMessageAsync(message);
        }
    }
}

// Apply the pattern in XAML
public class AuthenticationService : ServiceNode
{
    static AuthenticationService()
    {
        CommunicationPattern.SetPattern(
            typeof(AuthenticationService),
            new AuthenticationPattern()
        );
    }
}

## Best Practices

1. **Message Flow Design**
   - Design service hierarchies based on message flow patterns
   - Use routing strategies to control message propagation
   - Implement clear message ownership boundaries
   - Define explicit routing paths
   - Consider message priority and ordering

2. **State Propagation**
   - Use dependency properties for network state
   - Implement proper state synchronization
   - Handle partial network failures
   - Maintain consistency across services
   - Support state recovery mechanisms

3. **Performance Optimization**
   - Cache routing paths
   - Batch related messages
   - Optimize message serialization
   - Implement smart routing decisions
   - Monitor routing performance

4. **Security**
   - Validate message routes
   - Authenticate service nodes
   - Authorize message propagation
   - Encrypt sensitive content
   - Audit message flow