Tree Tunnel Routing
The Tree Tunnel Routing strategy implements tunneling events, where events flow down through the middleware tree from parent to child nodes.
Implementation
private async tunnelEvent(event: MiddlewareEvent, node: TreeNode): Promise<void> {
console.log(`[TreeTunnelRoutingStrategy] Visiting node: ${node.node.name}`);
await node.node.handleEvent(event); // Current node processes event
if (!event.handled) {
for (const child of node.children) {
await this.tunnelEvent(event, child); // Propagate downward
if (event.handled) break; // Stop if handled
}
}
}Key Features
- Automatic Propagation: Events flow automatically from parent to children
- Early Interception: Parent nodes can handle events before children
- Propagation Control: Stop event flow by marking as handled
- Async Support: Full support for asynchronous event handlers
Usage Example
const router = new TreeTunnelRoutingStrategy();
const parent = new CoreElement();
const child = new CoreElement();
parent.addChild(child);
// Event will tunnel from parent to child
parent.on("init", async (ctx, next) => {
console.log("Parent initializing");
await next();
});
child.on("init", async (ctx, next) => {
console.log("Child initializing");
await next();
});
// Route an event using tree tunnel strategy
await router.routeEvent(new MiddlewareEvent("init"), parent);Best Practices
-
Use for Initialization
- Perfect for setup and configuration events
- Parent nodes can initialize before children
- Ensure proper state propagation
-
Handle Cancellation
- Mark events as handled to stop propagation
- Use for validation or access control
- Prevent unnecessary processing
-
Maintain State
- Use context to pass state down the tree
- Modify context as needed at each level
- Keep state changes predictable
XAML Integration
<TreeGeometry xmlns="http://schemas.codeium.com/middleware/2023">
<MQTTConnector Name="MQTTConnector" Path=":mqtt"
onInit="handleInit"
onIncomingMessage="handleIncomingMessage">
<JWTAuthorizationComponent Name="JWTAuthorization"
Path=":jwt"
onInit="handleAuthInit">
<TerminalComponent Name="Terminal"
Path=":terminal"
onInit="handleTerminalInit" />
</JWTAuthorizationComponent>
</MQTTConnector>
</TreeGeometry>In this example, the onInit event will tunnel down through the tree, allowing each component to initialize in a parent-first order.