Update smoldot to 0.14.0 and smoldot-light to 0.12.0 (#1307)

* cargo: Update smoldot to the latest version

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Update cargo lock

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* lightclient: Replace subxt::with_buffers with smoldot::with_buffers

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* lightclient: Sync PlatformRef with latest updates

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Update which to 5.0.0

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Update parachain example

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
This commit is contained in:
Alexandru Vasile
2023-12-06 17:52:59 +02:00
committed by GitHub
parent c3e02e7be2
commit 418c3afc92
6 changed files with 675 additions and 1023 deletions
Generated
+113 -99
View File
@@ -333,21 +333,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
dependencies = [
"concurrent-queue",
"event-listener",
"event-listener 2.5.3",
"futures-core",
]
[[package]]
name = "async-channel"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ca33f4bc4ed1babef42cad36cc1f51fa88be00420404e5b1e80ab1b18f7678c"
dependencies = [
"concurrent-queue",
"event-listener 4.0.0",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c1da3ae8dabd9c00f453a329dfe1fb28da3c0a72e2478cdcd93171740c20499"
dependencies = [
"async-lock",
"async-lock 2.8.0",
"async-task",
"concurrent-queue",
"fastrand 2.0.1",
"futures-lite",
"futures-lite 1.13.0",
"slab",
]
@@ -357,10 +370,10 @@ version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "279cf904654eeebfa37ac9bb1598880884924aab82e290aa65c9e77a0e142e06"
dependencies = [
"async-lock",
"async-lock 2.8.0",
"autocfg",
"blocking",
"futures-lite",
"futures-lite 1.13.0",
]
[[package]]
@@ -369,11 +382,11 @@ version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af"
dependencies = [
"async-lock",
"async-lock 2.8.0",
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-lite",
"futures-lite 1.13.0",
"log",
"parking",
"polling",
@@ -389,7 +402,18 @@ version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b"
dependencies = [
"event-listener",
"event-listener 2.5.3",
]
[[package]]
name = "async-lock"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7125e42787d53db9dd54261812ef17e937c95a51e4d291373b670342fa44310c"
dependencies = [
"event-listener 4.0.0",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
@@ -400,7 +424,7 @@ checksum = "0434b1ed18ce1cf5769b8ac540e33f01fa9471058b5e89da9e06f3c882a8c12f"
dependencies = [
"async-io",
"blocking",
"futures-lite",
"futures-lite 1.13.0",
]
[[package]]
@@ -410,12 +434,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a9d28b1d97e08915212e2e45310d47854eafa69600756fc735fb788f75199c9"
dependencies = [
"async-io",
"async-lock",
"async-lock 2.8.0",
"autocfg",
"blocking",
"cfg-if",
"event-listener",
"futures-lite",
"event-listener 2.5.3",
"futures-lite 1.13.0",
"rustix 0.37.24",
"signal-hook",
"windows-sys 0.48.0",
@@ -651,12 +675,12 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94c4ef1f913d78636d78d538eec1f18de81e481f44b1be0a81060090530846e1"
dependencies = [
"async-channel",
"async-lock",
"async-channel 1.9.0",
"async-lock 2.8.0",
"async-task",
"fastrand 2.0.1",
"futures-io",
"futures-lite",
"futures-lite 1.13.0",
"piper",
"tracing",
]
@@ -702,9 +726,9 @@ checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"
[[package]]
name = "byteorder"
version = "1.4.3"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
@@ -1156,19 +1180,6 @@ dependencies = [
"syn 2.0.39",
]
[[package]]
name = "curve25519-dalek-ng"
version = "4.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c359b7249347e46fb28804470d071c921156ad62b3eef5d34e2ba867533dec8"
dependencies = [
"byteorder",
"digest 0.9.0",
"rand_core 0.6.4",
"subtle-ng",
"zeroize",
]
[[package]]
name = "darling"
version = "0.14.4"
@@ -1439,6 +1450,36 @@ version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "event-listener"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d93877bcde0eb80ca09131a08d23f0a5c18a620b01db137dba666d18cd9b30c2"
dependencies = [
"concurrent-queue",
"pin-project-lite",
]
[[package]]
name = "event-listener"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "770d968249b5d99410d61f5bf89057f3199a077a04d087092f58e7d10692baae"
dependencies = [
"concurrent-queue",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3"
dependencies = [
"event-listener 4.0.0",
"pin-project-lite",
]
[[package]]
name = "eyre"
version = "0.6.8"
@@ -1602,6 +1643,16 @@ dependencies = [
"waker-fn",
]
[[package]]
name = "futures-lite"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeee267a1883f7ebef3700f262d2d54de95dfaf38189015a74fdc4e0c7ad8143"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "futures-macro"
version = "0.3.29"
@@ -2241,7 +2292,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da2327ba8df2fdbd5e897e2b5ed25ce7f299d345b9736b6828814c3dbd1fd47b"
dependencies = [
"anyhow",
"async-lock",
"async-lock 2.8.0",
"async-trait",
"beef",
"futures-timer",
@@ -2314,9 +2365,9 @@ checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
[[package]]
name = "libm"
version = "0.2.7"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4"
checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "libsecp256k1"
@@ -2402,9 +2453,12 @@ checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "lru"
version = "0.11.1"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a83fb7698b3643a0e34f9ae6f2e8f0178c0fd42f8b59d493aa271ff3a5bf21"
checksum = "2994eeba8ed550fd9b47a0b38f0242bc3344e496483c6180b69139cc2fa5d1d7"
dependencies = [
"hashbrown 0.14.1",
]
[[package]]
name = "mach"
@@ -3279,12 +3333,12 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4"
[[package]]
name = "ruzstd"
version = "0.4.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3ffab8f9715a0d455df4bbb9d21e91135aab3cd3ca187af0cd0c3c3f868fdc"
checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d"
dependencies = [
"byteorder",
"thiserror-core",
"derive_more",
"twox-hash",
]
@@ -3454,22 +3508,6 @@ dependencies = [
"zeroize",
]
[[package]]
name = "schnorrkel"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "844b7645371e6ecdf61ff246ba1958c29e802881a749ae3fb1993675d210d28d"
dependencies = [
"arrayref",
"arrayvec 0.7.4",
"curve25519-dalek-ng",
"merlin 3.0.0",
"rand_core 0.6.4",
"sha2 0.9.9",
"subtle-ng",
"zeroize",
]
[[package]]
name = "schnorrkel"
version = "0.11.3"
@@ -3725,9 +3763,9 @@ checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500"
[[package]]
name = "siphasher"
version = "0.3.11"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
checksum = "54ac45299ccbd390721be55b412d41931911f654fa99e2cb8bfb57184b2061fe"
[[package]]
name = "slab"
@@ -3750,25 +3788,25 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13f2b548cd8447f8de0fdf1c592929f70f4fc7039a05e47404b0d096ec6987a1"
dependencies = [
"async-channel",
"async-channel 1.9.0",
"async-executor",
"async-fs",
"async-io",
"async-lock",
"async-lock 2.8.0",
"async-net",
"async-process",
"blocking",
"futures-lite",
"futures-lite 1.13.0",
]
[[package]]
name = "smoldot"
version = "0.12.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4388a7690d9f76320dedc7f97f213160fbe4fb4a38a8b4cc8bb96e0fd05e0971"
checksum = "eca99148e026936bbc444c3708748207033968e4ef1c33bfc885660ae4d44d21"
dependencies = [
"arrayvec 0.7.4",
"async-lock",
"async-lock 3.2.0",
"atomic-take",
"base64 0.21.4",
"bip39",
@@ -3779,14 +3817,15 @@ dependencies = [
"derive_more",
"ed25519-zebra 4.0.3",
"either",
"event-listener",
"event-listener 3.1.0",
"fnv",
"futures-lite",
"futures-lite 2.1.0",
"futures-util",
"hashbrown 0.14.1",
"hex",
"hmac 0.12.1",
"itertools 0.11.0",
"libm",
"libsecp256k1",
"merlin 3.0.0",
"no-std-net",
@@ -3800,7 +3839,7 @@ dependencies = [
"rand 0.8.5",
"rand_chacha 0.3.1",
"ruzstd",
"schnorrkel 0.10.2",
"schnorrkel 0.11.3",
"serde",
"serde_json",
"sha2 0.10.8",
@@ -3817,20 +3856,20 @@ dependencies = [
[[package]]
name = "smoldot-light"
version = "0.10.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bea3d21923cbdb1362205ff8b2adb5da67e6b81b34c4bba1baaef9b88cbd83b8"
checksum = "0e6f1898682b618b81570047b9d870b3faaff6ae1891b468eddd94d7f903c2fe"
dependencies = [
"async-channel",
"async-lock",
"async-channel 2.1.1",
"async-lock 3.2.0",
"base64 0.21.4",
"blake2-rfc",
"derive_more",
"either",
"event-listener",
"event-listener 3.1.0",
"fnv",
"futures-channel",
"futures-lite",
"futures-lite 2.1.0",
"futures-util",
"hashbrown 0.14.1",
"hex",
@@ -4326,12 +4365,6 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
[[package]]
name = "subtle-ng"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "734676eb262c623cec13c3155096e08d1f8f29adce39ba17948b18dad1e54142"
[[package]]
name = "subxt"
version = "0.32.1"
@@ -4564,26 +4597,6 @@ dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-core"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d97345f6437bb2004cd58819d8a9ef8e36cdd7661c2abc4bbde0a7c40d9f497"
dependencies = [
"thiserror-core-impl",
]
[[package]]
name = "thiserror-core-impl"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "thiserror-impl"
version = "1.0.50"
@@ -5352,14 +5365,15 @@ dependencies = [
[[package]]
name = "which"
version = "4.4.2"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
checksum = "9bf3ea8596f3a0dd5980b46430f2058dfe2c36a27ccfbb1845d6fbfcd9ba6e14"
dependencies = [
"either",
"home",
"once_cell",
"rustix 0.38.17",
"windows-sys 0.48.0",
]
[[package]]
+3 -3
View File
@@ -98,11 +98,11 @@ tracing-subscriber = "0.3.18"
trybuild = "1.0.85"
wabt = "0.10.0"
wasm-bindgen-test = "0.3.24"
which = "4.4.2"
which = "5.0.0"
# Light client support:
smoldot = { version = "0.12.0", default-features = false }
smoldot-light = { version = "0.10.0", default-features = false }
smoldot = { version = "0.14.0", default-features = false }
smoldot-light = { version = "0.12.0", default-features = false }
tokio-stream = "0.1.14"
futures-util = "0.3.29"
rand = "0.8.5"
+536 -528
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -36,6 +36,7 @@ web = [
"getrandom/js",
"smoldot",
"smoldot/std",
"smoldot-light",
"tokio-stream",
"tokio/sync",
+8 -376
View File
@@ -32,379 +32,11 @@ pub fn sleep(duration: Duration) -> Delay {
/// Implementation detail of a stream from the `SubxtPlatform`.
#[pin_project::pin_project]
pub struct Stream(#[pin] pub with_buffers::WithBuffers<WasmSocket>);
pub mod with_buffers {
use smoldot::libp2p::read_write;
use core::{
fmt, future, mem, ops,
pin::{self, Pin},
task::Poll,
};
use crate::platform::wasm_helpers::Instant;
use futures_util::{AsyncRead, AsyncWrite};
use std::io;
/// Holds an implementation of `AsyncRead` and `AsyncWrite`, alongside with a read buffer and a
/// write buffer.
#[pin_project::pin_project]
pub struct WithBuffers<T> {
/// Actual socket to read from/write to.
#[pin]
socket: T,
/// Error that has happened on the socket, if any.
error: Option<io::Error>,
/// Storage for data read from the socket. The first [`WithBuffers::read_buffer_valid`] bytes
/// contain actual socket data, while the rest contains garbage data.
/// The capacity of this buffer is at least equal to the amount of bytes requested by the
/// inner data consumer.
read_buffer: Vec<u8>,
/// Number of bytes of data in [`WithBuffers::read_buffer`] that contain actual data.
read_buffer_valid: usize,
read_buffer_reasonable_capacity: usize,
/// True if reading from the socket has returned `Ok(0)` earlier, in other words "end of
/// file".
read_closed: bool,
/// Storage for data to write to the socket.
write_buffers: Vec<Vec<u8>>,
/// True if the consumer has closed the writing side earlier.
write_closed: bool,
/// True if the consumer has closed the writing side earlier, and the socket still has to
/// be closed.
close_pending: bool,
/// True if data has been written on the socket and the socket needs to be flushed.
flush_pending: bool,
/// Value of [`read_write::ReadWrite::now`] that was fed by the latest call to
/// [`WithBuffers::read_write_access`].
read_write_now: Option<Instant>,
/// Value of [`read_write::ReadWrite::wake_up_after`] produced by the latest call
/// to [`WithBuffers::read_write_access`].
read_write_wake_up_after: Option<Instant>,
}
const BUFFER_CAPACITY: usize = 65536;
const WRITE_BYTES_QUEUEABLE: usize = 128 * 1024;
impl<T> WithBuffers<T> {
/// Initializes a new [`WithBuffers`] with the given socket.
///
/// The socket must still be open in both directions.
pub fn new(socket: T) -> Self {
WithBuffers {
socket,
error: None,
read_buffer: Vec::with_capacity(BUFFER_CAPACITY),
read_buffer_valid: 0,
read_buffer_reasonable_capacity: BUFFER_CAPACITY,
read_closed: false,
write_buffers: Vec::with_capacity(64),
write_closed: false,
close_pending: false,
flush_pending: false,
read_write_now: None,
read_write_wake_up_after: None,
}
}
/// Returns an object that implements `Deref<Target = ReadWrite>`. This object can be used
/// to push or pull data to/from the socket.
///
/// > **Note**: The parameter requires `Self` to be pinned for consistency with
/// > [`WithBuffers::wait_read_write_again`].
pub fn read_write_access(
self: Pin<&mut Self>,
now: Instant,
) -> Result<ReadWriteAccess, &io::Error> {
let this = self.project();
debug_assert!(this
.read_write_now
.as_ref()
.map_or(true, |old_now| *old_now <= now));
*this.read_write_wake_up_after = None;
*this.read_write_now = Some(now);
if let Some(error) = this.error.as_ref() {
return Err(error);
}
this.read_buffer.truncate(*this.read_buffer_valid);
let write_bytes_queued = this.write_buffers.iter().map(Vec::len).sum();
Ok(ReadWriteAccess {
read_buffer_len_before: this.read_buffer.len(),
write_buffers_len_before: this.write_buffers.len(),
read_write: read_write::ReadWrite {
now,
incoming_buffer: mem::take(this.read_buffer),
expected_incoming_bytes: if !*this.read_closed { Some(0) } else { None },
read_bytes: 0,
write_bytes_queued,
write_buffers: mem::take(this.write_buffers),
write_bytes_queueable: if !*this.write_closed {
// Limit outgoing buffer size to 128kiB.
Some(WRITE_BYTES_QUEUEABLE.saturating_sub(write_bytes_queued))
} else {
None
},
wake_up_after: this.read_write_wake_up_after.take(),
},
read_buffer: this.read_buffer,
read_buffer_valid: this.read_buffer_valid,
read_buffer_reasonable_capacity: *this.read_buffer_reasonable_capacity,
write_buffers: this.write_buffers,
write_closed: this.write_closed,
close_pending: this.close_pending,
read_write_wake_up_after: this.read_write_wake_up_after,
})
}
}
impl<T> WithBuffers<T>
where
T: AsyncRead + AsyncWrite,
{
/// Waits until [`WithBuffers::read_write_access`] should be called again.
///
/// Returns if an error happens on the socket. If an error happened in the past on the socket,
/// the future never yields.
pub async fn wait_read_write_again<F>(
self: Pin<&mut Self>,
timer_builder: impl FnOnce(Instant) -> F,
) where
F: future::Future<Output = ()>,
{
let mut this = self.project();
// Return immediately if `wake_up_after <= now`.
match (&*this.read_write_wake_up_after, &*this.read_write_now) {
(Some(when_wake_up), Some(now)) if *when_wake_up <= *now => {
return;
}
_ => {}
}
let mut timer = pin::pin!({
let fut = this
.read_write_wake_up_after
.as_ref()
.map(|when| timer_builder(*when));
async {
if let Some(fut) = fut {
fut.await;
} else {
future::pending::<()>().await;
}
}
});
// Grow the read buffer in order to make space for potentially more data.
this.read_buffer.resize(this.read_buffer.capacity(), 0);
future::poll_fn(move |cx| {
if this.error.is_some() {
// Never return.
return Poll::Pending;
}
// If still `true` at the end of the function, `Poll::Pending` is returned.
let mut pending = true;
match future::Future::poll(Pin::new(&mut timer), cx) {
Poll::Pending => {}
Poll::Ready(()) => {
pending = false;
}
}
if !*this.read_closed {
let read_result = AsyncRead::poll_read(
this.socket.as_mut(),
cx,
&mut this.read_buffer[*this.read_buffer_valid..],
);
match read_result {
Poll::Pending => {}
Poll::Ready(Ok(0)) => {
*this.read_closed = true;
pending = false;
}
Poll::Ready(Ok(n)) => {
*this.read_buffer_valid += n;
// TODO: consider waking up only if the expected bytes of the consumer are exceeded
pending = false;
}
Poll::Ready(Err(err)) => {
*this.error = Some(err);
return Poll::Ready(());
}
};
}
loop {
if this.write_buffers.iter().any(|b| !b.is_empty()) {
let write_result = {
let buffers = this
.write_buffers
.iter()
.map(|buf| io::IoSlice::new(buf))
.collect::<Vec<_>>();
AsyncWrite::poll_write_vectored(this.socket.as_mut(), cx, &buffers)
};
match write_result {
Poll::Ready(Ok(0)) => {
// It is not legal for `poll_write` to return 0 bytes written.
unreachable!();
}
Poll::Ready(Ok(mut n)) => {
*this.flush_pending = true;
while n > 0 {
let first_buf = this.write_buffers.first_mut().unwrap();
if first_buf.len() <= n {
n -= first_buf.len();
this.write_buffers.remove(0);
} else {
// TODO: consider keeping the buffer as is but starting the next write at a later offset
first_buf.copy_within(n.., 0);
first_buf.truncate(first_buf.len() - n);
break;
}
}
// Wake up if the write buffers switch from non-empty to empty.
if this.write_buffers.is_empty() {
pending = false;
}
}
Poll::Ready(Err(err)) => {
*this.error = Some(err);
return Poll::Ready(());
}
Poll::Pending => break,
};
} else if *this.flush_pending {
match AsyncWrite::poll_flush(this.socket.as_mut(), cx) {
Poll::Ready(Ok(())) => {
*this.flush_pending = false;
}
Poll::Ready(Err(err)) => {
*this.error = Some(err);
return Poll::Ready(());
}
Poll::Pending => break,
}
} else if *this.close_pending {
match AsyncWrite::poll_close(this.socket.as_mut(), cx) {
Poll::Ready(Ok(())) => {
*this.close_pending = false;
pending = false;
break;
}
Poll::Ready(Err(err)) => {
*this.error = Some(err);
return Poll::Ready(());
}
Poll::Pending => break,
}
} else {
break;
}
}
if !pending {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
}
}
impl<T: fmt::Debug> fmt::Debug for WithBuffers<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("WithBuffers").field(&self.socket).finish()
}
}
/// See [`WithBuffers::read_write_access`].
pub struct ReadWriteAccess<'a> {
read_write: read_write::ReadWrite<Instant>,
read_buffer_len_before: usize,
write_buffers_len_before: usize,
// Fields below as references from the content of the `WithBuffers`.
read_buffer: &'a mut Vec<u8>,
read_buffer_valid: &'a mut usize,
read_buffer_reasonable_capacity: usize,
write_buffers: &'a mut Vec<Vec<u8>>,
write_closed: &'a mut bool,
close_pending: &'a mut bool,
read_write_wake_up_after: &'a mut Option<Instant>,
}
impl<'a> ops::Deref for ReadWriteAccess<'a> {
type Target = read_write::ReadWrite<Instant>;
fn deref(&self) -> &Self::Target {
&self.read_write
}
}
impl<'a> ops::DerefMut for ReadWriteAccess<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.read_write
}
}
impl<'a> Drop for ReadWriteAccess<'a> {
fn drop(&mut self) {
*self.read_buffer = mem::take(&mut self.read_write.incoming_buffer);
*self.read_buffer_valid = self.read_buffer.len();
// Adjust `read_buffer` to the number of bytes requested by the consumer.
if let Some(expected_incoming_bytes) = self.read_write.expected_incoming_bytes {
if expected_incoming_bytes < self.read_buffer_reasonable_capacity
&& self.read_buffer.is_empty()
{
// We use `shrink_to(0)` then `reserve(cap)` rather than just `shrink_to(cap)`
// so that the `Vec` doesn't try to preserve the data in the read buffer.
self.read_buffer.shrink_to(0);
self.read_buffer
.reserve(self.read_buffer_reasonable_capacity);
} else if expected_incoming_bytes > self.read_buffer.len() {
self.read_buffer
.reserve(expected_incoming_bytes - self.read_buffer.len());
}
debug_assert!(self.read_buffer.capacity() >= expected_incoming_bytes);
}
*self.write_buffers = mem::take(&mut self.read_write.write_buffers);
if self.read_write.write_bytes_queueable.is_none() && !*self.write_closed {
*self.write_closed = true;
*self.close_pending = true;
}
*self.read_write_wake_up_after = self.read_write.wake_up_after.take();
// If the consumer has advanced its reading or writing sides, we make the next call to
// `read_write_access` return immediately by setting `wake_up_after`.
if (self.read_buffer_len_before != self.read_buffer.len()
&& self
.read_write
.expected_incoming_bytes
.map_or(false, |b| b <= self.read_buffer.len()))
|| (self.write_buffers_len_before != self.write_buffers.len()
&& !*self.write_closed)
{
*self.read_write_wake_up_after = Some(self.read_write.now);
}
}
}
}
pub struct Stream(
#[pin]
pub smoldot::libp2p::with_buffers::WithBuffers<
future::BoxFuture<'static, Result<WasmSocket, std::io::Error>>,
WasmSocket,
Instant,
>,
);
+14 -17
View File
@@ -6,10 +6,12 @@ use super::wasm_socket::WasmSocket;
use core::time::Duration;
use futures::prelude::*;
use smoldot::libp2p::with_buffers;
use smoldot_light::platform::{
Address, ConnectError, ConnectionType, IpAddr, MultiStreamAddress, MultiStreamWebRtcConnection,
PlatformRef, SubstreamDirection,
Address, ConnectionType, IpAddr, MultiStreamAddress, MultiStreamWebRtcConnection, PlatformRef,
SubstreamDirection,
};
use std::{io, net::SocketAddr, pin::Pin};
const LOG_TARGET: &str = "subxt-platform-wasm";
@@ -34,12 +36,9 @@ impl PlatformRef for SubxtPlatform {
type Instant = super::wasm_helpers::Instant;
type MultiStream = std::convert::Infallible;
type Stream = super::wasm_helpers::Stream;
type StreamConnectFuture = future::BoxFuture<'static, Result<Self::Stream, ConnectError>>;
type MultiStreamConnectFuture = future::BoxFuture<
'static,
Result<MultiStreamWebRtcConnection<Self::MultiStream>, ConnectError>,
>;
type ReadWriteAccess<'a> = super::wasm_helpers::with_buffers::ReadWriteAccess<'a>;
type StreamConnectFuture = future::Ready<Self::Stream>;
type MultiStreamConnectFuture = future::Pending<MultiStreamWebRtcConnection<Self::MultiStream>>;
type ReadWriteAccess<'a> = with_buffers::ReadWriteAccess<'a, Self::Instant>;
type StreamUpdateFuture<'a> = future::BoxFuture<'a, ()>;
type StreamErrorRef<'a> = &'a std::io::Error;
type NextSubstreamFuture<'a> = future::Pending<Option<(Self::Stream, SubstreamDirection)>>;
@@ -142,17 +141,15 @@ impl PlatformRef for SubxtPlatform {
}
};
Box::pin(async move {
let socket_future = async move {
tracing::debug!(target: LOG_TARGET, "Connecting to addr={addr}");
WasmSocket::new(addr.as_str())
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))
};
let socket = WasmSocket::new(addr.as_str()).map_err(|err| ConnectError {
message: format!("Failed to reach peer: {err}"),
})?;
Ok(super::wasm_helpers::Stream(
super::wasm_helpers::with_buffers::WithBuffers::new(socket),
))
})
future::ready(super::wasm_helpers::Stream(with_buffers::WithBuffers::new(
Box::pin(socket_future),
)))
}
fn connect_multistream(&self, _address: MultiStreamAddress) -> Self::MultiStreamConnectFuture {