1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 17:52:40 +01:00
actix-extras/src/ws/context.rs

265 lines
6.4 KiB
Rust
Raw Normal View History

use futures::sync::oneshot::Sender;
use futures::unsync::oneshot;
2018-04-14 01:02:01 +02:00
use futures::{Async, Poll};
use smallvec::SmallVec;
2018-04-14 01:02:01 +02:00
use actix::dev::{ContextImpl, SyncEnvelope, ToEnvelope};
use actix::fut::ActorFuture;
2018-04-14 01:02:01 +02:00
use actix::{Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message,
SpawnHandle, Syn, Unsync};
2018-04-14 01:02:01 +02:00
use body::{Binary, Body};
use context::{ActorHttpContext, Drain, Frame as ContextFrame};
2018-01-27 19:04:56 +01:00
use error::{Error, ErrorInternalServerError};
use httprequest::HttpRequest;
2018-02-10 09:05:20 +01:00
use ws::frame::Frame;
use ws::proto::{CloseReason, OpCode};
2018-03-30 00:00:18 +02:00
/// Execution context for `WebSockets` actors
2018-04-14 01:02:01 +02:00
pub struct WebsocketContext<A, S = ()>
where
A: Actor<Context = WebsocketContext<A, S>>,
{
inner: ContextImpl<A>,
stream: Option<SmallVec<[ContextFrame; 4]>>,
request: HttpRequest<S>,
disconnected: bool,
}
2018-04-14 01:02:01 +02:00
impl<A, S> ActorContext for WebsocketContext<A, S>
where
A: Actor<Context = Self>,
{
fn stop(&mut self) {
self.inner.stop();
}
fn terminate(&mut self) {
self.inner.terminate()
}
fn state(&self) -> ActorState {
self.inner.state()
}
}
2018-04-14 01:02:01 +02:00
impl<A, S> AsyncContext<A> for WebsocketContext<A, S>
where
A: Actor<Context = Self>,
{
fn spawn<F>(&mut self, fut: F) -> SpawnHandle
2018-04-14 01:02:01 +02:00
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
{
self.inner.spawn(fut)
}
fn wait<F>(&mut self, fut: F)
2018-04-14 01:02:01 +02:00
where
F: ActorFuture<Item = (), Error = (), Actor = A> + 'static,
{
self.inner.wait(fut)
}
#[doc(hidden)]
#[inline]
fn waiting(&self) -> bool {
2018-04-14 01:02:01 +02:00
self.inner.waiting() || self.inner.state() == ActorState::Stopping
|| self.inner.state() == ActorState::Stopped
}
fn cancel_future(&mut self, handle: SpawnHandle) -> bool {
self.inner.cancel_future(handle)
}
2018-01-31 21:57:02 +01:00
#[doc(hidden)]
#[inline]
2018-02-13 01:08:04 +01:00
fn unsync_address(&mut self) -> Addr<Unsync, A> {
self.inner.unsync_address()
}
2018-01-31 21:57:02 +01:00
#[doc(hidden)]
#[inline]
2018-02-13 01:08:04 +01:00
fn sync_address(&mut self) -> Addr<Syn, A> {
self.inner.sync_address()
}
}
2018-04-14 01:02:01 +02:00
impl<A, S: 'static> WebsocketContext<A, S>
where
A: Actor<Context = Self>,
{
#[inline]
pub fn new(req: HttpRequest<S>, actor: A) -> WebsocketContext<A, S> {
WebsocketContext::from_request(req).actor(actor)
}
pub fn from_request(req: HttpRequest<S>) -> WebsocketContext<A, S> {
WebsocketContext {
inner: ContextImpl::new(None),
stream: None,
request: req,
disconnected: false,
}
}
#[inline]
pub fn actor(mut self, actor: A) -> WebsocketContext<A, S> {
self.inner.set_actor(actor);
self
}
}
2018-04-14 01:02:01 +02:00
impl<A, S> WebsocketContext<A, S>
where
A: Actor<Context = Self>,
{
/// Write payload
#[inline]
2018-02-10 09:05:20 +01:00
fn write(&mut self, data: Binary) {
if !self.disconnected {
2018-02-10 05:43:14 +01:00
if self.stream.is_none() {
self.stream = Some(SmallVec::new());
}
let stream = self.stream.as_mut().unwrap();
2018-02-10 09:05:20 +01:00
stream.push(ContextFrame::Chunk(Some(data)));
self.inner.modify();
} else {
warn!("Trying to write to disconnected response");
}
}
/// Shared application state
#[inline]
pub fn state(&self) -> &S {
self.request.state()
}
/// Incoming request
#[inline]
pub fn request(&mut self) -> &mut HttpRequest<S> {
&mut self.request
}
/// Send text frame
2018-02-10 05:43:14 +01:00
#[inline]
2018-03-04 19:18:42 +01:00
pub fn text<T: Into<Binary>>(&mut self, text: T) {
2018-02-10 09:05:20 +01:00
self.write(Frame::message(text.into(), OpCode::Text, true, false));
}
/// Send binary frame
2018-02-10 05:43:14 +01:00
#[inline]
pub fn binary<B: Into<Binary>>(&mut self, data: B) {
2018-02-10 09:05:20 +01:00
self.write(Frame::message(data, OpCode::Binary, true, false));
}
/// Send ping frame
2018-02-10 05:43:14 +01:00
#[inline]
pub fn ping(&mut self, message: &str) {
2018-04-29 18:09:08 +02:00
self.write(Frame::message(
Vec::from(message),
OpCode::Ping,
true,
false,
));
}
/// Send pong frame
2018-02-10 05:43:14 +01:00
#[inline]
pub fn pong(&mut self, message: &str) {
2018-04-29 18:09:08 +02:00
self.write(Frame::message(
Vec::from(message),
OpCode::Pong,
true,
false,
));
}
/// Send close frame
2018-02-10 05:43:14 +01:00
#[inline]
pub fn close(&mut self, reason: Option<CloseReason>) {
self.write(Frame::close(reason, false));
}
/// Returns drain future
pub fn drain(&mut self) -> Drain<A> {
let (tx, rx) = oneshot::channel();
self.inner.modify();
self.add_frame(ContextFrame::Drain(tx));
Drain::new(rx)
}
/// Check if connection still open
#[inline]
pub fn connected(&self) -> bool {
!self.disconnected
}
2018-02-10 05:43:14 +01:00
#[inline]
fn add_frame(&mut self, frame: ContextFrame) {
if self.stream.is_none() {
self.stream = Some(SmallVec::new());
}
2018-04-29 18:09:08 +02:00
if let Some(s) = self.stream.as_mut() {
s.push(frame)
}
self.inner.modify();
}
2018-01-28 18:47:46 +01:00
/// Handle of the running future
///
/// SpawnHandle is the handle returned by `AsyncContext::spawn()` method.
pub fn handle(&self) -> SpawnHandle {
self.inner.curr_handle()
}
}
2018-04-14 01:02:01 +02:00
impl<A, S> ActorHttpContext for WebsocketContext<A, S>
where
A: Actor<Context = Self>,
S: 'static,
{
#[inline]
fn disconnected(&mut self) {
self.disconnected = true;
self.stop();
}
fn poll(&mut self) -> Poll<Option<SmallVec<[ContextFrame; 4]>>, Error> {
2018-04-29 18:09:08 +02:00
let ctx: &mut WebsocketContext<A, S> = unsafe { &mut *(self as *mut _) };
2018-03-16 21:37:47 +01:00
if self.inner.alive() && self.inner.poll(ctx).is_err() {
2018-04-14 01:02:01 +02:00
return Err(ErrorInternalServerError("error"));
}
// frames
if let Some(data) = self.stream.take() {
Ok(Async::Ready(Some(data)))
} else if self.inner.alive() {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(None))
}
}
}
2018-02-13 01:08:04 +01:00
impl<A, M, S> ToEnvelope<Syn, A, M> for WebsocketContext<A, S>
2018-04-14 01:02:01 +02:00
where
A: Actor<Context = WebsocketContext<A, S>> + Handler<M>,
M: Message + Send + 'static,
M::Result: Send,
{
2018-02-13 01:08:04 +01:00
fn pack(msg: M, tx: Option<Sender<M::Result>>) -> SyncEnvelope<A> {
SyncEnvelope::new(msg, tx)
}
}
impl<A, S> From<WebsocketContext<A, S>> for Body
2018-04-14 01:02:01 +02:00
where
A: Actor<Context = WebsocketContext<A, S>>,
S: 'static,
{
fn from(ctx: WebsocketContext<A, S>) -> Body {
Body::Actor(Box::new(ctx))
}
}