Commit Graph

313 Commits

Author SHA1 Message Date
ThouCheese ebb9f3cfdd Allow field defaults in 'FromForm' derive. 2021-06-03 00:02:32 -07:00
Sergio Benitez ed3cc13b84 Add internal '__typed_stream' proc-macro.
This resolves syntax ambiguity issues with public typed-stream macros.
Prior to this commit, greedy single-token matching by macro-rules macros
would result in certain tokens at the beginning of the macro input, such
as 'for', inadvertently triggering a '$ty' matching case resulting in
incorrect expansion.
2021-06-01 11:43:51 -07:00
Sergio Benitez 86c8000036 Improve 'self' token spans in field validators. 2021-06-01 11:34:31 -07:00
Sergio Benitez 2b8104ee2c Consistently prefix codegen variables with '__'.
Closes #1656.
2021-05-29 15:33:15 -07:00
Sergio Benitez 41d7138540 Allow custom generic bounds in 'Responder' derive. 2021-05-26 02:26:11 -07:00
Sergio Benitez a13a2f4a84 Move 'FileName', 'TempFile', 'NamedFile' to 'fs'.
This consolidates all file system related types into one module.
2021-05-22 16:22:01 -07:00
Sergio Benitez 28ba04b47b Impl 'IntoCollection' for '[T; N]'.
This introduces const generics into the codebase for a more efficient,
clone-free 'IntoCollection' for arrays.
2021-05-22 11:01:00 -07:00
Sergio Benitez 6784ebc097 Use 'syn', 'proc_macro2' directly.
Fixes #1641.
2021-05-21 09:13:47 -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 f6568aca68 Update UI tests for latest nightly. 2021-05-18 12:00:46 -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
Jeb Rosen 7478f0935d Update UI tests for latest stable. 2021-05-08 10:49:06 -07:00
Sergio Benitez fe23eaebd1 Document 'async' attributes. 2021-04-28 21:58:14 -07:00
Sergio Benitez ad8d80907b Remove unused reason phrase in 'Status'.
Closes #534.

Co-authored-by: YetAnotherMinion <yam@thinkalexandria.com>
2021-04-28 21:26:41 -07:00
Sergio Benitez 63e6845386 Revamp 'Response', 'Body' types.
This is a breaking change for many consumers of the 'Response' and all
consumers of the 'Body' API. The summary of breaking changes is:

  * 'Response::body()', 'Response::body_mut()' are infallible.
  * A 'Body' can represent an empty body in more cases.
  * 'ResponseBuilder' is now simply 'Builder'.
  * Direct body read methods on 'Response' were removed in favor of
    chaining through 'body_mut()': 'r.body_mut().to_string()'.
  * Notion of a 'chunked_body' was removed as it was inaccurate.
  * Maximum chunk size can be set on any body.
  * 'Response' no longer implements 'Responder'.

A few bugs were fixed in the process. Specifically, 'Body' will emit an
accurate size even for bodies that are partially read, and the size of
seek-determined bodies is emitted on HEAD request where it wasn't
before. Specifics on transport were clarified, and 'Body' docs greatly
improved as a result.
2021-04-28 02:21:33 -07:00
Sergio Benitez e7b28f18a9 Doc 'form' items, 'async_test', private macros. 2021-04-28 02:21:30 -07:00
Sergio Benitez bab3b1cb5b Mod-export 'msg!', 'local_cache!', 'try_outcome!'.
This removes the export of each of these macros from the root, limiting
their export-scope to their respective module. This is accomplished
using a new internal macro, 'export!', which does some "magic" to work
around rustdoc deficiencies.
2021-04-28 01:58:42 -07:00
Sergio Benitez 41018a5112 Add codegen internal 'Ident::uniqueify()' method.
This makes an ident unique based on some or no metadata.
2021-04-28 01:24:03 -07:00
Sergio Benitez 03d759ab90 Make type macros inelgible as sentinels. 2021-04-28 01:18:20 -07:00
Sergio Benitez 068aacd79d Require source lines to be under 100 chars. 2021-04-27 20:19:35 -07:00
Sergio Benitez 691d3f2d95 Rename codegen proxy struct methods.
Also fixes codegen so that rustc emits a warning on unused catchers, as
with routes in the previous commit.
2021-04-27 16:12:53 -07:00
Matthew Pomes d4466b73af Fix codegen so rustc emits unused route warnings.
Changes codegen to use an instance method on the route proxy struct
rather than implementing a trait on the proxy struct. This helps rustc
identify unused routes.

