Commit Graph

510 Commits

Author SHA1 Message Date
Sergio Benitez 6345d2b888 Update dependencies in core to latest versions.
This updates:

 * rmp-serde to 1
 * pretty_assertions to 1
 * parking_lot to 0.12
 * tokio-util to 0.7
2022-02-16 10:26:24 -08:00
Ning Sun 831ffc6c09 Update 'handlebars' to 4.0. 2021-08-30 03:42:57 -07:00
Sergio Benitez 42a0fb8afe Increase diesel DB example timeout for CI. 2021-08-19 23:36:30 -07:00
Sergio Benitez 3616f25c0b Update 'time' to 0.3, 'cookie' to 0.16.
Also reexport 'time' from the crate root.
2021-08-19 19:49:23 -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 5b1a04deab Introduce async database pools: 'rocket_db_pools'.
This is the async analog of 'rocket_sync_db_pools', rewritten to be
cleaner, leaner, easier to maintain and extend, and better documented.

Resolves #1117.
Resolves #1187.
2021-07-18 12:17:17 -07:00
Jeb Rosen f7f068be11 Initial implementation of async DB pooling. 2021-07-18 12:14:25 -07:00
Sergio Benitez 693f4f9ee5 Add README to databases example.
Closes #1760.
2021-07-12 16:45:56 -07:00
Sergio Benitez 677790d639 Bring back generated TLS keys, used by tests. 2021-07-09 16:35:09 -07:00
Sergio Benitez bbc36ba27f Initial implementation of mTLS.
Co-authored-by: Howard Su <howard0su@gmail.com>
Co-authored-by: Mikail Bagishov <bagishov.mikail@yandex.ru>
2021-07-09 00:05:20 -07:00
Sergio Benitez 71823915db Don't store example keys and certs in repository. 2021-07-07 12:16:12 -07:00
Sergio Benitez 95e9b2e9ef Remove latent 'dbg!()' in templating tests. 2021-07-02 11:33:32 -07:00
Mikail Bagishov be933ce398 Apply clippy suggestions. 2021-06-30 14:13:19 -07:00
Flying-Toast 8e3ad40beb Add 'context!' for ad-hoc templating contexts. 2021-06-30 10:09:28 -07:00
Sergio Benitez fb3ae9f7db Impl std traits, 'UriDisplay<Query>' for 'Json'.
The 'Json' type now implements:

  * Clone
  * PartialEq
  * Eq
  * PartialOrd
  * Ord
  * Hash
  * UriDisplay<Query>

Method calls that resolve to a method in the set of traits above
previously resolved to the `Deref` target. For example, `foo.clone()`,
where `foo: Json<T>`, previously resolved to `<T as Clone>::clone()` but
now resolves to `<Json<T> as Clone>::clone()`.
2021-06-29 03:31:27 -07:00
Sergio Benitez 76ec847a58 Use 'RelativePathBuf' as 'Config.temp_dir' type.
This makes a relative 'temp_dir' declared in a config file relative to
the config file itself.
2021-06-25 11:42:49 -07:00
Sergio Benitez 128234d9a8 Allow customizing and removing 'Server' header. 2021-06-08 23:09:57 -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
Juhasz Sandor 469f3942eb Use an 'include' in tera templating example. 2021-06-03 13:21:04 -07:00
Sergio Benitez 74299a9719 Make minor improvements to chat example. 2021-06-02 00:10:34 -07:00
Sergio Benitez f1ecb79a7e Add fully featured SSE chat example. 2021-06-01 13:47:52 -07:00
Sergio Benitez 29c5bfd6cc Add usage comments to 'hello' example. 2021-06-01 11:16:40 -07:00
Sergio Benitez 5a4e66ec43 Split 'rocket_contrib' into distinct crates.
This follows the completed graduation of stable contrib features into
core, removing 'rocket_contrib' in its entirety in favor of two new
crates. These crates are versioned independently of Rocket's core
libraries, allowing upgrades to dependencies without consideration for
versions in core libraries.

'rocket_dyn_templates' replaces the contrib 'templates' features. While
largely a 1-to-1 copy, it makes the following changes:

  * the 'tera_templates' feature is now 'tera'
  * the 'handlebars_templates' feature is now 'handlebars'
  * fails to compile if neither 'tera' nor 'handlebars' is enabled

'rocket_sync_db_pools' replaces the contrib 'database' features. It
makes no changes to the replaced features except that the `database`
attribute is properly documented at the crate root.
2021-05-24 22:57:51 -07:00
Sergio Benitez 8a9000a9cb Document the 'Contextual' form guard. 2021-05-23 18:09:43 -07:00
Sergio Benitez a7cfa4c8b7 Don't disable default 'Shield' in 'hello' example. 2021-05-22 17:20:36 -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 b1d05d20ac Graduate 'serve' into core as 'fs', 'FileServer'.
This completes the graduation of stable 'contrib' features to 'core'.

