Event Routing
Message Structure
Every event in the Matrix Framework contains:
type: The type of the event (e.g.,IncomingMessageEvent)payload: The data being carried by the eventroutingStrategy: Defines how the event should propagate through the treemetadata: Additional information about the event’s context and handling
Event Types
Core Events
interface MiddlewareEvent {
type: string;
payload: any;
routingStrategy: RoutingStrategy;
metadata: {
timestamp: number;
source: string;
handled: boolean;
};
}Common Event Types
-
Message Events
IncomingMessageEventOutgoingMessageEventMessageAckEvent
-
Lifecycle Events
InitializeEventStartEventStopEventDisposeEvent
-
Error Events
ErrorEventValidationErrorEventTimeoutEvent
Routing Strategies
1. Tunnel Strategy
- Propagates events from the root to the leaves
- Useful for configuration and control messages
- Can be intercepted at any level
class TunnelStrategy implements RoutingStrategy {
async route(event: MiddlewareEvent, node: TreeNode): Promise<void> {
await node.handleEvent(event);
if (!event.metadata.handled) {
for (const child of node.children) {
await this.route(event, child);
}
}
}
}2. Bubble Strategy
- Propagates events from leaves back to the root
- Ideal for collecting responses and aggregating data
- Can be stopped at any level if handled
class BubbleStrategy implements RoutingStrategy {
async route(event: MiddlewareEvent, node: TreeNode): Promise<void> {
const children = node.children.slice().reverse();
for (const child of children) {
await this.route(event, child);
if (event.metadata.handled) break;
}
if (!event.metadata.handled) {
await node.handleEvent(event);
}
}
}3. Broadcast Strategy
- Sends events to all nodes regardless of handling
- Used for system-wide notifications
- Cannot be intercepted or stopped
class BroadcastStrategy implements RoutingStrategy {
async route(event: MiddlewareEvent, node: TreeNode): Promise<void> {
await node.handleEvent(event);
for (const child of node.children) {
await this.route(event, child);
}
}
}Event Handling
Handler Registration
interface EventHandler {
(event: MiddlewareEvent): Promise<void>;
}
class TreeNode {
private handlers: Map<string, EventHandler[]>;
addHandler(eventType: string, handler: EventHandler): void {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, []);
}
this.handlers.get(eventType).push(handler);
}
}Event Processing
class TreeNode {
async handleEvent(event: MiddlewareEvent): Promise<void> {
const handlers = this.handlers.get(event.type) || [];
for (const handler of handlers) {
try {
await handler(event);
if (event.metadata.handled) break;
} catch (error) {
await this.handleError(error, event);
}
}
}
}