Resolves #1598.
2021-04-27 16:11:42 -07:00
Sergio Benitez 801e04bd53 Log guard failures, potential misuses.
This commit includes changes that improve how and what Rocket logs
automatically. Rocket now logs:

  * All guard errors, indicating the failing guard kind and type.
  * A warning when a 'TempFile' is used as a data guard for a request
    that specifies a 'form' Content-Type.
  * Only the top/sub of a request's format.

This commit makes the following breaking changes:

  * '<T as FromData>::Error' must implement 'Debug'.

Furthermore, this commit restores the previous behavior of always
logging launch info. It further restores the unspecified behavior of
modifying logging state only when the set logger is Rocket's logger.
2021-04-23 19:19:39 -07:00
Antoine Martin f6749e1b44 Fix misspelled link in '#[route]' attribute docs. 2021-04-20 17:26:08 -07:00
Sergio Benitez 64e46b7107 Introduce sentinels: auto-discovered launch abort.
Sentinels resolve a long-standing usability and functional correctness
issue in Rocket: starting an application with guards and/or responders
that depend on state that isn't available. The canonical example is the
'State' guard. Prior to this commit, an application with routes that
queried unmanaged state via 'State' would fail at runtime. With this
commit, the application refuses to launch with a detailed error message.

The 'Sentinel' docs explains it as:

    A sentinel, automatically run on ignition, can trigger a launch
    abort should an instance fail to meet arbitrary conditions. Every
    type that appears in a mounted route's type signature is eligible to
    be a sentinel. Of these, those that implement 'Sentinel' have their
    'abort()' method invoked automatically, immediately after ignition,
    once for each unique type. Sentinels inspect the finalized instance
    of 'Rocket' and can trigger a launch abort by returning 'true'.

The following types are now sentinels:

  * 'contrib::databases::Connection' (any '#[database]' type)
  * 'contrib::templates::Metadata'
  * 'contrib::templates::Template'
  * 'core::State'

The following are "specialized" sentinels, which allow sentinel
discovery even through type aliases:

  * 'Option<T>', 'Debug<T>' if 'T: Sentinel'
  * 'Result<T, E>', 'Either<T, E>' if 'T: Sentinel', 'E: Sentinel'

Closes #464.
2021-04-16 01:44:53 -07:00
Sergio Benitez 1872818570 Support type generics in 'Responder' derive. 2021-04-16 01:22:11 -07:00
Sergio Benitez 4f3511786c Introduce statically-enforced 'Rocket' phasing.
The core 'Rocket' type is parameterized: 'Rocket<P: Phase>', where
'Phase' is a newly introduced, sealed marker trait. The trait is
implemented by three new marker types representing the three launch
phases: 'Build', 'Ignite', and 'Orbit'. Progression through these three
phases, in order, is enforced, as are the invariants guaranteed by each
phase. In particular, an instance of 'Rocket' is guaranteed to be in its
final configuration after the 'Build' phase and represent a running
local or public server in the 'Orbit' phase. The 'Ignite' phase serves
as an intermediate, enabling inspection of a finalized but stationary
instance. Transition between phases validates the invariants required
by the transition.

All APIs have been adjusted appropriately, requiring either an instance
of 'Rocket' in a particular phase ('Rocket<Build>', 'Rocket<Ignite>', or
'Rocket<Orbit>') or operating generically on a 'Rocket<P>'.
Documentation is also updated and substantially improved to mention
required and guaranteed invariants.

Additionally, this commit makes the following relevant changes:

  * 'Rocket::ignite()' is now a public interface.
  * 'Rocket::{build,custom}' methods can no longer panic.
  * 'Launch' fairings are now 'ignite' fairings.
  * 'Liftoff' fairings are always run, even in local mode.
  * All 'ignite' fairings run concurrently at ignition.
  * Launch logging occurs on launch, not any point prior.
  * Launch log messages have improved formatting.
  * A new launch error kind, 'Config', was added.
  * A 'fairing::Result' type alias was introduced.
  * 'Shutdown::shutdown()' is now 'Shutdown::notify()'.

Some internal changes were also introduced:

  * Fairing 'Info' name for 'Templates' is now 'Templating'.
  * Shutdown is implemented using 'tokio::sync::Notify'.
  * 'Client::debug()' is used nearly universally in tests.

Resolves #1154.
Resolves #1136.
2021-04-13 19:26:45 -07:00
Sergio Benitez 887b2aed87 Move catcher, route types into eponymous modules.
In the course, significantly improve their documentation.
2021-04-13 18:58:05 -07:00
Sergio Benitez fd8c9ce795 Use launch-inferred '_' in most example code. 2021-04-13 18:12:39 -07: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 c45a83897f Allow several 'field' attributes in all derives.
In particular, 'FromFormField' and 'UriDisplayQuery' now allow any
number of form 'field' attributes. For the former, multiple 'value's are
allowed, all of which are used to match against incoming fields - any
match wins. For the latter, multiple 'name' and 'value's are allowed;
the first of each is used to render the query value.

