Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

179 lines
6.6 KiB
Rust
Raw Normal View History

2017-11-07 18:25:10 +01:00
// Copyright 2017 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
2017-11-08 10:11:58 +01:00
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
2017-11-08 10:11:58 +01:00
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2017-11-08 10:11:58 +01:00
// DEALINGS IN THE SOFTWARE.
2017-11-07 18:25:10 +01:00
//! Integration tests for protocol negotiation.
2017-11-07 18:25:10 +01:00
use futures::prelude::*;
use multistream_select::{dialer_select_proto, listener_select_proto, NegotiationError, Version};
2017-11-07 10:26:45 +01:00
#[test]
fn select_proto_basic() {
async fn run(version: Version) {
let (client_connection, server_connection) = futures_ringbuf::Endpoint::pair(100, 100);
let server = async_std::task::spawn(async move {
let protos = vec!["/proto1", "/proto2"];
let (proto, mut io) = listener_select_proto(server_connection, protos)
.await
.unwrap();
assert_eq!(proto, "/proto2");
let mut out = vec![0; 32];
let n = io.read(&mut out).await.unwrap();
out.truncate(n);
assert_eq!(out, b"ping");
io.write_all(b"pong").await.unwrap();
io.flush().await.unwrap();
});
let client = async_std::task::spawn(async move {
let protos = vec!["/proto3", "/proto2"];
let (proto, mut io) =
dialer_select_proto(client_connection, protos.into_iter(), version)
.await
.unwrap();
assert_eq!(proto, "/proto2");
io.write_all(b"ping").await.unwrap();
io.flush().await.unwrap();
let mut out = vec![0; 32];
let n = io.read(&mut out).await.unwrap();
out.truncate(n);
assert_eq!(out, b"pong");
});
server.await;
client.await;
}
[multistream-select] Reduce roundtrips in protocol negotiation. (#1212) * Remove tokio-codec dependency from multistream-select. In preparation for the eventual switch from tokio to std futures. Includes some initial refactoring in preparation for further work in the context of https://github.com/libp2p/rust-libp2p/issues/659. * Reduce default buffer sizes. * Allow more than one frame to be buffered for sending. * Doc tweaks. * Remove superfluous (duplicated) Message types. * Reduce roundtrips in multistream-select negotiation. 1. Enable 0-RTT: If the dialer only supports a single protocol, it can send protocol data (e.g. the actual application request) together with the multistream-select header and protocol proposal. Similarly, if the listener supports a proposed protocol, it can send protocol data (e.g. the actual application response) together with the multistream-select header and protocol confirmation. 2. In general, the dialer "settles on" an expected protocol as soon as it runs out of alternatives. Furthermore, both dialer and listener do not immediately flush the final protocol confirmation, allowing it to be sent together with application protocol data. Attempts to read from the negotiated I/O stream implicitly flushes any pending data. 3. A clean / graceful shutdown of an I/O stream always completes protocol negotiation. The publich API of multistream-select changed slightly, requiring both AsyncRead and AsyncWrite bounds for async reading and writing due to the implicit buffering and "lazy" negotiation. The error types have also been changed, but they were not previously fully exported. Includes some general refactoring with simplifications and some more tests, e.g. there was an edge case relating to a possible ambiguity when parsing multistream-select protocol messages. * Further missing commentary. * Remove unused test dependency. * Adjust commentary. * Cleanup NegotiatedComplete::poll() * Fix deflate protocol tests. * Stabilise network_simult test. The test implicitly relied on "slow" connection establishment in order to have a sufficient probability of passing. With the removal of roundtrips in multistream-select, it is now more likely that within the up to 50ms duration between swarm1 and swarm2 dialing, the connection is already established, causing the expectation of step == 1 to fail when receiving a Connected event, since the step may then still be 0. This commit aims to avoid these spurious errors by detecting runs during which a connection is established "too quickly", repeating the test run. It still seems theoretically possible that, if connections are always established "too quickly", the test runs forever. However, given that the delta between swarm1 and swarm2 dialing is 0-50ms and that the TCP transport is used, that seems probabilistically unlikely. Nevertheless, the purpose of the artificial dialing delay between swarm1 and swarm2 should be re-evaluated and possibly at least the maximum delay further reduced. * Complete negotiation between upgrades in libp2p-core. While multistream-select, as a standalone library and providing an API at the granularity of a single negotiation, supports lazy negotiation (and in particular 0-RTT negotiation), in the context of libp2p-core where any number of negotiations are composed generically within the concept of composable "upgrades", it is necessary to wait for protocol negotiation between upgrades to complete. * Clarify docs. Simplify listener upgrades. Since reading from a Negotiated I/O stream implicitly flushes any pending negotiation data, there is no pitfall involved in not waiting for completion.
2019-08-12 12:09:53 +02:00
async_std::task::block_on(run(Version::V1));
async_std::task::block_on(run(Version::V1Lazy));
2017-11-07 10:26:45 +01:00
}
/// Tests the expected behaviour of failed negotiations.
2017-11-07 10:26:45 +01:00
#[test]
fn negotiation_failed() {
let _ = env_logger::try_init();
async fn run(
Test {
version,
listen_protos,
dial_protos,
dial_payload,
}: Test,
) {
let (client_connection, server_connection) = futures_ringbuf::Endpoint::pair(100, 100);
let server = async_std::task::spawn(async move {
let io = match listener_select_proto(server_connection, listen_protos).await {
Ok((_, io)) => io,
Err(NegotiationError::Failed) => return,
Err(NegotiationError::ProtocolError(e)) => {
panic!("Unexpected protocol error {e}")
}
};
match io.complete().await {
Err(NegotiationError::Failed) => {}
_ => panic!(),
}
});
let client =
async_std::task::spawn(async move {
let mut io =
match dialer_select_proto(client_connection, dial_protos.into_iter(), version)
.await
{
Err(NegotiationError::Failed) => return,
Ok((_, io)) => io,
Err(_) => panic!(),
};
// The dialer may write a payload that is even sent before it
// got confirmation of the last proposed protocol, when `V1Lazy`
// is used.
io.write_all(&dial_payload).await.unwrap();
match io.complete().await {
Err(NegotiationError::Failed) => {}
_ => panic!(),
}
});
server.await;
client.await;
}
/// Parameters for a single test run.
#[derive(Clone)]
struct Test {
version: Version,
listen_protos: Vec<&'static str>,
dial_protos: Vec<&'static str>,
dial_payload: Vec<u8>,
}
// Disjunct combinations of listen and dial protocols to test.
//
// The choices here cover the main distinction between a single
// and multiple protocols.
let protos = vec![
(vec!["/proto1"], vec!["/proto2"]),
(vec!["/proto1", "/proto2"], vec!["/proto3", "/proto4"]),
];
// The payloads that the dialer sends after "successful" negotiation,
// which may be sent even before the dialer got protocol confirmation
// when `V1Lazy` is used.
//
// The choices here cover the specific situations that can arise with
// `V1Lazy` and which must nevertheless behave identically to `V1` w.r.t.
// the outcome of the negotiation.
let payloads = vec![
// No payload, in which case all versions should behave identically
// in any case, i.e. the baseline test.
vec![],
// With this payload and `V1Lazy`, the listener interprets the first
// `1` as a message length and encounters an invalid message (the
// second `1`). The listener is nevertheless expected to fail
// negotiation normally, just like with `V1`.
vec![1, 1],
// With this payload and `V1Lazy`, the listener interprets the first
// `42` as a message length and encounters unexpected EOF trying to
// read a message of that length. The listener is nevertheless expected
// to fail negotiation normally, just like with `V1`
vec![42, 1],
];
for (listen_protos, dial_protos) in protos {
for dial_payload in payloads.clone() {
for &version in &[Version::V1, Version::V1Lazy] {
async_std::task::block_on(run(Test {
version,
listen_protos: listen_protos.clone(),
dial_protos: dial_protos.clone(),
dial_payload: dial_payload.clone(),
}))
}
}
}
2017-11-07 10:26:45 +01:00
}