Update Rust crate rocket to v0.5.1 #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR contains the following updates:
=0.5.0-rc.3→=0.5.1Release Notes
rwf2/Rocket (rocket)
v0.5.1Compare Source
This release contains the following crate updates:
rocket0.5.1rocket_db_pools0.2.0rocket_dyn_templates0.2.0rocket_ws0.1.1rocket0.5.1The following
charandstd::ops::Rangetypes now implementFromForm:charRange<T: FromForm>withstartandendfieldsRangeFrom<T: FromForm>withstartfieldRangeTo<T: FromForm>withendfieldRangeToInclusive<T: FromForm>withendfield[T; N],Vec<T>, and[u8]can now be passed touri!.The guide now includes a deploying section.
The
FromFormderive now properly records errors involving entire forms.FromFormderive can now be used in code emitted bymacro_rules!macros.(fix #2668 via 52de9a) [
TempFile] now ensures it flushes beforebeing persisted.
rocket_db_pools0.2.0SQLite extensions are now supported in
sqlx_sqlite.Use a database configuration option of
extensionsto specify extensions:(breaking)
deadpoolwas updated to0.13.(breaking) The
Configstructure has a new
extensionsfield.rocket_dyn_templates0.2.0Support for
minijinja2.0templates was introduced.Templates with an extension of
.j2are recognized and rendered withMinijinja.
(breaking)
handlebarswas updated to5.1.rocket_ws0.1.1Introduced
WebSocket::accept_key()method.tungstenitewas updated to0.21.General Changes
The
rust-versionfor all crates was updated to1.64.This reflects the correct MSRV required to build
rocket0.5.0.License files are now present in all published crates.
v0.5.0Compare Source
Major Features and Improvements
This release introduces the following major features and improvements:
async/await.rocket_ws.context.
shutdown fairings.
rocket_db_pools.Certificates.h2ALPN.json,msgpack, anduuidrocket_contribfeatures into core.Shield: security and privacy headers for all responses.uri!macro.serdefor built-in guards and types.#[launch]and#[rocket::main].#[catch(default)], which handle any status code.TempFiledata and form guard for automatic uploading to a temporary file.Capped<T>data and form guard which enables detecting truncation due to data limits.uri!.References.<param..>) which match zero segments.local_cache!macro for request-local storage of non-uniquely typed values.CookieJarwithout "one-at-a-time" limitations.2.mebibytes().#[derive(Responder)].chatapplication.Support for Rust Stable
As a result of support for Rust stable (Rust 2021 Edition and beyond),
#![feature(..)]crate attributes are no longer required to use Rocket. Thecomplete canonical example with a single
helloroute becomes:See a
diffof the changes from v0.4.Breaking Changes
This release includes many breaking changes. For a walkthrough guide on handling these changes, see
the v0.4 to v0.5 migration guide. The most significant changes are listed below.
Silent Changes
These changes are invisible to the compiler and will not yield errors or warnings at compile-time.
We strongly advise all application authors to review this list carefully.
sleep(),Mutex,RwLock, etc.) may preventthe server from making progress and should be avoided, replaced with an
asyncvariant, orperformed in a worker thread. This is a consequence of Rust's cooperative
asyncmultitasking.For details, see the new multitasking section of the guide.
ROCKET_ENVis nowROCKET_PROFILE. A warning is emitted a launch time if the former is set.debug, notdev.release, notprod.ROCKET_LOGis nowROCKET_LOG_LEVEL. A warning is emitted a launch time if the former is set.ROCKET_ADDRESSaccepts only IP addresses, no longer resolves hostnames likelocalhost.ROCKET_CLI_COLORSaccepts booleanstrue,falsein place of strings"on","off".secretsis enabled in non-debugprofiles without a configuredsecret_key.template_diris reported as an error at launch time.FileServer::new()fails immediately if the provided directory does not exist.-12to-1. There is no breaking change if only code generatedroutes are used. Manually configured routes with negative ranks may collide or be considered in
a different order than before.
:are properly recognized as invalid and rejected.Segmentsiterator now returns percent-decoded&strs.Formguard. UseStrictfor the previous behavior.Option<T>form guard defaults toNoneinstead of the default value forT.413 Payload Too Largestatus is returned to the client.Acceptheader.
true: the query string?fis the same as?f=true.Created<R>does not automatically send anETagheader ifR: Hash. UseCreated::tagged_bodyinstead.FileServernow forwards when a file is not found instead of failing with404 Not Found.Shieldis enabled by default. You may need to disable or change policies if your applicationdepends on typically insecure browser features or if you wish to opt-in to different policies
than the defaults.
CookieJarget()s do not return cookies added during request handling. SeeCookieJar#pending.Hashimpls forMediaTypeandContentTypeno longer consider media type parameters.FromFormimplementations ofVecandMaps are now properly lenient.[and]characters are now accepted in URI paths.[and]characters are no longer encoded byuri!.Securecookie flag is set by default for all cookies when serving over TLS.SameSiteset toLaxby default.MediaType::JavaScriptis nowtext/javascript.Contrib Graduation
The
rocket_contribcrate is deprecated and the functionality moved to otherrocketcrates. Thecontrib deprecation upgrade guide provides a walkthrough on migrating. The relevant changes are:
rocket_contribwere merged intorocketitself:json,msgpack, anduuidare now features ofrocket.rocket_contrib::jsontorocket::serde::json.rocket_contrib::msgpacktorocket::serde::msgpack.rocket_contrib::uuidtorocket::serde::uuid.rocket_contrib::helmettorocket::shield.Shieldis enabled by default.rocket_contrib::servetorocket::fs,StaticFilestorocket::fs::FileServer.UuidandJsonValuewrapper types.Shieldthat are no longer respected by browsers.rocket_contribare now provided by separate crates:rocket_contrib::templateswithrocket_dyn_templates.rocket_contrib::databaseswithrocket_sync_db_poolsandrocket_db_pools.rocket.rocket_contrib::databases::DbErroris nowrocket_sync_db_pools::Error.redis,mongodb, andmysqlintegrations which have upstreamasyncdrivers.#[database]attribute generates an
async run()method instead ofDerefimplementations.General
The following breaking changes apply broadly and are likely to cause compile-time errors.
Rocketis now generic over a phase marker:Rocket<Build>,Rocket<Ignite>,Rocket<Orbit>, orRocket<P: Phase>asneeded.
Build,Ignite,Orbitorder.rocket::ignite()is nowrocket::build()and returns aRocket<Build>.Rocket::ignite()transitions to theIgnitephase. This is run automatically on launch asneeded.
ignitefairings, and verifies sentinels.Rocket::launch()transitions into theOrbitphase and starts the server.Request::rocket()that refer to a live Rocket instance return an&Rocket<Orbit>.async:attachfairings withignitefairings. Unlikeattachfairings, which ranimmediately at the time of attachment,
ignitefairings are run when transitioning into theIgnitephase.launchfairings withliftofffairings.liftofffairings are always run, even inlocal clients, after the server begins listening and the concrete port is known.
ROCKET_ENVis superseded byROCKET_PROFILE.ROCKET_LOGis superseded byROCKET_LOG_LEVEL.dev,stage, andprodprofiles carry nospecial meaning.
debugandreleaseprofiles are the default profiles for the debug and releasecompilation profiles.
defaultprofile specifies defaults for all profiles.globalprofile has highest precedence, followed by the selected profile, followed bydefault.LoggingLeveltoLogLevel.Errorstructure.workerstousizefromu16.keep_alive: it is disabled with0, notfalseoroff.secretsfeature (for private cookies) by default.Figment.ConfigBuilder: all fields ofConfigare public with constructors for each fieldtype.
async:FromRequest,Fairing,catcher::Handler,route::Handler, andFromDatause#[async_trait].NamedFile::openis now anasyncfunction.Request::local_cache_async()for use in async request guards.Responsebodies must beAsyncReadinstead ofRead.Responsebodies must beAsyncSeekinstead ofSeek.localmodule is split into two:rocket::local::asynchronousandrocket::local::blocking.Tryimplementation onOutcomewhich allowed using?withOutcomes. Therecommended replacement is the
rocket::outcome::try_outcome!macro or the variouscombinator functions on
Outcome.Result<T, E>implementsResponderonly when bothTandEimplementResponder. Thenew
Debugwrapping responder replacesResult<T: Responder, E: Debug>.!type to now usestd::convert::Infallible.IntoOutcomewas overhauled to supplant methods now removed inOutcome.IntoOutcome::into_outcome()is nowor_error().IntoOutcomeis implemented for allOutcometype aliases.Outcome::forward()requires specifying a status code.Outcome::from()andOutcome::from_or_forward()were removed.Rocket::register()now takes a base path to scope catchers under as its first argument.ErrorKind::Collisionhas been renamed toErrorKind::Collisions.tlsfeature is enabled.MediaType::with_params()andContentType::with_params()are now builder methods.contentresponder type names are now prefixed withRaw.content::Plainresponder is now calledcontent::RawText.content::Custom<T>responder was removed in favor of(ContentType, T).CookieJar::get_private_pending()in favor ofCookieJar::get_pending().local_cache!macro accepts fewer types. Uselocal_cache_once!as appropriate.Rocket::launch()allowsRocketrecovery by returning the instance after shutdown.ErrorKind::Runtimewas removed;ErrorKind::Shutdownwas added.Outcome::Failurewas renamed toOutcome::Error.Routing and URIs
#[route(GET, path = "...")],pathis nowuri:#[route(GET, uri = "...")]./<p..>) now match zero or more segments./<a>/<p..>) now collides with (/<a>), requires arankto resolve.rocket::catcher.rocket::route.rocket::http::uri::fmt.Tno longer converts toOption<T>orResult<T, _>foruri!query parameters.uri!requires using a wrapped value or_.&RawStrno longer implementsFromParam: use&strinstead.FromParamimplementations.RawStr::url_decode()andRawStr::url_decode_lossy()allocate as necessary, returnCow.RawStr::from_str()was replaced withRawStr::new().Origin::segments()was replaced withOrigin.path().segments().Origin::path()andOrigin::query()return&RawStrinstead of&str.Route::nameis nowOption<Cow<'static, str>>.Route::set_uriwas replaced withRoute::map_base().Route::urifield is now of typeRouteUri.Route::basewas removed in favor ofRoute.uri().base().Forwardoutcomes are now associated with aStatus.FromParamerrors now forward as 422.&Host,&Accept,&ContentType,IpAddr, andSocketAddrall forwardwith a 500.
Data and Forms
Datanow has a lifetime generic:Data<'r>.Data::open()indelibly requires a data limit.FromDataSimple. UseFromDataandlocal_cache!orlocal_cache_once!.DataStreamAPIs require limits and returnCapped<T>types.rocket::requesttorocket::form.FromQuery. Dynamic query parameters (#[get("/?<param>")]) useFromForminstead.FromFormValuewithFromFormField. AllT: FromFormFieldimplementFromForm.FromFormFieldimplementations.#[form(field = ...)]attribute to#[field(name = ...)].Status.Request Guards
CookiestoCookieJar. Its methods take&self.Flash.nametoFlash.kind,Flash.msgtoFlash.message.Request::get_param()withRequest::param().Request::get_segments()toRequest::segments().Request::get_query_value()withRequest::query_value().Segments::into_path_buf()withSegments::to_path_buf().SegmentsandQuerySegmentswithSegments<Path>andSegments<Query>.Flashconstructors now takeInto<String>instead ofAsRef<str>.State<'_, T>request guard is now&State<T>.FromRequest:FromRequest<'r>.FlashMessage:FlashMessage<'_>.Statereexports exceptrocket::State.Responders
NamedFiletorocket::fs::NamedFileContentwithcontent::Custom.Response::bodyandResponse::body_mutare now infallible methods.ResponseBuildertoBuilder.Responsebody reading methods. Use methods onr.body_mut()instead.ResponderimplforResponse. Prefer custom responders with#[derive(Responder)].Status.response::statuswere unified to all be ofthe form
Status<R>(R).General Improvements
In addition to new features and changes, Rocket saw the following improvements:
General
FromFormderive,#[route]macros, anduri!.#[field(name = uncased(...))].#[field(default = expr())].#[field]attributes on struct fields.Config::identfor configuring or removing the globalServerheader.Rocket::figment()andRocket::catchers().LocalRequest::json()andLocalResponse::json().LocalRequest::msgpack()andLocalResponse::msgpack().use m::route; routes![route]instead of needingroutes![m::route].a/b/cfalls back toa/bthena.LocalRequest::inner_mut().LocalRequestimplementsDerefMuttoRequest.Configfor all config parameter names.ErrorKind::Configto represent errors in configuration at runtime.rocket::fairing::Resulttype alias, returned byFairing::on_ignite().Rocket::mount()now accepts a base value of any type that implementsTryInto<Origin<'_>>.500error catcher.Errorto not panic if a panic is already in progress.ReferenceandAsteriskURI types.UriDisplayQueryfor C-like enums.UriDisplayQueryderive now recognizes the#[field]attribute for field renaming.Clientmethod builders acceptTryInto<Origin>allowing auri!()to be used directly.Rocketis now#[must_use].http2crate feature.rocket::execute()for executing Rocket'slaunch()future.context!macro torocket_dyn_templatesfor ad-hoc template contexts.timecrate is re-exported from the crate root.FromForm,Responder, andUriDisplayderives now fully support generics.serdesubmodules.ShieldHSTS preload header now includesincludeSubdomains.write!errors ifstdoutdisappears, preventing panics.Client::terminate()to run graceful shutdown in testing.asyncruntime, never the process.local_cache_once!macro for request-local storage.Rocket<Build>are now#[must_use], not allRocket<P>.FromFormderive.FromFormderive now collects all errors that occur.rocket_sync_db_pools.Metadata::render()inrocket_dyn_templatesfor direct template rendering.cookiesecurefeature is now properly conditionally enabled.rocket_sync_db_poolswas fixed.max_blockingconfiguration parameter to control number of blocking threads.ip_header"real IP" header configuration parameter.pool()method is emitted byrocket_sync_db_poolsfor code-generated pools.&[u8]form guard.TempFile::open()to streamTempFiledata.LocalRequest::identity().Error::pretty_print()for pretty-printing errors like Rocket.Stringis used as a route parameter.debuglog level.Outcomes now includes the relevant status code.Span::mixed_site()is used in codegen to reduce errantclippywarnings.HTTP
http2crate feature.constconstructor forMediaType.RawStrBuf, an ownedRawStr.RawStr.RawStr::percent_encode()andRawStr::strip().Hostand&Hostrequest guards.RawStr::percent_encode_bytes().NODELAYis now enabled on all connections by default.Known Media Types
image/avif.EventStream:text/event-stream.Markdown:text/markdown.MP3:audio/mpeg.CBZ:application/vnd.comicbook+zip, extension.cbz.CBR:application/vnd.comicbook-rar, extension.cbr.RAR:application/vnd.rar, extension.rar.EPUB:application/epub+zip, extension.epub.OPF:application/oebps-package+xml, extension.opf.XHTML:application/xhtml+xml, extension.xhtml.Textas an alias for thePlainmedia type.Bytesas an alias for theBinarymedia type..mjsas known JavaScript extension.Request
:in socket or IP address values in [FromFormValue].Request::rocket()to access the activeRocketinstance.Request::uri()now returns an&Origin<'r>instead of&Origin<'_>.Request::accept(),Request::content_type()reflect changes toAccept,Content-Type.Json<T>,MsgPack<T>acceptT: Deserialize, not onlyT: DeserializeOwned.rocket_sync_db_poolsuse better defaults.workers * 4.Request::host()to retrieve the client-requested host.Response
Template::try_custom()for fallible template engine customization.Template::render().X-DNS-Prefetch-Controlheader toShield.expiresvalues for private cookies.#[derive(Responder)].Serverheader is only set if one isn't already set.Content-Lengthheaders are sent even for partially readBodys.Redirectnow accepts aTryFrom<Reference>, allowing fragment parts.Trait Implementations
CloneforState.CopyandCloneforfairing::Info.DebugforRocketandClient.DefaultforStatus(returnsStatus::Ok).PartialEq,Eq,Hash,PartialOrd, andOrdforStatus.Eq,Hash, andPartialEq<&str>forOrigin.PartialEq<Cow<'_, RawStr>>>forRawStr.std::error::ErrorforError.DerefandDerefMutforLocalRequest(toRequest).DerefMutforForm,LenientForm.From<T>forJson<T>,MsgPack<T>.TryFrom<String>andTryFrom<&str>forOrigin.TryFrom<Uri>for each of the specific URI variants.FromRequestfor&Config.FromRequestforIpAddr.FromParamforPathBufFromParam,FromData, andFromFormfor&str.FromFormforJson<T>,MsgPack<T>.FromFormFieldforCowandCapped<Cow>>Responderfortokio::fs::File.Responderfor(ContentType, R) where R: Responder.Responderfor(Status, R) where R: Responderwhich overridesR's status.Responderforstd::io::Error(behaves asDebug<std::io::Error>).ResponderforEither<T, E>, equivalently toResult<T, E>.SerializeforFlash.Serialize,Deserialize,UriDisplayandFromUriParamforuuid::UuidSerialize,DeserializeforRawStr.Serialize,Deserializefor all URI types.ResponderforArc<T>,Box<T>whereT: Responder.SerializeandDeserializeforMethod.EqforMediaTypeandContentType.ResponderforBox<T: Responder + Sized>.FromFormforArc<T>.FairingforArc<dyn Fairing>.SerializeandDeserializeforStatus.Dependency Changes
serdewas introduced (1.0).futureswas introduced (0.3).binasciiwas introduced (0.1).ref-castwas introduced (1.0).atomicwas introduced (0.5).parking_lotwas introduced (0.11).ubtyewas introduced (0.10).figmentwas introduced (0.10).randwas introduced (0.8).eitherwas introduced (1.0).pin-project-litewas introduced (0.2).indexmapwas introduced (2.0).tempfilewas introduced (3.0).async-traitwas introduced (0.1).async-streamwas introduced (0.3).multerwas introduced (2.0).tokiowas introduced (1.6.1).tokio-utilwas introduced (0.6).tokio-streamwas introduced (0.1.6).byteswas introduced (1.0).normpathwas introduced (1).statewas updated to0.6.rmp-serdewas updated to0.15.uuidwas updated to0.8.terawas updated to1.10.postgreswas updated to0.19.rusqlitewas updated to0.25.r2d2_sqlitewas updated to0.18.timewas updated to0.3.handlebarswas updated to4.0.memcachewas updated to0.16.rustlswas updated to0.21.tokio-rustlswas updated to0.24.synwas updated to2.dieselwas updated to2.0.sqlxwas updated to0.7.notifywas updated to6.criterionwas updated to0.4.cookiewas updated to0.18.yansiwas updated to1.0.attywas removed.Infrastructure
The following changes were made to the project's infrastructure:
usestatements to examples in the guide.criterionand datasets extracted from real-world projects.Cargo.tomlfiles.test.shfor a+flag (e.g.+stable) to pass tocargo.test.shfor extra flags to be passed on tocargo.resolver = 2.v0.5.0-rc.4: Rocket v0.5.0-rc.4Compare Source
See the CHANGELOG, news article, migration guide, and FAQ for more information.
Configuration
📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.