Skip to content

Commit

Permalink
docs: Refactor examples (#109)
Browse files Browse the repository at this point in the history
Signed-off-by: Xuanwo <github@xuanwo.io>
  • Loading branch information
Xuanwo authored Aug 26, 2024
1 parent e64b419 commit a1d62d9
Show file tree
Hide file tree
Showing 19 changed files with 260 additions and 190 deletions.
12 changes: 12 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ jobs:
RUST_LOG: DEBUG
RUST_BACKTRACE: full

nightly-unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: rustup toolchain install nightly
- name: Test
run: cargo +nightly test --all-features
env:
RUST_LOG: DEBUG
RUST_BACKTRACE: full
RUSTDOCFLAGS: "--cfg docsrs"

wasm-unit:
runs-on: ubuntu-latest
steps:
Expand Down
9 changes: 9 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ name = "backon"
repository = "https://github.com/Xuanwo/backon"
version = "0.5.0"

[package.metadata.docs.rs]
all-features = true
targets = [
"x86_64-unknown-linux-gnu",
"x86_64-apple-darwin",
"x86_64-pc-windows-msvc",
"wasm32-unknown-unknown",
]

[features]
gloo-timers-sleep = ["dep:gloo-timers", "gloo-timers/futures"]
tokio-sleep = ["dep:tokio", "tokio/time"]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

<img src="./.github/assets/logo.jpeg" alt="BackON" width="38.2%"/>

BackON: Make **retry** like a built-in feature provided by Rust.
Make **retry** like a built-in feature provided by Rust.

- **Simple**: Just like a built-in feature: `your_fn.retry(ExponentialBuilder::default()).await`.
- **Flexible**: Supports both blocking and async functions.
Expand Down
23 changes: 0 additions & 23 deletions examples/async.rs

This file was deleted.

21 changes: 0 additions & 21 deletions examples/blocking.rs

This file was deleted.

24 changes: 0 additions & 24 deletions examples/sqlx.rs

This file was deleted.

1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
edition = "2021"
reorder_imports = true

# format_code_in_doc_comments = true
# imports_granularity = "Item"
# group_imports = "StdExternalCrate"
19 changes: 19 additions & 0 deletions src/docs/examples/basic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Retry an async function.

```rust
use backon::ExponentialBuilder;
use backon::Retryable;
use anyhow::Result;

async fn fetch() -> Result<String> {
Ok("Hello, Workd!".to_string())
}

#[tokio::main]
async fn main() -> Result<()> {
let content = fetch.retry(ExponentialBuilder::default()).await?;

println!("fetch succeeded: {}", content);
Ok(())
}
```
15 changes: 7 additions & 8 deletions examples/closure.rs → src/docs/examples/closure.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// For more examples, please see: https://docs.rs/backon/#examples
Retry an closure.

// this example does not run on wasm32-unknown-unknown
#[cfg(not(target_arch = "wasm32"))]
fn main() -> anyhow::Result<()> {
use backon::BlockingRetryable;
```rust
use backon::ExponentialBuilder;
use backon::Retryable;
use backon::BlockingRetryable;

fn main() -> anyhow::Result<()> {
let var = 42;
// `f` can use input variables
let f = || Ok::<u32, anyhow::Error>(var);
Expand All @@ -13,6 +14,4 @@ fn main() -> anyhow::Result<()> {

Ok(())
}

#[cfg(target_arch = "wasm32")]
fn main() {}
```
22 changes: 22 additions & 0 deletions src/docs/examples/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Examples of using backon.
#[doc = include_str!("basic.md")]
pub mod basic {}

#[doc = include_str!("closure.md")]
pub mod closure {}

#[doc = include_str!("sqlx.md")]
pub mod sqlx {}

#[doc = include_str!("with_args.md")]
pub mod with_args {}

#[doc = include_str!("with_mut_self.md")]
pub mod with_mut_self {}

#[doc = include_str!("with_self.md")]
pub mod with_self {}

#[doc = include_str!("with_specific_error.md")]
pub mod with_specific_error {}
23 changes: 23 additions & 0 deletions src/docs/examples/sqlx.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Retry sqlx operations.

```rust
use backon::Retryable;
use anyhow::Result;
use backon::ExponentialBuilder;

#[tokio::main]
async fn main() -> Result<()> {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(5)
.connect("sqlite::memory:")
.await?;

let row: (i64,) = (|| sqlx::query_as("SELECT $1").bind(150_i64).fetch_one(&pool))
.retry(ExponentialBuilder::default())
.await?;

assert_eq!(row.0, 150);

Ok(())
}
```
24 changes: 24 additions & 0 deletions src/docs/examples/with_args.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Retry function with args.

It's a pity that rust doesn't allow us to implement `Retryable` for async function with args. So we have to use a workaround to make it work.

```rust
use anyhow::Result;
use backon::ExponentialBuilder;
use backon::Retryable;

async fn fetch(url: &str) -> Result<String> {
Ok(reqwest::get(url).await?.text().await?)
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let content = (|| async { fetch("https://www.rust-lang.org").await })
.retry(ExponentialBuilder::default())
.when(|e| e.to_string() == "retryable")
.await?;

println!("fetch succeeded: {}", content);
Ok(())
}
```
36 changes: 36 additions & 0 deletions src/docs/examples/with_mut_self.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Retry an async function which takes `&mut self` as receiver.

This is a bit more complex since we need to capture the receiver in the closure with ownership. backon supports this use case by `RetryableWithContext`.

```rust
use anyhow::Result;
use backon::ExponentialBuilder;
use backon::RetryableWithContext;

struct Test;

impl Test {
async fn fetch(&mut self, url: &str) -> Result<String> {
Ok(reqwest::get(url).await?.text().await?)
}
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let test = Test;

let (_, result) = (|mut v: Test| async {
let res = v.fetch("https://www.rust-lang.org").await;
// Return input context back.
(v, res)
})
.retry(ExponentialBuilder::default())
// Passing context in.
.context(test)
.when(|e| e.to_string() == "retryable")
.await;

println!("fetch succeeded: {}", result.unwrap());
Ok(())
}
```
27 changes: 27 additions & 0 deletions src/docs/examples/with_self.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Retry an async function which takes `&self` as receiver.

```rust
use anyhow::Result;
use backon::ExponentialBuilder;
use backon::Retryable;

struct Test;

impl Test {
async fn fetch(&self, url: &str) -> Result<String> {
Ok(reqwest::get(url).await?.text().await?)
}
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let test = Test;
let content = (|| async { test.fetch("https://www.rust-lang.org").await })
.retry(ExponentialBuilder::default())
.when(|e| e.to_string() == "retryable")
.await?;

println!("fetch succeeded: {}", content);
Ok(())
}
```
21 changes: 21 additions & 0 deletions src/docs/examples/with_specific_error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Retry with specify retryable error by `when`.

```rust
use anyhow::Result;
use backon::ExponentialBuilder;
use backon::Retryable;

async fn fetch() -> Result<String> {
Ok("Hello, Workd!".to_string())
}

#[tokio::main]
async fn main() -> Result<()> {
let content = fetch
.retry(ExponentialBuilder::default())
.when(|e| e.to_string() == "retryable")
.await?;
println!("fetch succeeded: {}", content);
Ok(())
}
```
3 changes: 3 additions & 0 deletions src/docs/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! Docs for the backon crate, like examples.
pub mod examples;
Loading

0 comments on commit a1d62d9

Please sign in to comment.