Additionally, 'UriDisplayQuery' can now be derived for C-like enums.
This brings the derive to parity with 'FromFormValue' and allows their
unified application on C-like enums.

Resolves #843.
2021-04-07 23:09:05 -07:00
Sergio Benitez fd03417188 Emit a dummy 'Origin' in failed 'uri!' expansions.
This significantly reduces the number of spurious, fallout compiler
errors when the 'uri!' macros fails.
2021-04-07 23:09:05 -07:00
Sergio Benitez 579508d58f Make 'FileName' a DST. Improve sanitization.
Resolves #1594.
2021-04-03 17:09:00 -07:00
Sergio Benitez 2893ce754d Introduce scoped catchers.
Catchers can now be scoped to paths, with preference given to the
longest-prefix, then the status code. This a breaking change for all
applications that register catchers:

  * `Rocket::register()` takes a base path to scope catchers under.
    - The previous behavior is recovered with `::register("/", ...)`.
  * Catchers now fallibly, instead of silently, collide.
  * `ErrorKind::Collision` is now `ErrorKind::Collisions`.

Related changes:

  * `Origin` implements `TryFrom<String>`, `TryFrom<&str>`.
  * All URI variants implement `TryFrom<Uri>`.
  * Added `Segments::prefix_of()`.
  * `Rocket::mount()` takes a  `TryInto<Origin<'_>>` instead of `&str`
    for the base mount point.
  * Extended `errors` example with scoped catchers.
  * Added scoped sections to catchers guide.

Internal changes:

  * Moved router code to `router/router.rs`.
2021-03-28 13:57:33 -07:00
Sergio Benitez feadb4dd16 Prefer '&str' in doc examples. 2021-03-27 16:25:39 -07:00
Sergio Benitez e7934a2a3f Parse inner form 'T' in 'Option<T>' strictly.
This behavior more closely matches the expectation that a missing field
results in 'None'.

Also cleans up forms docs for readability, completeness.
2021-03-24 19:53:13 -07:00
Sergio Benitez b3021e2acb Fix all broken links. Update some outdated docs. 2021-03-19 18:09:13 -07:00
Sergio Benitez def9b4dcd2 Always emit 'Request<'_>', with lifetime. 2021-03-19 18:05:27 -07:00
Sergio Benitez 84fda62678 Emit query parse code only when there's a query. 2021-03-19 18:04:28 -07:00
Sergio Benitez 9c678e606b Track and log catcher names. 2021-03-15 02:27:53 -07:00
Sergio Benitez 70b42e6f0e Remove second lifetime from 'FromRequest'.
While offering some utility, the lifetime did not carry its weight, and
in practice offered no further ability to borrow. This greatly
simplifies request guard implementations.
2021-03-14 19:57:59 -07:00
Sergio Benitez e532f4e2b3 Disallow defaults in strict forms.
Partially resolves #1536.
2021-03-11 02:03:13 -08:00
Sergio Benitez c0caa3b874 Fix codegen doctests for 'Route.name' changes. 2021-03-10 22:28:06 -08:00
Sergio Benitez 4e06ee64aa Test 'secret_key' validation, now on pre-launch.
Prior to this commit, it was not possible to test Rocket crates in
production mode without setting a global secret key or bypassing secret
key checking - the testing script did the latter. The consequence is
that it became impossible to test secret key related failures because
the tests passed regardless.

This commit undoes this. As a consequence, all tests are now aware of
the difference between debug and release configurations, the latter of
which validates 'secret_key' by default. New 'Client::debug()' and
'Client::debug_with()' simplify creating an instance of 'Client' with
configuration in debug mode to avoid undesired test failures.

The summary of changes in this commit are:

  * Config 'secret_key' success and failure are now tested.
  * 'secret_key' validation was moved to pre-launch from 'Config:from()'.
  * 'Config::from()' only extracts the config.
  * Added 'Config::try_from()' for non-panicking extraction.
  * 'Config' now knows the profile it was extracted from.
  * The 'Config' provider sets a profile of 'Config.profile'.
  * 'Rocket', 'Client', 'Fairings', implement 'Debug'.
  * 'fairing::Info' implements 'Copy', 'Clone'.
  * 'Fairings' keeps track of, logs attach fairings.
  * 'Rocket::reconfigure()' was added to allow modifying a config.

Internally, the testing script was refactored to properly test the
codebase with the new changes. In particular, it no longer sets a rustc
'cfg' to avoid secret-key checking.