Closes #1107.
2021-05-22 11:15:56 -07:00
Sergio Benitez a78814f1c5 Graduate contrib 'uuid' into core.
This has the following nice benefits:

  * The 'Uuid' wrapper type is gone.
  * 'Uuid' implements 'UriDisplay', 'FromUriParam'.
  * The 'serialization' example merges in 'uuid'.

Resolves #1299.
2021-05-22 11:01:00 -07:00
Sergio Benitez f6a7087c84 Graduate 'helmet' as 'shield' into core.
The 'SpaceHelmet' fairing is now called 'Shield'. It features the
following changes and improvements:

  * Headers which are now ignored by browsers are removed.
  * 'XssFilter' is no longer an on-by-default policy.
  * A new 'Permission' policy is introduced.
  * 'Shield' is attached to all 'Rocket' instances by default.
  * Default headers never allocate on 'Clone'.
  * Policy headers are rendered once and cached at start-up.
  * Improved use of typed URIs in policy types.
2021-05-22 11:01:00 -07:00
Sergio Benitez c74bcfd40a Graduate contrib 'json' and 'msgpack' into core.
This has the following nice benefits:

  * The 'JsonValue' wrapper type is gone.
  * 'Local{Request, Response}' natively support JSON/MessagePack.
  * The 'json' and 'msgpack' limits are officially recognized.
  * Soon, Rocket application will not require an explicit 'serde' dep.

This marks the beginning of the end of 'rocket_contrib'.
2021-05-22 11:01:00 -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 1c600bda30 Discover manually registered templates.
This includes one breaking change: the default Content-Type of templates
without an identifying extension is now 'Text'. This is to prevent Tera
templates from rendering as HTML without being escaped.

Resolves #1637.
2021-05-18 11:40:10 -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 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 336a03e27f Introduce async streams.
This reworks the entire 'response::stream' module for async streams.

Resolves #1066.
2021-04-28 04:01:02 -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 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
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
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 fe4d0425e6 Remove unnecessary second 'Handler' lifetimes. 2021-04-14 22:17:21 -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 4c96ae7b52 Add 'Rocket.toml' to templating example.
This allows 'template_dir' to be relative to the workspace as opposed to
relative to the CWD.
2021-04-13 18:20:41 -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 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 0bdb6b7bc7 Remove 'attach' fairings. Add 'liftoff' fairings.
Launch fairings are now fallible and take the place of attach fairings,
but they are only run, as the name implies, at launch time.

This is is a fundamental shift from eager execution of set-up routines,
including the now defunct attach fairings, to lazy execution,
precipitated by the transition to `async`. The previous functionality,
while simple, caused grave issues:

  1. A instance of 'Rocket' with async attach fairings requires an async
     runtime to be constructed.
  2. The instance is accessible in non-async contexts.
  3. The async attach fairings have no runtime in which to be run.

Here's an example:

```rust
let rocket = rocket::ignite()
    .attach(AttachFairing::from(|rocket| async {
        Ok(rocket.manage(load_from_network::<T>().await))
    }));

let state = rocket.state::<T>();
```

This had no real meaning previously yet was accepted by running the
attach fairing future in an isolated runtime. In isolation, this causes
no issue, but when attach fairing futures share reactor state with other
futures in Rocket, panics ensue.

The new Rocket application lifecycle is this:

  * Build - A Rocket instance is constructed. No fairings are run.
  * Ignition - All launch fairings are run.
  * Liftoff - If all launch fairings succeeded, the server is started.

