Commit Graph

60 Commits

Author SHA1 Message Date
Sergio Benitez 02011a1307 Clean up codebase: fix reasonable clippy warnings.
This commit is a codebase-wide cleanup driven by clippy warnings. In
addition to fixing every reasonable warning, the following new
functionality was introduced:

  * `Accept::new()` now takes any `T: Into<QMediaType>` iterator.
  * `TempFile::is_empty()` was added.
  * `HeaderMap` now implements `IntoIterator`.

This commit makes the following breaking changes:

  * The `IntoCollection` trait is gone. Generics previously bound by the
    trait are now bound by `IntoIterator`. This affects:
    - `Accept::new()`
    - `ContentType::with_params()`
    - `Permission::{allow, allowed}()`
  * `MediaType`, `QMediaType`, and `Allow` implement `IntoIterator`,
    enabling most existing code to continue working without change.
  * The inherent `HeaderMap::into_iter()` method was removed.
  * The `Ok` variant in ErrorKind::Liftoff` is now `Box<Rocket<Orbit>>`.
2024-03-20 00:47:38 -07:00
Sergio Benitez 78aad3aa95 Fix 'PasteId' 'use' in pastebin tutorial. 2022-05-08 18:30:13 -05:00
Sergio Benitez fccb5759db Revamp pastebin tutorial for Rocket v0.5.
Closes #1756.
2022-05-08 01:57:49 -05:00
Konrad Borowski 4d258739f5 Migrate Rocket to Rust 2021 edition. 2022-04-19 18:35:38 -07:00
Sergio Benitez cc0621626b Prefix 'content' responder names with 'Raw'.
The primary aim of this commit is to reduce confusion between
'content::Json' and 'rocket::serde::json::Json' be renaming the former
to 'content::RawJson'. The complete changes in this PR are:

  * All responders in the 'content' module are prefixed with 'Raw'.
  * The 'content::Custom' responder was removed entirely.
  * The 'Plain' responder is now 'RawText'.
  * The 'content' API docs point to the 'serde' responders.
  * The docs and examples were updated accordingly.
2021-07-20 02:09:11 -07:00
Sergio Benitez 1a42009e9f Fix various generated and direct clippy warnings. 2021-06-08 13:27:09 -07:00
Sergio Benitez 4c6562cd29 Drop 'Data' after sending a response, not before.
This allows responses to be sent to the client even when data is only
partially read, significantly improving the experience for the client
from one with a "connection closed" error to one with a proper response.
The consequence is a lifetime in 'Data'.

Though other non-lifetime-introducing solutions exist, the introduction
of a lifetime to 'Data' is a longstanding desire as it prevents
smuggling 'Data' into a longer-lived context. Use of 'Data' in that
context was unspecified with various runtime consequences. The addition
of a lifetime bound by the request prevents this error statically.

In summary, the changes are:
  * Clients receive responses even when data isn't fully read.
  * 'Data' becomes 'Data<'r>'. 'FromData' changes accordingly.
  * Route 'Outcome's are strictly tied to the request lifetime.

Tangentially, the invalid length form field validation error message has
improved to format length in byte units if it exceeds 1024.
2021-06-08 13:26:16 -07:00
Sergio Benitez fa3e0334c1 Overhaul URI types, parsers, 'uri!' macro.
This commit entirely rewrites Rocket's URI parsing routines and
overhauls the 'uri!' macro resolving all known issues and removing any
potential limitations for compile-time URI creation. This commit:

  * Introduces a new 'Reference' URI variant for URI-references.
  * Modifies 'Redirect' to accept 'TryFrom<Reference>'.
  * Introduces a new 'Asterisk' URI variant for parity.
  * Allows creation of any URI type from a string literal via 'uri!'.
  * Enables dynamic/static prefixing/suffixing of route URIs in 'uri!'.
  * Unifies 'Segments' and 'QuerySegments' into one generic 'Segments'.
  * Consolidates URI formatting types/traits into a 'uri::fmt' module.
  * Makes APIs more symmetric across URI types.

It also includes the following less-relevant changes:

  * Implements 'FromParam' for a single-segment 'PathBuf'.
  * Adds 'FileName::is_safe()'.
  * No longer reparses upstream request URIs.

Resolves #842.
Resolves #853.
Resolves #998.
2021-05-19 18:47:11 -07:00
Sergio Benitez d03a07b183 Retrieve managed state via a borrow: '&State<T>'.
This has the following positive effects:

  1) The lifetime retrieved through 'Deref' is now long-lived.
  2) An '&State<T>` can be created via an '&T'.
  3) '&State<T>' is shorter to type than 'State<'_, T>'.