Resolves #1543.
Fixes #1564.
2021-03-09 21:57:26 -08:00
Sergio Benitez 7784cc982a Allow multiple and uncased field renamings. 2021-03-05 18:09:12 -08:00
Sergio Benitez 5ed3c13240 Remove 'extern crate's in generated URI macro.
Resolves #1554.
2021-03-05 14:21:52 -08:00
Sergio Benitez 4d0042c395 Allow '<path..>' to match zero segments.
This changes core routing so that '<path..>' in a route URI matches zero
or more segments. Previously, '<path..>' matched _1_ or more.

  * Routes '$a' and '$b/<p..>' collide if $a and $b previously collided.
  * For example, '/' now collides with '/<p..>'.
  * Request '$a' matches route '$b/<p..>' if $a previously matched $b.
  * For example, request '/' matches route '/<p..>'.

Resolves #985.
2021-03-05 02:01:24 -08:00
Sergio Benitez a3946377f7 Use 'UriPart::Kind' to avoid unreachable match arms. 2021-03-04 02:48:07 -08:00
Sergio Benitez 7628546ca2 Improve 'FromForm' derive error spans. 2021-03-04 02:11:06 -08:00
Sergio Benitez 398a044eb0 Complete forms documentation. Improve 'validate'.
* Add a `msg!()` macro to easily change a field validation message.
  * Allow a field to refer to itself via `self.field`.
  * Improve the various field validation traits.
2021-03-04 02:08:40 -08:00
Sergio Benitez 78e2f8a3c9 Revamp codegen, fixing inconscpicuous bugs.
This commit completely revamps the way that codegen handles route URI
"parameters". The changes are largely internal. In summary, codegen code
is better organized, better written, and less subject to error.

There are three breaking changes:
  * `path` is now `uri` in `route` attribute: `#[route(GET, path = "..")]`
    becomes `#[route(GET, uri = "..")]`.
  * the order of execution for path and query guards relative to
    each-other is now unspecified
  * URI normalization now normalizes the query part as well.

Several error messages were improved. A couple of bugs were fixed:
  * Prior to this commit, Rocket would optimistically try to parse every
    segment of a URI as an ident, in case one was needed in the future.
    A bug in rustc results in codegen "panicking" if the segment
    couldn't _lex_ as an ident. This panic didn't manifest until far
    after expansion, unfortunately. This wasn't a problem before as we
    only allowed ident-like segments (ASCII), but now that we allow any
    UTF-8, the bug surfaced. This was fixed by never attempting to parse
    non-idents as idents.
  * Prior to this commit, it was impossible to generate typed URIs for
    paths that ignored path parameters via the recently added syntax
    `<_>`: the macro would panic. This was fixed by, well, handling
    these ignored parameters.

Some minor additions:
  * Added `RawStr::find()`, expanding its `Pattern`-based API.
  * Added an internal mechanism to dynamically determine if a `UriPart`
    is `Path` or `Query`.
2021-03-04 02:01:25 -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
Rudi Floren e332ee83da Add missing lifetime parameter in codegen for routes and catchers.
This is linted against by `elided_lifetimes_in_paths`, which is not
enabled by default but is part of the `rust_2018_idioms` lint group.
2021-02-28 15:59:45 -08:00
Jeb Rosen 87f03d3b26 Update UI tests for latest nightly and 'pear' error messages. 2021-02-26 22:15:37 -08:00
Jeb Rosen 453fa037da Update UI tests for latest stable. 2021-02-20 12:01:44 -08:00
Sergio Benitez 2a49368313 Update UI tests for latest nightly. 2021-02-09 17:17:44 -08:00
Sergio Benitez 031948c1da Remove superfluous semicolons. 2021-01-13 14:30:08 -08:00
Brendon Federko e68a951a54 Upodate tests for latest stable. 2021-01-12 14:52:34 -08:00
Jeb Rosen 1f1f44f336 Update UI tests for latest stable. 2020-11-21 12:42:57 -08:00
Sergio Benitez 86ff66a69c Streamline raw identifier support in codegen. 2020-11-03 12:07:23 -08:00
Jeb Rosen 97f6bc5dc0 Support raw identifiers in forms, routes, uri.
Resolves #881.
2020-11-03 01:42:37 -08:00
Sergio Benitez 337e8843a4 Use 'Option', 'Result' directly in 'uri!' query.
Prior to this commit, the conversion 'T -> Option<T>' was applied in
both the path and query parts of a URI in the 'uri' macro via the
'FromUriParam' trait with no implementation for 'Option<T>' directly.
This meant that it was impossible to directly render an 'Option<T>'.
This was exactly desired for the path part, where rendering a 'None'
would yield an incorrect URI, but the restriction was too strict for the
query part, where a 'None' is entirely valid. This commit makes changes
the conversion so that it only applied to path parts and adds the
identity conversions for 'Option<T>' and 'Result<T, E>' for query parts.

