Skip to content

Switch on testing for the book; fix #6 #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@ language: rust
env:
- RUSTFLAGS="-D warnings"

before_script:
- rustup component add rustfmt

matrix:
fast_finish: true
include:
- rust: nightly
os: linux
env: BUILD_DOCS=1
env: BUILD_DOCS=1 BUILD_BOOK=1
- rust: nightly
os: osx
osx_image: xcode9.2
env: BUILD_DOCS=1
- rust: nightly-x86_64-pc-windows-msvc
os: windows

before_script:
- rustup component add rustfmt
- (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update)
- (test -x $HOME/.cargo/bin/mdbook || cargo install --vers "^0.3" mdbook)
- cargo install-update -a

script:
- cargo check --all --benches --bins --examples --tests
- cargo test --all
- if ![[ -n "$BUILD_BOOK" ]]; then cargo check --all --benches --bins --examples --tests && cargo test --all; fi
- if [[ -n "$BUILD_BOOK" ]]; then cargo test --all --benches --bins --examples --tests; fi
Copy link
Author

@ghost ghost Aug 20, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've had to modify the travis config to where, when the book should be built, we don't run cargo check but instead just run cargo test.

This might cause ci to not fail as quickly on the linux build but the problem is that running cargo check followed by cargo test produces two entries for async_std in ./target/debug/deps which then causes mdbook test to fail when trying to resolve extern crate async_std.

I don't know of another way to fix that issue. If this is an acceptable workaround then I think this PR is good to go.

- cargo fmt --all -- --check
- if [[ -n "$BUILD_DOCS" ]]; then cargo doc --features docs; fi
- if [[ -n "$BUILD_DOCS" ]]; then cargo doc --features docs; fi
- if [[ -n "$BUILD_BOOK" ]]; then mdbook build docs && mdbook test -L ./target/debug/deps docs; fi
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ docs = []
async-task = "1.0.0"
cfg-if = "0.1.9"
crossbeam-channel = "0.3.9"
futures-preview = "0.3.0-alpha.17"
futures-timer = "0.3.0"
lazy_static = "1.3.0"
log = { version = "0.4.8", features = ["kv_unstable"] }
Expand All @@ -37,6 +36,10 @@ num_cpus = "1.10.0"
pin-utils = "0.1.0-alpha.4"
slab = "0.4.2"

[dependencies.futures-preview]
version = "0.3.0-alpha.17"
features = ["async-await", "nightly"]

[dev-dependencies]
femme = "1.1.0"
tempdir = "0.3.7"
Expand Down
33 changes: 20 additions & 13 deletions docs/src/concepts/futures.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ Remember the talk about "deferred computation" in the intro? That's all it is. I

Let's have a look at a simple function, specifically the return value:

```rust
```rust,edition2018
# use std::{fs::File, io::{self, Read}};
#
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path)?;
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
contents
Ok(contents)
}
```

Expand All @@ -64,12 +66,14 @@ Note that this return value talks about the past. The past has a drawback: all d

But we wanted to abstract over *computation* and let someone else choose how to run it. That's fundamentally incompatible with looking at the results of previous computation all the time. So, let's find a type that *describes* a computation without running it. Let's look at the function again:

```rust
```rust,edition2018
# use std::{fs::File, io::{self, Read}};
#
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path)?;
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
contents
Ok(contents)
}
```

Expand All @@ -79,10 +83,11 @@ This is the moment where we could reach for [threads](https://en.wikipedia.org/w

What we are searching for is something that represents ongoing work towards a result in the future. Whenever we say "something" in Rust, we almost always mean a trait. Let's start with an incomplete definition of the `Future` trait:

```rust
```rust,edition2018
# use std::{pin::Pin, task::{Context, Poll}};
#
trait Future {
type Output;

fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output>;
}
```
Expand All @@ -105,14 +110,16 @@ Note that calling `poll` again after case 1 happened may result in confusing beh

While the `Future` trait has existed in Rust for a while, it was inconvenient to build and describe them. For this, Rust now has a special syntax: `async`. The example from above, implemented with `async-std`, would look like this:

```rust
use async_std::fs::File;

```rust,edition2018
# extern crate async_std;
# use async_std::{fs::File, io::Read};
# use std::io;
#
async fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path).await?;
let mut file = File::open(path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
contents
Ok(contents)
}
```

Expand Down
47 changes: 33 additions & 14 deletions docs/src/concepts/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ Now that we know what Futures are, we want to run them!

In `async-std`, the [`tasks`][tasks] module is responsible for this. The simplest way is using the `block_on` function:

```rust
use async_std::fs::File;
use async_std::task;

```rust,edition2018,no_run
# extern crate async_std;
# use async_std::{fs::File, io::Read, task};
# use std::io;
#
async fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
contents
Ok(contents)
}

