1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 21:39:26 +00:00
actix-web/actix-web/MIGRATION-4.0.md

350 lines
15 KiB
Markdown
Raw Normal View History

2022-02-02 02:46:37 +00:00
# Migrating to 4.0.0
2022-02-19 17:05:54 +00:00
This guide walks you through the process of migrating from v3.x.y to v4.x.y.
If you are migrating to v4.x.y from an older version of Actix Web (v2.x.y or earlier), check out the other historical migration notes in this folder.
2022-02-02 02:46:37 +00:00
2022-02-19 17:05:54 +00:00
This document is not designed to be exhaustive - it focuses on the most significant changes coming in v4.
You can find an exhaustive changelog in [CHANGES.md](./CHANGES.md), complete of PR links. If you think that some of the changes that we omitted deserve to be called out in this document, please open an issue or submit a PR.
2022-02-02 03:42:07 +00:00
2022-02-19 17:05:54 +00:00
Headings marked with :warning: are **breaking behavioral changes**. They will probably not surface as compile-time errors though automated tests _might_ detect their effects on your app.
2022-02-02 02:46:37 +00:00
2022-02-02 03:09:33 +00:00
## Table of Contents:
2022-02-02 02:46:37 +00:00
2022-02-02 03:13:11 +00:00
- [MSRV](#msrv)
2022-02-15 00:54:12 +00:00
- [Tokio v1 Ecosystem](#tokio-v1-ecosystem)
2022-02-02 03:13:11 +00:00
- [Module Structure](#module-structure)
- [`NormalizePath` Middleware :warning:](#normalizepath-middleware-warning)
2022-02-08 16:53:09 +00:00
- [Server Settings :warning:](#server-settings-warning)
2022-02-02 03:13:11 +00:00
- [`FromRequest` Trait](#fromrequest-trait)
- [Compression Feature Flags](#compression-feature-flags)
- [`web::Path`](#webpath)
2022-02-09 12:31:06 +00:00
- [Rustls Crate Upgrade](#rustls-crate-upgrade)
- [Removed `awc` Client Re-export](#removed-awc-client-re-export)
- [Integration Testing Utils Moved To `actix-test`](#integration-testing-utils-moved-to-actix-test)
- [Header APIs](#header-apis)
2022-02-09 16:12:39 +00:00
- [Response Body Types](#response-body-types)
2022-02-09 12:31:06 +00:00
- [Middleware Trait APIs](#middleware-trait-apis)
- [`Responder` Trait](#responder-trait)
- [`App::data` Deprecation :warning:](#appdata-deprecation-warning)
- [Direct Dependency On `actix-rt` And `actix-service`](#direct-dependency-on-actix-rt-and-actix-service)
- [Server Must Be Polled :warning:](#server-must-be-polled-warning)
- [Guards API](#guards-api)
- [Returning `HttpResponse` synchronously](#returning-httpresponse-synchronously)
- [`#[actix_web::main]` and `#[tokio::main]`](#actixwebmain-and-tokiomain)
- [`web::block`](#webblock)
2022-02-02 03:09:33 +00:00
## MSRV
The MSRV of Actix Web has been raised from 1.42 to 1.54.
2022-02-15 00:54:12 +00:00
## Tokio v1 Ecosystem
2022-02-19 17:05:54 +00:00
Actix Web v4 is now underpinned by `tokio`'s v1 ecosystem.
`cargo` supports having multiple versions of the same crate within the same dependency tree, but `tokio` v1 does not interoperate transparently with its previous versions (v0.2, v0.1). Some of your dependencies might rely on `tokio`, either directly or indirectly - if they are using an older version of `tokio`, check if an update is available.
The following command can help you to identify these dependencies:
2022-02-15 00:54:12 +00:00
```sh
2022-02-19 17:05:54 +00:00
# Find all crates in your dependency tree that depend on `tokio`
# It also reports the different versions of `tokio` in your dependency tree.
2022-02-15 00:54:12 +00:00
cargo tree -i tokio
2022-02-19 17:05:54 +00:00
# if you depend on multiple versions of tokio, use this command to
# list the dependencies relying on a specific version of tokio:
2022-02-15 00:54:12 +00:00
cargo tree -i tokio:0.2.25
```
2022-02-02 03:09:33 +00:00
## Module Structure
2022-02-19 17:05:54 +00:00
Lots of modules have been re-organized in this release. If a compile error refers to "item XYZ not found in module..." or "module XYZ not found", check the [documentation on docs.rs](https://docs.rs/actix-web) to search for items' new locations.
2022-02-02 03:09:33 +00:00
2022-02-02 03:13:11 +00:00
## `NormalizePath` Middleware :warning:
2022-02-02 02:46:37 +00:00
2022-02-19 17:05:54 +00:00
The default `NormalizePath` behavior now strips trailing slashes by default.
This was the _documented_ behaviour in Actix Web v3, but the _actual_ behaviour differed - the discrepancy has now been fixed.
As a consequence of this change, routes defined with trailing slashes will become inaccessible when using `NormalizePath::default()`. Calling `NormalizePath::default()` will log a warning. We suggest to use `new` or `trim`.
2022-02-02 02:46:37 +00:00
```diff
2022-02-04 18:22:38 +00:00
- #[get("/test/")]
+ #[get("/test")]
2022-02-02 03:09:33 +00:00
async fn handler() {
2022-02-02 02:46:37 +00:00
2022-02-02 03:09:33 +00:00
App::new()
2022-02-04 18:22:38 +00:00
- .wrap(NormalizePath::default())
+ .wrap(NormalizePath::trim())
2022-02-02 02:46:37 +00:00
```
Alternatively, explicitly require trailing slashes: `NormalizePath::new(TrailingSlash::Always)`.
2022-02-08 16:53:09 +00:00
## Server Settings :warning:
Until Actix Web v4, the underlying `actix-server` crate used the number of available **logical** cores as the default number of worker threads. The new default is the number of [physical CPU cores available](https://github.com/actix/actix-net/commit/3a3d654c). For more information about this change, refer to [this analysis](https://github.com/actix/actix-web/issues/957).
If you notice performance regressions, please open a new issue detailing your observations.
2022-02-02 03:09:33 +00:00
## `FromRequest` Trait
2022-02-02 02:46:37 +00:00
2022-02-02 03:09:33 +00:00
The associated type `Config` of `FromRequest` was removed. If you have custom extractors, you can just remove this implementation and refer to config types directly, if required.
```diff
impl FromRequest for MyExtractor {
2022-02-04 18:22:38 +00:00
- type Config = ();
2022-02-02 03:09:33 +00:00
}
```
2022-02-02 02:46:37 +00:00
Consequently, the `FromRequest::configure` method was also removed. Config for extractors is still provided using `App::app_data` but should now be constructed in a standalone way.
2022-02-02 03:09:33 +00:00
## Compression Feature Flags
2022-02-02 02:46:37 +00:00
2022-02-19 17:05:54 +00:00
The `compress` feature flag has been split into more granular feature flags, one for each supported algorithm (brotli, gzip, zstd). By default, all compression algorithms are enabled. If you want to select specific compression codecs, the new flags are:
2022-02-02 02:46:37 +00:00
- `compress-brotli`
- `compress-gzip`
- `compress-zstd`
2022-02-02 03:09:33 +00:00
## `web::Path`
2022-02-19 17:05:54 +00:00
The inner field for `web::Path` is now private.
It was causing too many issues when used with inner tuple types due to its `Deref` implementation.
2022-02-02 03:09:33 +00:00
```diff
- async fn handler(web::Path((foo, bar)): web::Path<(String, String)>) {
+ async fn handler(params: web::Path<(String, String)>) {
+ let (foo, bar) = params.into_inner();
```
## Rustls Crate Upgrade
2022-02-19 17:05:54 +00:00
Actix Web now depends on version 0.20 of `rustls`. As a result, the server config builder has changed. [See the updated example project.](https://github.com/actix/examples/tree/master/https-tls/rustls/)
2022-02-02 03:42:07 +00:00
## Removed `awc` Client Re-export
2022-02-19 17:05:54 +00:00
Actix Web's sister crate `awc` is no longer re-exported through the `client` module. This allows `awc` to have its own release cadence - its breaking changes are no longer blocked by Actix Web's (more conservative) release schedule.
2022-02-02 03:42:07 +00:00
```diff
- use actix_web::client::Client;
+ use awc::Client;
```
2022-02-08 16:53:09 +00:00
## Integration Testing Utils Moved To `actix-test`
2022-02-02 03:42:07 +00:00
2022-02-19 17:05:54 +00:00
`TestServer` has been moved to its own crate, [`actix-test`](https://docs.rs/actix-test).
2022-02-02 03:42:07 +00:00
```diff
- use use actix_web::test::start;
+ use use actix_test::start;
```
2022-02-19 17:05:54 +00:00
`TestServer` previously lived in `actix_web::test`, but it depends on `awc` which is no longer part of Actix Web's public API (see above).
2022-02-02 03:42:07 +00:00
## Header APIs
2022-02-19 17:05:54 +00:00
Header related APIs have been standardized across all `actix-*` crates. The terminology now better matches the underlying `HeaderMap` naming conventions.
2022-02-08 16:53:09 +00:00
2022-02-19 17:05:54 +00:00
In short, "insert" always indicates that any existing headers with the same name are overridden, while "append" is used for adding with no removal (e.g. multi-valued headers).
2022-02-08 16:53:09 +00:00
For request and response builder APIs, the new methods provide a unified interface for adding key-value pairs _and_ typed headers, which can often be more expressive.
```diff
- .set_header("Api-Key", "1234")
+ .insert_header(("Api-Key", "1234"))
- .header("Api-Key", "1234")
+ .append_header(("Api-Key", "1234"))
- .set(ContentType::json())
+ .insert_header(ContentType::json())
```
2022-02-02 03:42:07 +00:00
2022-02-19 17:05:54 +00:00
We chose to deprecate most of the old methods instead of removing them immediately - the warning notes will guide you on how to update.
2022-02-09 16:12:39 +00:00
## Response Body Types
2022-02-02 03:42:07 +00:00
2022-02-19 17:05:54 +00:00
There have been a lot of changes to response body types. They are now more expressive and their purpose should be more intuitive.
2022-02-09 16:12:39 +00:00
2022-02-19 17:05:54 +00:00
We have boosted the quality and completeness of the documentation for all items in the [`body` module](https://docs.rs/actix-web/4/actix_web/body).
2022-02-09 16:12:39 +00:00
### `ResponseBody`
`ResponseBody` is gone. Its purpose was confusing and has been replaced by better components.
### `Body`
`Body` is also gone. In combination with `ResponseBody`, the API it provided was sub-optimal and did not encourage expressive types. Here are the equivalents in the new system (check docs):
- `Body::None` => `body::None::new()`
- `Body::Empty` => `()` / `web::Bytes::new()`
- `Body::Bytes` => `web::Bytes::from(...)`
- `Body::Message` => `.boxed()` / `BoxBody`
### `BoxBody`
2022-02-19 17:05:54 +00:00
`BoxBody` is a new type-erased body type. It's used for all error response bodies.
Creating a boxed body is best done by calling [`.boxed()`](https://docs.rs/actix-web/4/actix_web/body/trait.MessageBody.html#method.boxed) on a `MessageBody` type.
2022-02-09 16:12:39 +00:00
### `EitherBody`
2022-02-19 17:05:54 +00:00
`EitherBody` is a new "either" type that is particularly useful in middlewares that can bail early, returning their own response plus body type.
2022-02-09 16:12:39 +00:00
### Error Handlers
2022-02-02 03:42:07 +00:00
2022-02-09 16:12:39 +00:00
TODO In particular, folks seem to be struggling with the `ErrorHandlers` middleware because of this change and the obscured nature of `EitherBody` within its types.
2022-02-02 03:42:07 +00:00
## Middleware Trait APIs
2022-02-09 16:12:39 +00:00
This section builds upon guidance from the [response body types](#response-body-types) section.
2022-02-09 12:31:06 +00:00
2022-02-02 03:42:07 +00:00
TODO
TODO: Also write the Middleware author's guide.
## `Responder` Trait
2022-02-08 16:53:09 +00:00
The `Responder` trait's interface has changed. Errors should be handled and converted to responses within the `respond_to` method. It's also no longer async so the associated `type Future` has been removed; there was no compelling use case found for it. These changes simplify the interface and implementation a lot.
2022-02-02 03:42:07 +00:00
2022-02-09 16:12:39 +00:00
Now that more emphasis is placed on expressive body types, as explained in the [body types migration section](#response-body-types), this trait has introduced an associated `type Body`. The simplest migration will be to use `BoxBody` + `.map_into_boxed_body()` but if there is a more expressive type for your responder then try to use that instead.
2022-02-02 03:42:07 +00:00
2022-02-08 16:53:09 +00:00
```diff
impl Responder for &'static str {
- type Error = Error;
- type Future = Ready<Result<HttpResponse, Error>>;
+ type Body = &'static str;
- fn respond_to(self, req: &HttpRequest) -> Self::Future {
+ fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> {
let res = HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self);
- ok(res)
+ res
}
}
```
2022-02-02 03:42:07 +00:00
2022-02-09 12:31:06 +00:00
## `App::data` Deprecation :warning:
2022-02-02 03:42:07 +00:00
2022-02-19 17:05:54 +00:00
The `App::data` method is deprecated. Replace instances of this with `App::app_data`. Exposing both methods led to lots of confusion when trying to extract the data in handlers. Now, when using the `Data` wrapper, the type you put in to `app_data` is the same type you extract in handler arguments.
2022-02-02 03:42:07 +00:00
2022-02-08 16:53:09 +00:00
You may need to review the [guidance on shared mutable state](https://docs.rs/actix-web/4/actix_web/struct.App.html#shared-mutable-state) in order to migrate this correctly.
2022-02-02 03:42:07 +00:00
2022-02-08 16:53:09 +00:00
```diff
use actix_web::web::Data;
#[get("/")]
async fn handler(my_state: Data<MyState>) -> { todo!() }
HttpServer::new(|| {
- App::new()
- .data(MyState::default())
- .service(hander)
+ let my_state: Data<MyState> = Data::new(MyState::default());
+
+ App::new()
+ .app_data(my_state)
+ .service(hander)
})
```
## Direct Dependency On `actix-rt` And `actix-service`
2022-02-19 17:05:54 +00:00
Improvements to module management and re-exports have resulted in not needing direct dependencies on these underlying crates for the vast majority of cases. In particular:
- all traits necessary for creating middlewares are now re-exported through the `dev` modules;
- `#[actix_web::test]` now exists for async test definitions.
Relying on these re-exports will ease the transition to future versions of Actix Web.
2022-02-08 16:53:09 +00:00
```diff
- use actix_service::{Service, Transform};
+ use actix_web::dev::{Service, Transform};
```
```diff
- #[actix_rt::test]
+ #[actix_web::test]
async fn test_thing() {
```
## Server Must Be Polled :warning:
In order to _start_ serving requests, the `Server` object returned from `run` **must** be `poll`ed, `await`ed, or `spawn`ed. This was done to prevent unexpected behavior and ensure that things like signal handlers are able to function correctly when enabled.
For example, in this contrived example where the server is started and then the main thread is sent to sleep, the server will no longer be able to serve requests with v4.0:
```rust
#[actix_web::main]
async fn main() {
HttpServer::new(|| App::new().default_service(web::to(HttpResponse::Conflict)))
.bind(("127.0.0.1", 8080))
.unwrap()
.run();
thread::sleep(Duration::from_secs(1000));
}
```
2022-02-02 03:42:07 +00:00
## Guards API
2022-02-19 17:05:54 +00:00
Implementors of routing guards will need to use the modified interface of the `Guard` trait. The API is more flexible than before. See [guard module docs](https://docs.rs/actix-web/4/actix_web/guard/struct.GuardContext.html) for more details.
2022-02-02 03:42:07 +00:00
2022-02-08 16:53:09 +00:00
```diff
struct MethodGuard(HttpMethod);
2022-02-09 12:31:06 +00:00
2022-02-08 16:53:09 +00:00
impl Guard for MethodGuard {
- fn check(&self, request: &RequestHead) -> bool {
+ fn check(&self, ctx: &GuardContext<'_>) -> bool {
- request.method == self.0
+ ctx.head().method == self.0
}
}
```
## Returning `HttpResponse` synchronously
2022-02-08 15:24:35 +00:00
The implementation of `Future` for `HttpResponse` was removed because it was largely useless for all but the simplest handlers like `web::to(|| HttpResponse::Ok().finish())`. It also caused false positives on the `async_yields_async` clippy lint in reasonable scenarios. The compiler errors will looks something like:
```
web::to(|| HttpResponse::Ok().finish())
^^^^^^^ the trait `Handler<_>` is not implemented for `[closure@...]`
```
2022-02-17 19:13:03 +00:00
This form should be replaced with explicit async functions and closures:
```diff
- fn handler() -> HttpResponse {
+ async fn handler() -> HttpResponse {
HttpResponse::Ok().finish()
}
```
2022-02-08 15:24:35 +00:00
```diff
- web::to(|| HttpResponse::Ok().finish())
+ web::to(|| async { HttpResponse::Ok().finish() })
```
Or, for these extremely simple cases, utilise an `HttpResponseBuilder`:
```diff
- web::to(|| HttpResponse::Ok().finish())
+ web::to(HttpResponse::Ok)
```
2022-02-02 03:42:07 +00:00
2022-02-08 06:58:26 +00:00
## `#[actix_web::main]` and `#[tokio::main]`
2022-02-19 17:05:54 +00:00
Actix Web now works seamlessly with the primary way of starting a multi-threaded Tokio runtime, `#[tokio::main]`. Therefore, it is no longer necessary to spawn a thread when you need to run something alongside Actix Web that uses Tokio's multi-threaded mode; you can simply await the server within this context or, if preferred, use `tokio::spawn` just like any other async task.
2022-02-08 15:24:35 +00:00
For now, `actix` actor support (and therefore WebSocket support via `actix-web-actors`) still requires `#[actix_web::main]` so that a `System` context is created. Designs are being created for an alternative WebSocket interface that does not require actors that should land sometime in the v4.x cycle.
2022-02-09 12:31:06 +00:00
## `web::block`
The `web::block` helper has changed return type from roughly `async fn(fn() -> Result<T, E>) Result<T, BlockingError<E>>` to `async fn(fn() -> T) Result<T, BlockingError>`. That's to say that the blocking function can now return things that are not `Result`s and it does not wrap error types anymore. If you still need to return `Result`s then you'll likely want to use double `?` after the `.await`.
```diff
- let n: u32 = web::block(|| Ok(123)).await?;
+ let n: u32 = web::block(|| 123).await?;
- let n: u32 = web::block(|| Ok(123)).await?;
+ let n: u32 = web::block(|| Ok(123)).await??;
```