The side effect is a breaking change: due to conflicting impls, the 'T'
to 'Option<T>' conversion was removed for query parts. Thus, all 'uri!'
query route arguments of type 'Option' or 'Result' must now be wrapped
in 'Some' or 'Ok'. Due to new 'Option<T> <-> Result<T, E>' conversions,
either 'Some' _and_ 'Ok' work in both contexts.

Closes #1420.
2020-11-01 10:30:30 -08:00
Sergio Benitez a6f5a63535 Add tests for ignored parameters '<_>'.
Co-authored-by: timokoesters <timo@koesters.xyz>
2020-10-30 00:47:41 -07:00
Sergio Benitez 8e8fb4cae8 Allow ignored route path segments.
Co-authored-by: timokoesters <timo@koesters.xyz>
2020-10-30 00:06:39 -07:00
Sergio Benitez bbfe2ba5cc Point all docs and doc links to 'master' branch. 2020-10-21 04:54:24 -07:00
Sergio Benitez 1fb061496d Revamp configuration.
This commit completely overhauls Rocket's configuration systems, basing
it on the new Figment library. It includes many breaking changes
pertaining to configuration. They are:

  * "Environments" are replaced by "profiles".
  * 'ROCKET_PROFILE' takes the place of 'ROCKET_ENV'.
  * Profile names are now arbitrary, but 'debug' and 'release' are given
    special treatment as default profiles for the debug and release
    compilation profiles.
  * A 'default' profile now sits along-side the meta 'global' profile.
  * The concept of "extras" is no longer present; users can extract any
    values they want from the configured 'Figment'.
  * The 'Poolable' trait takes an '&Config'.
  * The 'secrets' feature is disabled by default.
  * It is a hard error if 'secrets' is enabled under the 'release'
    profile and no 'secret_key' is configured.
  * 'ConfigBuilder' no longer exists: all fields of 'Config' are public
    with public constructors for each type.
  * 'keep_alive' is disabled with '0', not 'false' or 'off'.
  * Inlined error variants into the 'Error' structure.
  * 'LoggingLevel' is now 'LogLevel'.
  * Limits can now be specified in SI units: "1 MiB".

The summary of other changes are:

  * The default config file can be configured with 'ROCKET_CONFIG'.
  * HTTP/1 and HTTP/2 keep-alive configuration is restored.
  * 'ctrlc' is now a recognized config option.
  * 'serde' is now a core dependency.
  * TLS misconfiguration errors are improved.
  * Several example use '_' as the return type of '#[launch]' fns.
  * 'AdHoc::config()' was added for simple config extraction.
  * Added more documentation for using 'Limits'.
  * Launch information is no longer treated specially.
  * The configuration guide was rewritten.

Resolves #852.
Resolves #209.
Closes #1404.
Closes #652.
2020-10-20 19:21:56 -07:00
Sergio Benitez 8da034ab83 Update 'devise'. 2020-10-15 01:01:30 -07:00
Sergio Benitez 5cf249581f Add 'const' constructor for 'MediaType'. 2020-10-14 23:54:37 -07: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 2f330d2967 Allow return type of '#[launch]' fn to be elided. 2020-10-12 22:32:02 -07:00
Sergio Benitez 092e03f720 Generate a proxy structure for better namespacing.
Prior to this commit, it was impossible to 'use' a route from a separate
namespace for use in a 'routes!' macro. Naturally, this was a common
source of confusion amongst users. This commit obviates this deficiency
by generating a "proxy" structure that can be imported and converted
into a 'Route'/'Catcher' or their static variants.

This change is largely backwards compatible but can break existing code
when routes are named identically to other types in the namespace.
2020-10-12 22:11:44 -07:00
Jeb Rosen 83a7fc48d2 Update UI tests for latest nightly. 2020-10-11 12:21:45 -07:00
Jeb Rosen f976c15c25 Update UI tests for latest nightly. 2020-09-06 18:34:24 -07:00
Jeb Rosen dc2c6ecd8a Update UI tests for latest stable. 2020-08-31 18:51:38 -07:00
Sergio Benitez 52320020bc Use thread-safe 'CookieJar's.
The user-facing changes effected by this commit are:

  * The 'http::Cookies<'_>' guard is now '&http::CookieJar<'_>'.
  * The "one-at-a-time" jar restriction is no longer imposed.
  * 'CookieJar' retrieval methods return 'http::CookieCrumb'.
  * The 'private-cookies' feature is now called 'secrets'.
  * Docs flag private cookie methods with feature cfg.
  * Local, async request dispatching is never serialized.
  * 'Client::cookies()' returns the tracked 'CookieJar'.
  * 'LocalResponse::cookies()' returns a 'CookieJar'.
  * 'Response::cookies()' returns an 'impl Iterator'.
  * A path of '/' is set by default on all cookies.
  * 'SameSite=strict' is set by default on all cookies.
  * 'LocalRequest::cookies()' accepts any 'Cookie' iterator.
  * The 'Debug' impl for 'Request' prints the cookie jar.