fn main() {
Expand All @@ -31,24 +32,35 @@ fn main() {

This asks the runtime baked into `async_std` to execute the code that reads a file. Let's go one by one, though, inside to outside.

```rust
```rust,edition2018,no_run
# extern crate async_std;
# use async_std::{fs::File, io::Read, task};
# use std::io;
#
# async fn read_file(path: &str) -> Result<String, io::Error> {
# let mut file = File::open(path).await?;
# let mut contents = String::new();
# file.read_to_string(&mut contents).await?;
# Ok(contents)
# }
#
async {
let result = read_file("data.csv").await;
match result {
Ok(s) => println!("{}", s),
Err(e) => println!("Error reading file: {:?}", e)
}
}
};
```

This is an `async` *block*. Async blocks are necessary to call `async` functions, and will instruct the compiler to include all the relevant instructions to do so. In Rust, all blocks return a value and `async` blocks happen to return a value of the kind `Future`.

But let's get to the interesting part:

```rust

task::spawn(async { })

```rust,edition2018
# extern crate async_std;
# use async_std::task;
task::spawn(async { });
```

`spawn` takes a `Future` and starts running it on a `Task`. It returns a `JoinHandle`. Futures in Rust are sometimes called *cold* Futures. You need something that starts running them. To run a Future, there may be some additional bookkeeping required, e.g. whether it's running or finished, where it is being placed in memory and what the current state is. This bookkeeping part is abstracted away in a `Task`.
Expand All @@ -72,7 +84,9 @@ Tasks in `async_std` are one of the core abstractions. Much like Rust's `thread`

`Task`s are assumed to run _concurrently_, potentially by sharing a thread of execution. This means that operations blocking an _operating system thread_, such as `std::thread::sleep` or io function from Rust's `std` library will _stop execution of all tasks sharing this thread_. Other libraries (such as database drivers) have similar behaviour. Note that _blocking the current thread_ is not in and by itself bad behaviour, just something that does not mix well with the concurrent execution model of `async-std`. Essentially, never do this:

```rust
```rust,edition2018
# extern crate async_std;
# use async_std::task;
fn main() {
task::block_on(async {
// this is std::fs, which blocks
Expand All @@ -91,7 +105,9 @@ In case of `panic`, behaviour differs depending on whether there's a reasonable

In practice, that means that `block_on` propagates panics to the blocking component:

```rust
```rust,edition2018,should_panic
# extern crate async_std;
# use async_std::task;
fn main() {
task::block_on(async {
panic!("test");
Expand All @@ -106,7 +122,10 @@ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

While panicing a spawned task will abort:

```rust
```rust,edition2018,should_panic
# extern crate async_std;
# use async_std::task;
# use std::time::Duration;
task::spawn(async {
panic!("test");
});
Expand Down
12 changes: 6 additions & 6 deletions docs/src/patterns/small-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ A collection of small, useful patterns.

`async-std` doesn't provide a `split()` method on `io` handles. Instead, splitting a stream into a read and write half can be done like this:

```rust
use async_std::io;

async fn echo(stream: io::TcpStream) {
```rust,edition2018
# extern crate async_std;
use async_std::{io, net::TcpStream};
async fn echo(stream: TcpStream) {
let (reader, writer) = &mut (&stream, &stream);
io::copy(reader, writer).await?;
io::copy(reader, writer).await;
}
```
```
2 changes: 1 addition & 1 deletion docs/src/security/policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ This policy is adapted from the [Rust project](https://www.rust-lang.org/policie

## PGP Key

```
```text
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBF1Wu/ABCADJaGt4HwSlqKB9BGHWYKZj/6mTMbmc29vsEOcCSQKo6myCf9zc
Expand Down
57 changes: 41 additions & 16 deletions docs/src/tutorial/accept_loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@

Let's implement the scaffold of the server: a loop that binds a TCP socket to an address and starts accepting connections.


First of all, let's add required import boilerplate:

```rust
```rust,edition2018
# extern crate async_std;
use std::net::ToSocketAddrs; // 1

use async_std::{
prelude::*, // 2
task, // 3
task, // 3
net::TcpListener, // 4
};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; // 5
```

1. `async_std` uses `std` types where appropriate.
We'll need `ToSocketAddrs` to specify address to listen on.
We'll need `ToSocketAddrs` to specify address to listen on.
2. `prelude` re-exports some traits required to work with futures and streams.
3. The `task` module roughly corresponds to the `std::thread` module, but tasks are much lighter weight.
A single thread can run many tasks.
Expand All @@ -27,10 +26,18 @@ type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>
To propagate the errors, we will use a boxed error trait object.
Do you know that there's `From<&'_ str> for Box<dyn Error>` implementation in stdlib, which allows you to use strings with `?` operator?


Now we can write the server's accept loop:

```rust
```rust,edition2018
# extern crate async_std;
# use async_std::{
# net::TcpListener,
# prelude::Stream,
# };
# use std::net::ToSocketAddrs;
#
# type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#
async fn server(addr: impl ToSocketAddrs) -> Result<()> { // 1
let listener = TcpListener::bind(addr).await?; // 2
let mut incoming = listener.incoming();
Expand All @@ -48,19 +55,37 @@ async fn server(addr: impl ToSocketAddrs) -> Result<()> { // 1
Mirroring API of `std` is an explicit design goal of `async_std`.
3. Here, we would like to iterate incoming sockets, just how one would do in `std`:

```rust
let listener: std::net::TcpListener = unimplemented!();
for stream in listener.incoming() {

}
```
```rust,edition2018,should_panic
let listener: std::net::TcpListener = unimplemented!();
for stream in listener.incoming() {
}
```

Unfortunately this doesn't quite work with `async` yet, because there's no support for `async` for-loops in the language yet.
For this reason we have to implement the loop manually, by using `while let Some(item) = iter.next().await` pattern.
Unfortunately this doesn't quite work with `async` yet, because there's no support for `async` for-loops in the language yet.
For this reason we have to implement the loop manually, by using `while let Some(item) = iter.next().await` pattern.

Finally, let's add main:

```rust
```rust,edition2018,no_run
# extern crate async_std;
# use async_std::{
# net::TcpListener,
# prelude::Stream,
# task,
# };
# use std::net::ToSocketAddrs;
#
# type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#
# async fn server(addr: impl ToSocketAddrs) -> Result<()> { // 1
# let listener = TcpListener::bind(addr).await?; // 2
# let mut incoming = listener.incoming();
# while let Some(stream) = incoming.next().await { // 3
# // TODO
# }
# Ok(())
# }
#
fn main() -> Result<()> {
let fut = server("127.0.0.1:8080");
task::block_on(fut)
Expand Down
Loading