Skip to main content

EventStream

Struct EventStream 

Source
pub struct EventStream { /* private fields */ }
Expand description

A stream of server-sent events, sent as a response.

use laravel::http::sse::{Event, EventStream};
use laravel::stream::{self, Stream, StreamExt};
use laravel::view::{data, view};

async fn stream() -> EventStream {
    EventStream::new(added_tasks().map(|task| {
        Event::new("task-added", view("tasks.index", data! { task }).fragment("row"))
    }))
}

Data sent without a name becomes an update event. The stream ends with an update event whose data is </stream>, which the @laravel/stream hooks listen for:

use laravel::http::Json;
use laravel::http::sse::EventStream;
use laravel::stream::{self, StreamExt};

async fn progress() -> EventStream {
    // Sends `update` events of `{"done":1}`, `{"done":2}`, and `{"done":3}`...
    let events = stream::iter(1..=3).map(|done| Json(serde_json::json!({ "done": done })));

    EventStream::new(events)
}

Each view renders as its event is sent. When a view fails to render, or JSON can’t be serialized, Laravel reports the error and skips the event. By then the response has already begun, so it can’t become an error page.

On a quiet stream, the response sends a comment every 15 seconds so proxies don’t close the connection. The stream ends when the server begins to shut down, so it doesn’t hold up a deploy. In that case, the stream ends without its end event, so browsers reconnect to the new server.

Implementations§

Source§

impl EventStream

Send a cookie with this response. A (name, value) pair uses the default attributes, and a Cookie sets its own. The cookie replaces any cookie that this response already sends with the same name, path, and domain.

use laravel::http::{Redirect, Response};

let response = Response::new("Saved").with_cookie(("theme", "dark"));
let redirect = Redirect::to("/").with_cookie(("theme", "dark"));

Remove a browser cookie by sending an expired cookie. A name uses the default path and domain. To match a custom path or domain, pass a Cookie. The cookie values that the current request returns stay unchanged.

use laravel::http::Response;
use laravel::cookie::Cookie;

let response = Response::new("Signed out")
    .without_cookie("remember")
    .without_cookie(Cookie::new("tour", "").path("/admin"));
Source

pub fn with_header<K, V>(self, name: K, value: V) -> EventStream

Send a header with the response, replacing any header with the same name, including one the response would otherwise send:

use laravel::view::{View, view};

async fn report() -> View {
    view("reports.show", ()).with_header("cache-control", "no-store")
}

A name or value that isn’t a valid header turns the response into a 500 error when the response is sent.

Source

pub fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> EventStream

Send several headers with the response, such as .with_headers([("x-one", "1"), ("x-two", "2")]). Each header replaces any header with the same name, so when the list holds a name twice, the last value wins.

A name or value that isn’t a valid header turns the response into a 500 error when the response is sent.

Source