Resolves #1332.
2020-08-16 02:19:45 -07:00
Sergio Benitez 549c9241c4 Require data limits on 'Data::open()'.
Closes #1325.
2020-08-06 02:46:04 -05:00
Sergio Benitez 45b4436ed3 Add default catchers: '#[catch(default)]'.
The bulk of the changes in this commit are for creating an
'ErrorHandler' trait that works like the 'Handler' trait, but for
errors. Furthermore, Rocket's default catcher now responds with a JSON
payload if the preferred 'Accept' media type is JSON.

This commit also fixes a bug in 'LocalRequest' where the internal
'Request' contained an correct 'URI'.
2020-07-30 01:55:41 -07:00
Sergio Benitez e531770989 Make URI modifications to 'Route' codegen-safe.
This commit aims to make it impossible to modify a 'Route' structure in
a way that violates expectations of a code-generated 'Route'. It removes
'Route::set_uri()' in favor of 'Route::map_base()', which allows for
safe modifications of the route's base.

In a similar vain, this commit also includes the following changes:

  * 'Route::path()' was added to safely retrieve the route's 'path'.
  * The base of a 'Route' is underlined during launch printing.
  * 'Origin::into_normalized()' replaces 'Origin::to_normalized()'.

Fixes #1262.
2020-07-29 16:38:24 -07: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 ddfd73d6f3 Delete broken symlinks to 'update-references.sh'.
Fixes #1385.
2020-07-22 06:52:04 -07:00
Sergio Benitez 56a6172625 Enable compilation with stable Rust.
To the Rust teams, Rust's contributors, Rocket's contributors, the
entire Rust and Rocket communities, my colleagues at Stanford and
beyond, and Jeb: thank you all. Sincerely.

To the next ~4 years of Rocket!

Closes #19.
2020-07-21 16:30:45 -07:00
Sergio Benitez 9a2149b43d Test guide and README using stable 'doc_comment'. 2020-07-21 15:31:44 -07:00
Sergio Benitez 67efe143c5 Improve diagnostics, especially on stable. 2020-07-21 15:31:42 -07:00
Sergio Benitez 1858403203 Implement codegen testing on stable.
This commits migrates to 'trybuild' from 'compiletest' for codegen
diagnostic testing.
2020-07-21 15:11:07 -07:00
Sergio Benitez 95a4b442cc Update Pear to 0.2. 2020-07-21 15:11:07 -07:00
Jeb Rosen 7f276eb2fc Update 'devise' to the latest commit. 2020-07-20 23:26:36 -07:00
Sergio Benitez 3f2b8f6006 Remove 'proc_macro' features. 2020-07-16 05:46:39 -07:00
Sergio Benitez 7bcf82a199 Improve catcher mismatched type errors. 2020-07-14 02:48:46 -07:00
Sergio Benitez dfca18d307 Generate 'uri!' macro names independently of span.
Prior to this commit, codegen used 'Span' information to generate a
unique id for a given route. This commit changes the id generation to
instead use 1) the route's name and path, 2) a an per-generation
atomically increasing ID, and 3) the ids of the process/thread the
proc-macro is running in. Together, these values should provide a unique
id for a given route, even in the face of the reused processes and
threads, while also removing the dependence on unstable Span features.

