This repository has been archived by the owner on Sep 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
feat: Introduce a streaming way to encode BodyChunkIpld
. Fixes #498
#586
Open
jsantell
wants to merge
1
commit into
main
Choose a base branch
from
body-chunk-stream
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,187 @@ | ||
//! WIP on cross-platform benchmarking our encoder. | ||
//! | ||
//! wasm32 builds use `wasm_bindgen_test` runs as if | ||
//! it were running tests, hence the `wasm_bindgen_test` | ||
//! attribute on functions. Native builds run as expected. | ||
use async_stream::try_stream; | ||
use bytes::Bytes; | ||
use cid::Cid; | ||
use noosphere_core::data::{BodyChunkIpld, BufferStrategy}; | ||
use noosphere_core::tracing::initialize_tracing; | ||
use noosphere_storage::{helpers::make_disposable_storage, SphereDb, Storage}; | ||
use std::collections::HashMap; | ||
use tokio::{self, io::AsyncRead}; | ||
use tokio_stream::{Stream, StreamExt}; | ||
use tokio_util::io::StreamReader; | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
use web_time::Instant; | ||
jsantell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
use std::time::Instant; | ||
|
||
#[derive(PartialEq, Debug)] | ||
enum BenchmarkPosition { | ||
Start, | ||
End, | ||
} | ||
|
||
/// Simple timer util to record duration of processing. | ||
/// Does not support nested, overlapping, or duplicate time ranges. | ||
struct EncodingBenchmark { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this overlap at all with the benchmarking work done in #623 ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, similar constructs here; haven't updated this PR within that context, but some scaffolding can be shared here |
||
name: String, | ||
timestamps: Vec<(BenchmarkPosition, String, Instant)>, | ||
} | ||
|
||
impl EncodingBenchmark { | ||
pub fn new(name: &str) -> Self { | ||
EncodingBenchmark { | ||
name: name.to_owned(), | ||
timestamps: vec![], | ||
} | ||
} | ||
|
||
pub fn name(&self) -> &str { | ||
&self.name | ||
} | ||
|
||
pub fn start(&mut self, name: &str) { | ||
self.timestamps | ||
.push((BenchmarkPosition::Start, name.to_owned(), Instant::now())) | ||
} | ||
|
||
pub fn end(&mut self, name: &str) { | ||
self.timestamps | ||
.push((BenchmarkPosition::End, name.to_owned(), Instant::now())) | ||
} | ||
|
||
pub fn results(&self) -> anyhow::Result<HashMap<String, String>> { | ||
let mut current: Option<&(BenchmarkPosition, String, Instant)> = None; | ||
let mut results = HashMap::default(); | ||
for timestamp in self.timestamps.iter() { | ||
if let Some(current_timestamp) = current { | ||
assert!(timestamp.0 == BenchmarkPosition::End); | ||
assert_eq!(timestamp.1, current_timestamp.1); | ||
let duration = current_timestamp.2.elapsed().as_millis(); | ||
if results | ||
.insert(timestamp.1.to_owned(), format!("{}ms", duration)) | ||
.is_some() | ||
{ | ||
return Err(anyhow::anyhow!("Duplicate entry for {}", timestamp.1)); | ||
} | ||
current = None; | ||
} else { | ||
assert!(timestamp.0 == BenchmarkPosition::Start); | ||
current = Some(timestamp); | ||
} | ||
} | ||
Ok(results) | ||
} | ||
} | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
use wasm_bindgen_test::wasm_bindgen_test; | ||
#[cfg(target_arch = "wasm32")] | ||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); | ||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
#[tokio::main] | ||
pub async fn main() -> anyhow::Result<()> { | ||
initialize_tracing(None); | ||
bench_100_x_1kb().await?; | ||
bench_500_x_2kb().await?; | ||
bench_4_x_256kb().await?; | ||
bench_10_x_1mb().await?; | ||
bench_10000_x_1kb().await?; | ||
Ok(()) | ||
} | ||
|
||
#[cfg(target_arch = "wasm32")] | ||
pub fn main() { | ||
initialize_tracing(None); | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] | ||
async fn bench_100_x_1kb() -> anyhow::Result<()> { | ||
run_bench("100 x 1kb", 1024, 100, 0).await | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] | ||
async fn bench_500_x_2kb() -> anyhow::Result<()> { | ||
run_bench("500 x 2kb", 1024 * 2, 500, 0).await | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] | ||
async fn bench_4_x_256kb() -> anyhow::Result<()> { | ||
run_bench("4 x 256kb", 1024 * 256, 4, 0).await | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] | ||
async fn bench_10_x_1mb() -> anyhow::Result<()> { | ||
run_bench("10 x 1mb", 1024 * 1024, 10, 0).await | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] | ||
async fn bench_10000_x_1kb() -> anyhow::Result<()> { | ||
run_bench("10^3 x 1kb", 1024, 1024 * 10, 0).await | ||
} | ||
|
||
async fn run_bench( | ||
name: &str, | ||
chunk_size: u32, | ||
chunk_count: usize, | ||
memory_limit: u64, | ||
) -> anyhow::Result<()> { | ||
let mut bench = EncodingBenchmark::new(name); | ||
let provider = make_disposable_storage().await?; | ||
let db = SphereDb::new(&provider).await?; | ||
let total_size = chunk_size * <usize as TryInto<u32>>::try_into(chunk_count).unwrap(); | ||
assert!(total_size as u64 > memory_limit); | ||
|
||
let stream = make_stream(chunk_size, chunk_count); | ||
let reader = StreamReader::new(stream); | ||
bench.start("encode"); | ||
let cid = encode_stream(reader, &db, memory_limit).await?; | ||
bench.end("encode"); | ||
bench.start("decode"); | ||
let bytes_read = decode_stream(&cid, &db).await?; | ||
bench.end("decode"); | ||
|
||
assert_eq!(bytes_read, total_size); | ||
|
||
tracing::info!("{}: {:#?}", bench.name(), bench.results()); | ||
Ok(()) | ||
} | ||
|
||
fn make_stream<'a>( | ||
chunk_size: u32, | ||
chunk_count: usize, | ||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Unpin + 'a { | ||
Box::pin(try_stream! { | ||
for n in 1..=chunk_count { | ||
let chunk: Vec<u8> = vec![n as u8; <u32 as TryInto<usize>>::try_into(chunk_size).unwrap()]; | ||
yield Bytes::from(chunk); | ||
} | ||
}) | ||
} | ||
|
||
async fn encode_stream<S, R>(content: R, db: &SphereDb<S>, memory_limit: u64) -> anyhow::Result<Cid> | ||
where | ||
R: AsyncRead + Unpin, | ||
S: Storage, | ||
{ | ||
BodyChunkIpld::encode(content, db, Some(BufferStrategy::Limit(memory_limit))).await | ||
} | ||
|
||
async fn decode_stream<S>(cid: &Cid, db: &SphereDb<S>) -> anyhow::Result<u32> | ||
where | ||
S: Storage, | ||
{ | ||
let stream = BodyChunkIpld::decode(cid, db); | ||
tokio::pin!(stream); | ||
let mut bytes_read: u32 = 0; | ||
while let Some(chunk) = stream.try_next().await? { | ||
bytes_read += chunk.len() as u32; | ||
} | ||
Ok(bytes_read) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's
#![warn(missing_docs)]