pub fn new<E>(events: impl Stream<Item = E> + Send + 'static) -> EventStream
where E: Into<Event> + 'static,

Send the stream’s events. Each item is an Event, or data for an update event.

Source

pub fn channel<F, Fut>(produce: F) -> EventStream
where F: FnOnce(Sender) -> Fut, Fut: Future<Output = Result<(), Error>> + Send + 'static,

Send each event a producer sends, as soon as it sends it. The producer runs as its own task in the request’s context, so helpers such as view() work inside it and errors propagate with ?. The task starts when Laravel builds the response from this value.

Sender::send fails with ClientGone once the client disconnects, so ? stops the producer without reporting anything. When the producer returns any other error, or panics, Laravel reports it and ends the stream early without sending the end event.

use laravel::http::sse::{Event, EventStream};

async fn progress() -> EventStream {
    EventStream::channel(async |sse| {
        sse.send("Starting").await?;
        sse.send(Event::new("done", "Finished")).await?;
        Ok(())
    })
}
Source

pub fn end_with(self, event: impl Into<Event>) -> EventStream

End the stream with this event, instead of an update event of </stream>.

Source

pub fn without_end_event(self) -> EventStream

End the stream without an end event.

Source

pub fn keep_alive( self, every: impl Into<ZonedDateTimeArithmetic>, ) -> EventStream

Send a comment at this interval on a quiet stream, such as 30.seconds(), so proxies don’t close the connection. The default is every 15 seconds.

Trait Implementations§

Source§

impl Debug for EventStream

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl IntoResponse for EventStream

Source§

fn into_response(self) -> Response

Turn this into a Response. Read more
Send a cookie with this response, replacing any cookie the response already sends with the same name, path, and domain. Read more
Remove a browser cookie. Pass the cookie’s name, or a Cookie with the path and domain that set it. Read more
Source§

fn with_header<K, V>(self, name: K, value: V) -> Response

Send a header with the response, replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.
Source§

fn with_headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> Response

Send several headers with the response, each replacing any header with the same name. A name or value that isn’t a valid header makes the response a 500 error.

Auto Trait Implementations§

§

impl !RefUnwindSafe for EventStream

§

impl !Sync for EventStream

§

impl !UnwindSafe for EventStream

§

impl Forget for EventStream

§

impl Freeze for EventStream
where *const dyn Stream<Item = ChannelItem> + Send is !null: Freeze, PhantomData<dyn Stream<Item = ChannelItem> + Send>: Freeze, *const dyn Future<Output = ()> + Send is !null: Freeze, PhantomData<dyn Future<Output = ()> + Send>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze, *const ArcInner<dyn Render> is !null: Freeze, PhantomData<ArcInner<dyn Render>>: Freeze, *const [Pos] is !null: Freeze, PhantomData<[Pos]>: Freeze, PhantomData<Bucket<HeaderValue>>: Freeze, PhantomData<ExtraValue<HeaderValue>>: Freeze, *const ArcInner<Inner> is !null: Freeze, PhantomData<ArcInner<Inner>>: Freeze,

§

impl Move for EventStream

§

impl Send for EventStream
where BoxRaw<dyn Stream<Item = ChannelItem> + Send>: Send, BoxRaw<dyn Future<Output = ()> + Send>: Send, RawVecInner: Send, Arc<dyn Render>: Send, BoxRaw<[Pos]>: Send, Bytes: Send, Arc<Inner>: Send,

§

impl Unpin for EventStream
where Box<dyn Stream<Item = ChannelItem> + Send>: Unpin, Box<dyn Future<Output = ()> + Send>: Unpin, *const u8 is !null: Unpin, Arc<dyn Render>: Unpin, Box<[Pos]>: Unpin, *const u8: Unpin, Align8<*mut ()>: Unpin, &'static Vtable: Unpin, Arc<Inner>: Unpin,

§

impl UnsafeUnpin for EventStream
where *const dyn Stream<Item = ChannelItem> + Send is !null: UnsafeUnpin, PhantomData<dyn Stream<Item = ChannelItem> + Send>: UnsafeUnpin, *const dyn Future<Output = ()> + Send is !null: UnsafeUnpin, PhantomData<dyn Future<Output = ()> + Send>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<dyn Render> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Render>>: UnsafeUnpin, *const [Pos] is !null: UnsafeUnpin, PhantomData<[Pos]>: UnsafeUnpin, PhantomData<Bucket<HeaderValue>>: UnsafeUnpin, PhantomData<ExtraValue<HeaderValue>>: UnsafeUnpin, *const ArcInner<Inner> is !null: UnsafeUnpin, PhantomData<ArcInner<Inner>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> FillValue<Option<T>> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<Option<T>, Error>

Resolves the column’s value. Read more
Source§

impl<T> FillValue<T> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<T, Error>

Resolves the column’s value. Read more
Source§

impl<K> ForeignKey<K> for K

Source§

fn key(&self) -> Option<&K>

Returns the key, or None when the field holds no key.
Source§

fn __from_key(key: K) -> K

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T, N> NotifiedBy<T> for N
where T: Notification<N>,

Source§

fn __routes(&self) -> Vec<Route>

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, V> UpdateValue<T> for V
where V: FillValue<T>,

Source§

fn __update<M, U>(self, column: Column<M, T>, update: U) -> U
where M: Model, U: Updates<M>, T: IntoExpr + Clone + Send + Sync + 'static,

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more