Fixes #1373.
2020-07-14 00:44:59 -07:00
Sergio Benitez 816b8c44ab Ignore 'snake_case' warnings for 'tmp' variables. 2020-07-14 00:43:48 -07:00
Sergio Benitez 33e95f4900 Rename 'FromDataSimple' to 'FromData'. Make async.
The 'FromData' trait becomes 'FromTransformedData'.
2020-07-12 02:23:00 -07:00
Sergio Benitez f4c82d7ffe Remove unnecessary 'dev-dependencies'. 2020-07-11 11:27:23 -07:00
Sergio Benitez 62355b424f Remove use of stable 'proc_macro_hygiene' feature. 2020-07-11 10:48:08 -07:00
Sergio Benitez 08b34e8263 Fix and re-enable UI tests. 2020-07-11 09:24:30 -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 d89c7024ed Replace 'Manifest' with 'Cargo'.
This is largely an internal change. Prior to this commit, the 'Manifest'
type, now replaced with the 'Cargo' type, robbed responsibility from the
core 'Rocket' type. This new construction restores the previous
responsibility and makes it clear that 'Cargo' is _only_ for freezing,
and representing the stability of, Rocket's internal state.
2020-07-11 09:24:30 -07:00
Sergio Benitez 1704ff7743 Asyncify 'Handler'. Rename 'ErrorHandlerFuture' to 'CatcherFuture'. 2020-07-11 09:24:30 -07:00
Sergio Benitez 2465e2f136 Make 'Responder' trait sync; fix its lifetimes.
In summary, this commit modifies 'Responder' so that:

  * ..it is no longer 'async'. To accommodate, the 'sized_body' methods
    in 'Response' and 'ResponseBuilder' are no longer 'async' and accept
    an optional size directly. If none is supplied, Rocket will attempt
    to compute the size, by seeking, before writing out the response.
    The 'Body' type was also changed to differentiate between its sized
    'Seek' and chunked body variants.

  * ..'&Request' gains a lifetime: 'r, and the returned 'Response' is
    parameterized by a new 'o: 'r. This allows responders to return
    references from the request or those that live longer.
2020-07-11 09:24:29 -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
Sergio Benitez 8696dd94af Make references to core types absolute in codegen.
Prior to this commit, codegen emitted tokens containing bare types like
'Result' and 'Box' as well as presumed imported variants such as 'None'
and 'Ok'.  However, users are free to shadow these, and if they do, the
generated code will fail to compile, or worse, be incorrect. To avoid
this, this commit makes all references to these core types and imports
absolute.
2020-07-11 09:24:29 -07:00
Jeb Rosen 2ca15b663a Update minimum nightly to '2019-12-29'.
This version of rustc was the first to ship with a version of cargo that
supports 'proc_macro' without an 'extern crate' declaration.
2020-07-11 09:24:29 -07:00
Sergio Benitez c0c6c79a7f Use 'async_trait' for 'Responder'.
Also:

  * Remove 'response::ResultFuture'.
  * Re-export 'tokio' and 'futures' from the crate root.
  * Make 'ResponseBuilder::sized_body()' and 'async fn'.
  * Remove the 'Future' implementation for 'ResponseBuilder'.
  * Add 'ResponseBuilder::finalize()' for finalizing the builder.
2020-07-11 09:24:29 -07:00
Sergio Benitez 431b963774 Use 'async_trait' for 'FromRequest'.
Removes 'FromRequestAsync'.
2020-07-11 09:24:29 -07:00
Sergio Benitez 48c333721c Use 'async_trait' for 'Fairing' trait.
Also re-exports the 'async_trait' attribute from 'rocket'.
2020-07-11 09:24:29 -07:00
Sergio Benitez a4e7972b4b Remove unnecessary 'extern crate's. 2020-07-11 09:24:29 -07:00
Michael Howell c9d0af09d6 Use 'AsyncSeek' for sized bodies in 'Response's.
In order to avoid making 'ResponseBuilder::sized_body' an asynchronous
function, the seeking is deferred until finalization. 'finalize()' is
replaced with '.await', and 'ResponseBuilder::ok()' is an 'async fn'.
2020-07-11 09:24:29 -07:00
Paolo Barbolini 003bf77c29 Upgrade to tokio 0.2.0.
* Update 'tokio', 'tokio-rustls', and 'hyper'.
* Remove unused dependencies on some `futures-*` crates.
* Rework 'spawn_on', which is now 'serve'.
* Simplify Ctrl-C handling.
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 df52616074 Update error positions after changes for async #[catch] support. 2020-07-11 09:24:29 -07:00
Jeb Rosen 4e5b889358 Add async-routes test for #[get] and #[catch]. 2020-07-11 09:24:29 -07:00
Jeb Rosen 5317664893 Fix UI tests for FromRequestAsync. 2020-07-11 09:24:29 -07:00
Jeb Rosen 1c28a9413b Allow catchers to be async fn. 2020-07-11 09:24:29 -07:00
Jeb Rosen adf7e4233a Add 'FromRequestAsync' and use it in route codegen.
'FromRequestAsync' is automatically implemented for all types
that implement 'FromRequest'.
2020-07-11 09:24:29 -07:00
Jeb Rosen ea06878581 Update 'hyper', 'futures-*-preview', and 'tokio-*' dependencies.
Use I/O traits and types from 'tokio-io' as much as possible.

