Struct actix_web_actors::HttpContext

source ·
pub struct HttpContext<A>
where A: Actor<Context = HttpContext<A>>,
{ /* private fields */ }
Expand description

Execution context for HTTP actors

§Example

A demonstration of server-sent events using actors:

use std::time::Duration;

use actix::{Actor, AsyncContext};
use actix_web::{get, http::header, App, HttpResponse, HttpServer};
use actix_web_actors::HttpContext;
use bytes::Bytes;

struct MyActor {
    count: usize,
}

impl Actor for MyActor {
    type Context = HttpContext<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        ctx.run_later(Duration::from_millis(100), Self::write);
    }
}

impl MyActor {
    fn write(&mut self, ctx: &mut HttpContext<Self>) {
        self.count += 1;
        if self.count > 3 {
            ctx.write_eof()
        } else {
            ctx.write(Bytes::from(format!("event: count\ndata: {}\n\n", self.count)));
            ctx.run_later(Duration::from_millis(100), Self::write);
        }
    }
}

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .insert_header(header::ContentType(mime::TEXT_EVENT_STREAM))
        .streaming(HttpContext::create(MyActor { count: 0 }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

Implementations§

source§

impl<A> HttpContext<A>
where A: Actor<Context = Self>,

source

pub fn create(actor: A) -> impl Stream<Item = Result<Bytes, Error>>

Create a new HTTP Context from a request and an actor

source

pub fn with_factory<F>(f: F) -> impl Stream<Item = Result<Bytes, Error>>
where F: FnOnce(&mut Self) -> A + 'static,

Create a new HTTP Context

source§

impl<A> HttpContext<A>
where A: Actor<Context = Self>,

source

pub fn write(&mut self, data: Bytes)

Write payload

source

pub fn write_eof(&mut self)

Indicate end of streaming payload. Also this method calls Self::close.

source

pub fn handle(&self) -> SpawnHandle

Handle of the running future

SpawnHandle is the handle returned by AsyncContext::spawn() method.

Trait Implementations§

source§

impl<A> ActorContext for HttpContext<A>
where A: Actor<Context = Self>,

source§

fn stop(&mut self)

Immediately stop processing incoming messages and switch to a stopping state. This only affects actors that are currently running. Future attempts to queue messages will fail.
source§

fn terminate(&mut self)

Terminate actor execution unconditionally. This sets the actor into the stopped state. This causes future attempts to queue messages to fail.
source§

fn state(&self) -> ActorState

Retrieve the current Actor execution state.
source§

impl<A> AsyncContext<A> for HttpContext<A>
where A: Actor<Context = Self>,

source§

fn spawn<F>(&mut self, fut: F) -> SpawnHandle
where F: ActorFuture<A, Output = ()> + 'static,

Spawns a future into the context. Read more
source§

fn wait<F>(&mut self, fut: F)
where F: ActorFuture<A, Output = ()> + 'static,

Spawns a future into the context, waiting for it to resolve. Read more
source§

fn cancel_future(&mut self, handle: SpawnHandle) -> bool

Cancels a spawned future. Read more
source§

fn address(&self) -> Addr<A>

Returns the address of the context.
§

fn waiting(&self) -> bool

Checks if the context is paused (waiting for future completion or stopping).
§

fn add_stream<S>(&mut self, fut: S) -> SpawnHandle
where S: Stream + 'static, A: StreamHandler<<S as Stream>::Item>,

Registers a stream with the context. Read more
§

fn add_message_stream<S>(&mut self, fut: S)
where S: Stream + 'static, <S as Stream>::Item: Message, A: Handler<<S as Stream>::Item>,

Registers a stream with the context, ignoring errors. Read more
§

fn notify<M>(&mut self, msg: M)
where A: Handler<M>, M: Message + 'static,

Sends the message msg to self. This bypasses the mailbox capacity, and will always queue the message. If the actor is in the stopped state, an error will be raised.
§

fn notify_later<M>(&mut self, msg: M, after: Duration) -> SpawnHandle
where A: Handler<M>, M: Message + 'static,

Sends the message msg to self after a specified period of time. Read more
§

fn run_later<F>(&mut self, dur: Duration, f: F) -> SpawnHandle
where F: FnOnce(&mut A, &mut <A as Actor>::Context) + 'static,

Executes a closure after a specified period of time. Read more
§

fn run_interval<F>(&mut self, dur: Duration, f: F) -> SpawnHandle
where F: FnMut(&mut A, &mut <A as Actor>::Context) + 'static,

Spawns a job to execute the given closure periodically, at a specified fixed interval.
source§

impl<A> AsyncContextParts<A> for HttpContext<A>
where A: Actor<Context = Self>,

source§

fn parts(&mut self) -> &mut ContextParts<A>

source§

impl<A, M> ToEnvelope<A, M> for HttpContext<A>
where A: Actor<Context = HttpContext<A>> + Handler<M>, M: Message + Send + 'static, M::Result: Send,

source§

fn pack(msg: M, tx: Option<Sender<M::Result>>) -> Envelope<A>

Pack message into suitable envelope

Auto Trait Implementations§

§

impl<A> Freeze for HttpContext<A>

§

impl<A> !RefUnwindSafe for HttpContext<A>

§

impl<A> !Send for HttpContext<A>

§

impl<A> !Sync for HttpContext<A>

§

impl<A> Unpin for HttpContext<A>

§

impl<A> !UnwindSafe for HttpContext<A>

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<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> Same for T

§

type Output = T

Should always be Self
source§

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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