New 'liftoff' fairings are run in this third phase.
2021-04-07 23: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 487485d108 Explicitly specify 'template_dir' in forms example. 2021-03-17 18:34:05 -07:00
Sergio Benitez b24e53454a Generate CA cert in 'gen_certs.sh'. 2021-03-17 18:25:06 -07:00
Abdullah Alyan af48d1f2e6 Support more TLS key types in PKCS format.
Closes #1449.
Resolves #1461.
2021-03-17 18:23:15 -07:00
Sergio Benitez 1b2edd38b3 Clarify 'TempFile' configuration parameters. 2021-03-15 02:43:01 -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 f483edaafb Remove unused imports in fairings test. 2021-03-10 22:30:23 -08:00
Sergio Benitez 015438a780 Print config on attach in config example. 2021-03-10 03:37:03 -08:00
Sergio Benitez ab3413826c Improve fairing example. 2021-03-09 21:57:30 -08: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 fe9e2256a3 Update hello_world example test. 2021-03-06 01:39:31 -08:00
Sergio Benitez f0a6b9a25a Rename external 'uuid' to 'extern_uuid'.
Use '_uuid' to refer to the crate internally.
2021-03-05 14:49:41 -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 671246e90c Fix checkbox in forms example. 2021-03-04 21:42:26 -08:00
Sergio Benitez 7628546ca2 Improve 'FromForm' derive error spans. 2021-03-04 02:11:06 -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 93e62c86ed Remove unnecessary allocation in hello_2018 example. 2021-03-02 08:36:41 -08:00
Jeb Rosen 9d45e786bb Update 'rand' dependency to 0.8. 2021-02-28 16:34:38 -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
Sergio Benitez 374ad8804c Fix 'legacy_derive_helpers' warning in todo example. 2021-02-22 19:33:50 -08:00
atouchet 0c5e184299 Update various dead hyperlinks; change some links from http to https. 2021-02-20 12:01:44 -08:00
Jeb Rosen 92af8fca72 Update to 'tokio' 1.0, 'hyper' 0.14. 2021-01-13 15:22:16 -08:00
Sergio Benitez 9671115796 Use 'workers' value from 'Config::figment()'.
This commit also improves config pretty-printing and warning messages.
It also fixes an issue that resulted in config value deprecation
warnings not being emitted. The 'workers' value is now a 'usize', not a
'u16'; contrib pool sizes now default to 'workers * 2'.

Closes #1470.
2020-12-24 15:58:48 -08:00
Sergio Benitez 0c150c2a0e Remove unused 'config' examples tests. 2020-10-22 18:13:19 -07:00
Sergio Benitez ec9b5816a8 Remove 'rocket::inspect()', 'Cargo'.
This commit reverts most of dea940c7 and d89c7024. The "fix" is to run
attach fairings on a new thread. If a runtime is already running, it is
used. Otherwise, the future is executed in a single-threaded executor.
2020-10-22 03:27:04 -07:00
Sergio Benitez 4b4e918a70 Manage state, not 'lazy_static', in 'uuid' example. 2020-10-20 21:02:29 -07:00
Sergio Benitez 7337321efb Take '&mut Data' in 'on_request' fairings.
Resolves #1438.
2020-10-20 20:22:32 -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 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 dee11966b6 Borrow 'self' in 'Connection::run()'.
This simulates the pre-async behavior of serialization attempts to use a
connection by using an `async` Mutex.
2020-09-10 03:34:26 -07:00
Jeb Rosen bc8c5b9ee2 Use 'spawn_blocking' in '#[database]'.
The connection guard type generated by `#[database]` no longer
implements `Deref` and `DerefMut`. Instead, it provides an `async fn
run()` that gives access to the underlying connection on a closure run
through `spawn_blocking()`.

Additionally moves most of the implementation of `#[database]` out
of generated code and into library code for better type-checking.
2020-09-10 03:34:26 -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
Jonathan Dickinson f3beb68491 Remove superfluous lifetimes in 'Fairing' methods. 2020-07-23 21:32:20 -07:00
Sergio Benitez a115eaa633 Add 'serve::crate_relative!' for relative paths.
The macro generates crate-relative paths for easier serving of files
stored relative to the crate root.
2020-07-23 20:12:17 -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
Jeb Rosen 31ddb0de45 Use 'serde' 'derive' feature, not 'serde_derive'. 2020-07-22 12:28:18 -07:00
Jeb Rosen fbe6c1081f Upgrade 'rusqlite' to 0.23 in 'contrib'. 2020-07-21 10:54:07 -07:00
Jeb Rosen cde0b1cefd Upgrade 'parking_lot' to 0.11 in the 'todo' example.
Also remove the use of the 'nightly' feature.
2020-07-21 10:54:07 -07:00
Sergio Benitez 3f2b8f6006 Remove 'proc_macro' features. 2020-07-16 05:46:39 -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
Sergio Benitez 832408ea9b Add example requiring async testing. 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 6482fa2fba Rework 'local' module. Add 'LocalResponse' methods.
This completes the 'local' blocking client implementation.
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 f7cd455558 Make 'NamedFile' async. Fix 'Handler' trait.
Previously, 'NamedFile::open()' called a synchronous I/O method. This
commit changes it to instead use tokio's 'File' for async I/O.

To allow this to change, the 'Handler' trait was fixed to enforce that
the lifetime of '&self', the reference to the handler, outlives the
incoming request. As a result, futures returned from a handler can hold
a reference to 'self'.
2020-07-11 09:24:30 -07:00