A few adapters only exist in futures-io-preview and use
futures-tokio-compat as a bridge for now.
2020-07-11 09:24:29 -07:00
Jeb Rosen 8718561bf8 Emit an error when #[async_test] is applied to a function with parameters. 2020-07-11 09:24:28 -07:00
Jeb Rosen af36f299c6 Fix ordering of messages in a UI test. 2020-07-11 09:24:28 -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
Jeb Rosen baa2ed27f3 Update UI tests affected by removal of typed headers. 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 633e495a6b Update many doc tests in 'core' for async. 2020-07-11 09:24:28 -07:00
Jeb Rosen 7c34a3a93e Make 'Fairing::on_response' and 'Responder::respond_to' async.
This is required to be able to do anything useful with the body in the
outgoing response. Request fairings do not appear to need to be async
as everything on Data that returns a future moves self and on_request only
gets &Data, but the same change in this commit should work for on_request
if desired.
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
Sergio Benitez 83925bbae1 Use clearer variables names in guide test macro.
Also removes latent, unnecessary 'guide' test.
2020-06-14 18:56:45 -07:00
Sergio Benitez 74f15a7ab5 Use top-level doc image URLs. 2020-06-11 02:30:14 -07:00
Sergio Benitez 63a4ae0485 Silence warnings on 'extern crate proc_macro'. 2020-06-08 12:25:10 -07:00
Jeb Rosen 91fb0804be Hide docs for more generated items. 2020-06-04 18:01:20 -07:00
Sergio Benitez 3f20e4ac93 Use proper SPDX license expression in 'Cargo.toml'. 2020-06-03 23:02:05 -07:00
Jeb Rosen 3abafaaedb Update UI tests for latest nightly. 2020-04-21 18:12:08 -07:00
Sergio Benitez 06e146e7d1 Update 'time' to 0.2 in 'contrib'. 2020-03-25 14:39:55 -07:00
Sergio Benitez 53353df633 Fix more broken links. 2020-03-09 02:03:38 -07:00
Sergio Benitez 95c981de79 Test all guide code examples.
Every code example is now fully runnable and testable. As a result, all
examples are now tested and include imports. Relevant imports are shown
by default. Code examples can be expanded to show all imports.

Fixes #432.
2020-02-15 04:02:19 -08:00
Sergio Benitez ee1a9903b6 Update UI tests for latest nightly. 2020-02-15 03:51:56 -08:00
Sergio Benitez 9f0e02fe27 Make references to core types absolute in codegen.
Prior to this commit, codegen emitted tokens containing bare types like
'Result' and 'Box' as well as presumed imported variants such as 'None'
and 'Ok'.  However, users are free to shadow these, and if they do, the
generated code will fail to compile, or worse, be incorrect. To avoid
this, this commit makes all references to these core types and imports
absolute.
2020-02-06 21:16:45 -08:00
Jeb Rosen ff2000293c Update 'compiletest' and fix and re-enable compile UI tests. 2020-01-15 17:09:57 -08:00
Jeb Rosen 96235615ce Update compile tests for changes in rust nightly. 2019-11-29 11:18:32 -08:00
Jeb Rosen 343f51d550 Disable UI tests for now. 2019-11-29 11:18:26 -08:00
Jacob Pratt 4e6a7ddd5f Remove use of the 'crate_visibility_modifier' feature.
Most items with 'crate' visibility become 'pub(crate)'.
Items are made 'pub' instead when they would remain private.
2019-09-21 09:16:04 -07:00
Jeb Rosen 335d8f7dbb Adjust '#[catch]' codegen output to fix a UI test regression in latest nightly. 2019-09-21 08:33:16 -07:00
Sergio Benitez 592e441de5 Use proper span in responder codegen output. 2019-09-09 21:57:10 -07:00
Sergio Benitez 22da02fa64 Remove double semicolons; silence test warnings. 2019-09-09 16:57:03 -07:00
Sergio Benitez 0b059e06e5 Update 'devise' to 0.3.
This transitively updates 'syn', 'proc-macro2', and 'quote' to 1.0.
2019-09-05 15:44:25 -07:00
Sergio Benitez dcea9563fc Update UI tests for latest nightly. 2019-08-26 12:48:32 -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 2f458b5217 Remove dependence on 'decl_macro' in codegen.
The generated 'uri' helper macros are now re-exports of 'macro_rules'
macros, made possible by the stable 'uniform_paths' feature.
2019-07-19 11:38:35 -07:00
Jeb Rosen be784a7845 Migrate codegen to Rust 2018. 2019-06-25 13:45:27 -04:00