handle method
Handle calls Negotiate to determine which protocol handler to use for an inbound stream, then invokes the protocol handler function, passing it the protocol ID and the stream. Returns an error if negotiation fails.
Implementation
@override
Future<void> handle(P2PStream<dynamic> stream) async {
final (proto, handler) = await negotiate(stream);
// Ensure the stream is valid before proceeding
if (stream.isClosed) {
_log.warning('[multistreamMuxer - handle] Stream for protocol $proto was closed during or immediately after negotiation. Aborting handler call.');
return;
}
try {
_log.fine('[multistreamMuxer - handle] Protocol $proto negotiated. Attempting to set protocol on stream scope and stream itself.');
// Set on the scope for resource management
await stream.scope().setProtocol(proto);
// Also set on the stream itself for application access
await stream.setProtocol(proto);
_log.fine('[multistreamMuxer - handle] Successfully set protocol $proto on stream scope and stream. Proceeding to call handler.');
} catch (e, s) {
_log.severe('[multistreamMuxer - handle] CRITICAL: Error occurred while setting protocol $proto on stream scope/stream: $e\n$s. Resetting stream and not calling handler.');
// If setProtocol fails (e.g., resource limits), we should not proceed to the handler.
await stream.reset();
// Depending on desired error propagation, you might rethrow or just log.
// For now, rethrowing makes the failure visible.
rethrow;
}
// Only call the handler if setProtocol was successful
return handler(proto, stream);
}