2021-05-11 08:58:16 -05:00
Sergio Benitez ad36b769bc Rename 'rocket::ignite()' to 'rocket::build()'.
...because loading up a Rocket while it's ignited is a bad idea.

More seriously, because 'Rocket.ignite()' will become an "execute
everything up to here" method.
2021-04-08 01:07:52 -07:00
Sergio Benitez 50c9e88cf9 Completely revamp, redo examples.
The new examples directory...

  * Contains a `README.md` explaining each example.
  * Consolidates examples into more complete chunks.
  * Is just better.

Resolves #1447.
2021-04-07 23:09:05 -07:00
Sergio Benitez 17dd8dafd0 Move examples to their own workspace.
This allows us to test all of the "core" crates (and the guide) by
testing the root workspace, and all of the examples by testing in the
examples workspace.
2021-03-09 21:57:30 -08:00
Sergio Benitez 63a14525d8 UTF-8 routes. Forms revamp. Temp files. Capped.
So. Many. Changes.

This is an insane commit: simultaneously one of the best (because of all
the wonderful improvements!) and one of the worst (because it is just
massive) in the project's history.

Routing:
  * All UTF-8 characters are accepted everywhere in route paths. (#998)
  * `path` is now `uri` in `route` attribute: `#[route(GET, path = "..")]`
    becomes `#[route(GET, uri = "..")]`.

Forms Revamp
  * All form related types now reside in a new `form` module.
  * Multipart forms are supported. (resolves #106)
  * Collections are supported in forms and queries. (resolves #205)
  * Nested structures in forms and queries are supported. (resolves #313)
  * Form fields can be ad-hoc validated with `#[field(validate = expr)]`.
  * `FromFormValue` is now `FromFormField`, blanket implements `FromForm`.
  * Form field values are always percent-decoded apriori.

Temporary Files
  * A new `TempFile` data and form guard allows streaming data directly to a
    file which can then be persisted.
  * A new `temp_dir` config parameter specifies where to store `TempFile`.
  * The limits `file` and `file/$ext`, where `$ext` is the file extension,
    determines the data limit for a `TempFile`.

Capped
  * A new `Capped` type is used to indicate when data has been truncated due to
    incoming data limits. It allows checking whether data is complete or
    truncated.
  * `DataStream` methods return `Capped` types.
  * `DataStream` API has been revamped to account for `Capped` types.
  * Several `Capped<T>` types implement `FromData`, `FromForm`.
  * HTTP 413 (Payload Too Large) errors are now returned when data limits are
    exceeded. (resolves #972)

Hierarchical Limits
  * Data limits are now hierarchical, delimited with `/`. A limit of `a/b/c`
    falls back to `a/b` then `a`.

Core
  * `&RawStr` no longer implements `FromParam`.
  * `&str` implements `FromParam`, `FromData`, `FromForm`.
  * `FromTransformedData` was removed.
  * `FromData` gained a lifetime for use with request-local data.
  * The default error HTML is more compact.
  * `&Config` is a request guard.
  * The `DataStream` interface was entirely revamped.
  * `State` is only exported via `rocket::State`.
  * A `request::local_cache!()` macro was added for storing values in
    request-local cache without consideration for type uniqueness by using a
    locally generated anonymous type.
  * `Request::get_param()` is now `Request::param()`.
  * `Request::get_segments()` is now `Request::segments()`, takes a range.
  * `Request::get_query_value()` is now `Request::query_value()`, can parse any
    `FromForm` including sequences.
  * `std::io::Error` implements `Responder` like `Debug<std::io::Error>`.
  * `(Status, R)` where `R: Responder` implements `Responder` by overriding the
    `Status` of `R`.
  * The name of a route is printed first during route matching.
  * `FlashMessage` now only has one lifetime generic.

HTTP
  * `RawStr` implements `serde::{Serialize, Deserialize}`.
  * `RawStr` implements _many_ more methods, in particular, those related to the
    `Pattern` API.
  * `RawStr::from_str()` is now `RawStr::new()`.
  * `RawStr::url_decode()` and `RawStr::url_decode_lossy()` only allocate as
    necessary, return `Cow`.
  * `Status` implements `Default` with `Status::Ok`.
  * `Status` implements `PartialEq`, `Eq`, `Hash`, `PartialOrd`, `Ord`.
  * Authority and origin part of `Absolute` can be modified with new
    `Absolute::{with,set}_authority()`, `Absolute::{with,set}_origin()` methods.
  * `Origin::segments()` was removed in favor of methods split into query and
    path parts and into raw and decoded versions.
  * The `Segments` iterator is smarter, returns decoded `&str` items.
  * `Segments::into_path_buf()` is now `Segments::to_path_buf()`.
  * A new `QuerySegments` is the analogous query segment iterator.
  * Once set, `expires` on private cookies is not overwritten. (resolves #1506)
  * `Origin::path()` and `Origin::query()` return `&RawStr`, not `&str`.

Codegen
  * Preserve more spans in `uri!` macro.
  * Preserve spans `FromForm` field types.
  * All dynamic parameters in a query string must typecheck as `FromForm`.
  * `FromFormValue` derive removed; `FromFormField` added.
  * The `form` `FromForm` and `FromFormField` field attribute is now named
    `field`. `#[form(field = ..)]` is now `#[field(name = ..)]`.

Contrib
  * `Json` implements `FromForm`.
  * `MsgPack` implements `FromForm`.
  * The `json!` macro is exported as `rocket_contrib::json::json!`.
  * Added clarifying docs to `StaticFiles`.

Examples
  * `form_validation` and `form_kitchen_sink` removed in favor of `forms`.
  * The `hello_world` example uses unicode in paths.
  * The `json` example only allocates as necessary.

Internal
  * Codegen uses new `exports` module with the following conventions:
    - Locals starts with `__` and are lowercased.
    - Rocket modules start with `_` and are lowercased.
    - `std` types start with `_` and are titlecased.
    - Rocket types are titlecased.
  * A `header` module was added to `http`, contains header types.
  * `SAFETY` is used as doc-string keyword for `unsafe` related comments.
  * The `Uri` parser no longer recognizes Rocket route URIs.
2021-03-04 01:51:21 -08:00
Jeb Rosen 9d45e786bb Update 'rand' dependency to 0.8. 2021-02-28 16:34:38 -08:00
Sergio Benitez 5d9035ddc1 Keep an op-log for sync 'CookieJar'.
In brief, this commit:

  * Updates to the latest upstream 'cookie', fixing a memory leak.
  * Make changes to 'CookieJar' observable only through 'pending()'.
  * Deprecates 'Client::new()' in favor of 'Client::tracked()'.
  * Makes 'dispatch()' on tracked 'Client's synchronize on cookies.
  * Makes 'Client::untracked()' actually untracked.

This commit updates to the latest 'cookie' which removes support for
'Sync' cookie jars. Instead of relying on 'cookie', this commit
implements an op-log based 'CookieJar' which internally keeps track of
changes. The API is such that changes are only observable through
specialized '_pending()' methods.
2020-10-14 21:37:16 -07:00
Sergio Benitez 549c9241c4 Require data limits on 'Data::open()'.
Closes #1325.
2020-08-06 02:46:04 -05:00
Sergio Benitez adc79016cd Rearrange top-level exports. Use '#[launch]'.
This commits makes the following high-level changes:

  * 'ShutdownHandle' is renamed to 'Shutdown'.
  * 'Rocket::shutdown_handle()' is renamed to 'Rocket::shutdown()'.
  * '#[launch]` is preferred to '#[rocket::launch]'.
  * Various docs phrasings are improved.
  * Fixed various broken links in docs.

This commits rearranges top-level exports as follows:

  * 'shutdown' module is no longer exported.
  * 'Shutdown' is exported from the crate root.
  * 'Outcome' is not longer exported from the root.
  * 'Handler', 'ErrorHandler' are no longer exported from the root.
2020-07-22 16:10:02 -07:00
Necmettin Karakaya fde6eda915 Fix various typos throughout the codebase. 2020-07-22 12:56:01 -07:00
Sergio Benitez 62355b424f Remove use of stable 'proc_macro_hygiene' feature. 2020-07-11 10:48:08 -07:00
Jeb Rosen 114a733d70 Use 'tokio::fs::File' in the 'pastebin' example. 2020-07-11 10:07:37 -07:00
Jeb Rosen 06975bfaea Use the blocking testing API everywhere.
Co-authored-by: Sergio Benitez <sb@sergio.bz>
2020-07-11 09:24:30 -07:00
Sergio Benitez 03127f4dae Add blocking variant of 'local'.
This commit adds the 'local::blocking' module and moves the existing
asynchronous testing to 'local::asynchronous'. It also includes several
changes to improve the local API, bringing it to parity (and beyond)
with master. These changes are:

  * 'LocalRequest' implements 'Clone'.
  * 'LocalResponse' doesn't implement 'DerefMut<Target=Response>'.
    Instead, direct methods on the type, such as 'into_string()', can
    be used to read the 'Response'.
  * 'Response::body()' returns an '&ResponseBody' as opposed to '&mut
    ResponseBody', which is returned by a new 'Response::body_mut()'.
  * '&ResponseBody' implements 'known_size()` to retrieve a body's size,
    if it is known.

Co-authored-by: Jeb Rosen <jeb@jebrosen.com>
2020-07-11 09:24:30 -07:00
Sergio Benitez 12308b403f Add '#[rocket::launch]' attribute.
The attribute is applied everywhere it can be across the codebase and is
the newly preferred method for launching an application. This commit
also makes '#[rocket::main]` stricter by warning when it is applied to
functions other than 'main'.
2020-07-11 09:24:29 -07:00
Jeb Rosen bc1b90cbdb Add '#[rocket::main]' attribute and make 'launch()' an 'async fn'.
'#[rocket::main]' works like '#[rocket::async_test]', but it uses
tokio's multithreaded scheduler.
2020-07-11 09:24:29 -07:00
Jeb Rosen b0238e5110 Make 'Fairing::on_attach()' async.
This transitively requires that 'Rocket::inspect()', 'Client::new()',
and 'Client::untracked()' also become async.
2020-07-11 09:24:29 -07:00
Jeb Rosen 7c4cd068d1 Update for rust-lang/rust#64856.
Raise the nightly version to one that accepts '...(format!(...)).await'.

This additionally reverts commit bdbf80f2da.
2020-07-11 09:24:29 -07:00
Jeb Rosen 62a99e9e49 Fix a minor compilation error, possibly caused by rust-lang/rust#64292. 2020-07-11 09:24:28 -07:00
Jacob Pratt cd6a80c230 Implement an API to request a graceful shutdown.
Additionally listen for Ctrl-C as a shutdown signal by default.
2020-07-11 09:24:28 -07:00
Jeb Rosen 1f0577bfc5 Update remaining examples for async. 2020-07-11 09:24:28 -07:00
Jeb Rosen 560f0977d3 Revamp testing system for async.
* body_string_wait and body_bytes_wait are removed; use `.await` instead
* `dispatch()` is now an async fn and must be .await-ed
* Add `#[rocket::async_test]` macro, similar in purpose to `tokio::test`
* Tests now use either `rocket::async_test(async { })` or
  `#[rocket::async_test]` in order to `.await` the futures returned
  from `dispatch()` and `body_{string,bytes}()`
* Update 'test.sh' to reflect the tests that should be passing.

Broken:

* Cloned dispatch and mut_dispatch() with a live previous response now both fail, due to a (partial) check for mutable aliasing in LocalRequest.
* Some tests are still failing and need example-specific changes.
2020-07-11 09:24:28 -07:00
Jacob Pratt e44c5896b8 Remove stabilized 'async_await' feature gate and update the minimum nightly version. 2020-07-11 09:24:28 -07:00
Jeb Rosen bc404f1f6d Use 'body_string_wait' in all example tests. 2020-07-11 09:24:28 -07:00
Jeb Rosen 5d439bafc0 Convert core to async and add support for async routes.
Minimum rustc bump required for rust-lang/rust#61775
2020-07-11 09:24:28 -07:00
gcarq 86d0bdddb2 Replace manual ASCII checks with 'std::char' calls. 2020-06-22 05:07:14 -07:00
Razican f4bb8bb511 Update depedencies:
* contrib: 'rmp-serde', 'tera', 'memcache', 'mysql', 'postgres', 'redis'.
* examples: 'parking-lot', 'rand'
2020-01-19 11:01:11 -08:00
Sergio Benitez 2537a1164d Remove 'Result' specialization. Add 'Debug' responder.
This removes all uses of specialization in Rocket.
2019-09-09 21:57:33 -07:00
Jeb Rosen 3e4f8453ce Remove use of the 'decl_macro' feature.
Also removes one internal use in the 'typed-uris' codegen test.
2019-07-19 11:39:56 -07:00
Jeb Rosen d9f989a496 Migrate all examples to Rust 2018. 2019-06-25 11:30:43 -07:00
Sergio Benitez fbcb99669e Update deprecated 'trim_right()' to 'trim_end()'. 2019-02-06 19:39:44 -08:00
Sergio Benitez 76c830a467 Update 'base64', 'crossbeam', 'rand' dependencies. 2018-11-18 03:47:12 -08:00
Sergio Benitez 2839aca8ce Update features for latest nightly. 2018-10-09 04:31:09 -07:00
Sergio Benitez 61f107f550 Reimplement route attribute as a proc-macro.
This commits also implement the query reform from #608. It also consists
of many, many breaking changes. Among them are:

  * Query parts in route paths use new query reform syntax.
  * Routing for queries is now lenient.
    - Default ranking has changed to reflect query reform.
  * Format routing matching has been fixed.
    - Routes with formats matching "accept" will always collide.
    - Routes with formats matching "content-type" require requests to
      have an equivalent content-type header to match.
    - Requests with imprecise content-types are treated as not having a
      content-type.
  * Generated routes and catchers respect visibility modifiers.
  * Raw getter methods from request were renamed and retooled.
    - In particular, the index parameter is based on segments in the
      route path, not dynamic parameters.
  * The method-based attributes no longer accept a keyed 'path'.
  * The 'rocket_codegen' crate is gone and will no longer be public.
  * The 'FormItems' iterator emits values of type 'FormItem'.
    - The internal form items' string can no longer be retrieved.
  * In general, routes are more strictly validated.
  * Logging from codegen now funnels through logging infrastructure.
  * Routing has been optimized by caching routing metadata.

Resolves #93.
Resolves #608.
Resolves #693.
Resolves #476.
2018-10-09 04:18:04 -07:00
jeb 8e779610c4 Reimplement 'routes!' and 'catchers!' as proc-macros. 2018-09-16 18:52:23 -07:00
Sean Stangl 9bf585496c Apply more Clippy suggestions. 2018-08-11 23:41:35 -07:00
Sergio Benitez 9405fc9055 Update 'rand' dependency in 'pastebin' example. 2018-07-22 21:59:40 -07:00
Sergio Benitez f171dc9d09 Reorganize repository.
The directory structure has changed to better isolate crates serving
core and contrib. The new directory structure is:

  contrib/
    lib/ - the contrib library
  core/
    lib/ - the core Rocket library
    codegen/ - the "compile extension" codegen library
    codegen_next/ - the new proc-macro library
  examples/ - unchanged
  scripts/ - unchanged
  site/ - unchanged

This commit also removes the following files:

  appveyor.yml - AppVeyor (Rust on Windows) is far too spotty for use
  rustfmt.toml - rustfmt is, unfortunately, not mature enough for use

Finally, all example Cargo crates were marked with 'publish = false'.
2018-06-03 18:44:38 +02:00
Sergio Benitez 65baa83fb4 Update dependencies.
* 'memchr' to 2.0
  * 'base64' to 0.9
  * 'smallvec' to 0.6
  * 'lazy_static' to 1.0

Update example dependencies.

  * 'rand' to 0.4
  * 'parking_lot' to 0.5
2018-01-05 02:00:26 -08:00
Sergio Benitez 084481a84e Initial implementation of typed URIs.
This is a breaking change. All Rocket applications using code
generation must now additionally declare usage of the 'decl_macro'
feature.
2017-09-14 22:10:25 -07:00
Rolf Sievers 3a76fe03db Improve commentary on collisions in pastebin example. 2017-08-13 02:56:23 -07:00
Sergio Benitez b8ba7b855f Remove Session in favor of private cookies. New testing API.
Sessions
--------

This commit removes the `Session` type in favor of methods on the
`Cookies` types that allow for adding, removing, and getting private
(signed and encrypted) cookies. These methods provide a superset of
the functionality of `Session` while also being a minimal addition to
the existing API. They can be used to implement the previous `Session`
type as well as other forms of session storage. The new methods are:

  * Cookie::add_private(&mut self, Cookie)
  * Cookie::remove_private(&mut self, Cookie)
  * Cookie::get_private(&self, &str)

Resolves #20

Testing
-------

This commit removes the `rocket::testing` module. It adds the
`rocket::local` module which provides a `Client` type for local
dispatching of requests against a `Rocket` instance. This `local`
package subsumes the previous `testing` package.

Rocket Examples
---------------

The `forms`, `optional_result`, and `hello_alt_methods` examples have
been removed. The following example have been renamed:

  * extended_validation -> form_validation
  * hello_ranks -> ranking
  * from_request -> request_guard
  * hello_tls -> tls

Other Changes
-------------

This commit also includes the following smaller changes:

  * Config::{development, staging, production} constructors have been
    added for easier creation of default `Config` structures.
  * The `Config` type is exported from the root.
  * `Request` implements `Clone` and `Debug`.
  * `Request::new` is no longer exported.
  * A `Response::body_bytes` method was added to easily retrieve a
    response's body as a `Vec<u8>`.
2017-06-08 17:34:50 -07:00