async-graphql/integrations/actix-web/src/subscription.rs

192 lines
6.2 KiB
Rust
Raw Normal View History

use std::str::FromStr;
use std::time::{Duration, Instant};
2020-03-17 09:26:59 +00:00
use actix::{
2020-09-17 18:22:54 +00:00
Actor, ActorContext, ActorFuture, ActorStream, AsyncContext, ContextFutureSpawner,
StreamHandler, WrapFuture, WrapStream,
2020-03-17 09:26:59 +00:00
};
use actix_http::error::PayloadError;
use actix_http::{ws, Error};
use actix_web::web::Bytes;
use actix_web::{HttpRequest, HttpResponse};
2020-03-17 09:26:59 +00:00
use actix_web_actors::ws::{Message, ProtocolError, WebsocketContext};
use async_graphql::http::{WebSocket, WebSocketProtocols};
use async_graphql::{Data, ObjectType, Result, Schema, SubscriptionType};
use futures_util::stream::Stream;
2020-03-17 09:26:59 +00:00
2020-04-07 06:30:46 +00:00
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
2020-04-14 01:53:17 +00:00
/// Actor for subscription via websocket
pub struct WSSubscription<Query, Mutation, Subscription> {
schema: Schema<Query, Mutation, Subscription>,
protocol: WebSocketProtocols,
2020-09-17 18:22:54 +00:00
last_heartbeat: Instant,
messages: Option<async_channel::Sender<Vec<u8>>>,
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
initializer: Option<Box<dyn FnOnce(serde_json::Value) -> Result<Data> + Send + Sync>>,
2020-09-17 18:22:54 +00:00
continuation: Vec<u8>,
2020-03-17 09:26:59 +00:00
}
2020-04-14 01:53:17 +00:00
impl<Query, Mutation, Subscription> WSSubscription<Query, Mutation, Subscription>
2020-03-17 09:26:59 +00:00
where
2020-03-19 09:20:12 +00:00
Query: ObjectType + Send + Sync + 'static,
Mutation: ObjectType + Send + Sync + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
2020-03-17 09:26:59 +00:00
{
/// Start an actor for subscription connection via websocket.
pub fn start<T>(
schema: Schema<Query, Mutation, Subscription>,
request: &HttpRequest,
stream: T,
) -> Result<HttpResponse, Error>
where
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
Self::start_with_initializer(schema, request, stream, |_| Ok(Default::default()))
}
/// Start an actor for subscription connection via websocket with an initialization function.
pub fn start_with_initializer<T, F>(
schema: Schema<Query, Mutation, Subscription>,
request: &HttpRequest,
stream: T,
initializer: F,
) -> Result<HttpResponse, Error>
where
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
F: FnOnce(serde_json::Value) -> Result<Data> + Send + Sync + 'static,
{
let protocol = match request
.headers()
.get("sec-websocket-protocol")
.and_then(|value| value.to_str().ok())
.and_then(|protocols| {
protocols
.split(',')
.find_map(|p| WebSocketProtocols::from_str(p.trim()).ok())
}) {
Some(protocol) => protocol,
None => {
// default to the prior standard
WebSocketProtocols::SubscriptionsTransportWS
}
};
actix_web_actors::ws::start_with_protocols(
Self {
schema,
protocol,
last_heartbeat: Instant::now(),
messages: None,
initializer: Some(Box::new(initializer)),
continuation: Vec::new(),
},
&["graphql-transport-ws", "graphql-ws"],
request,
stream,
)
2020-04-23 07:30:12 +00:00
}
2020-09-17 18:22:54 +00:00
fn send_heartbeats(&self, ctx: &mut WebsocketContext<Self>) {
2020-04-07 06:30:46 +00:00
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
2020-09-17 18:22:54 +00:00
if Instant::now().duration_since(act.last_heartbeat) > CLIENT_TIMEOUT {
2020-03-19 09:20:12 +00:00
ctx.stop();
}
2020-04-07 06:30:46 +00:00
ctx.ping(b"");
2020-03-19 09:20:12 +00:00
});
}
2020-03-17 09:26:59 +00:00
}
2020-04-14 01:53:17 +00:00
impl<Query, Mutation, Subscription> Actor for WSSubscription<Query, Mutation, Subscription>
2020-03-17 09:26:59 +00:00
where
2020-03-19 09:20:12 +00:00
Query: ObjectType + Sync + Send + 'static,
Mutation: ObjectType + Sync + Send + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
2020-03-17 09:26:59 +00:00
{
type Context = WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
2020-09-17 18:22:54 +00:00
self.send_heartbeats(ctx);
let (tx, rx) = async_channel::unbounded();
2020-09-17 18:22:54 +00:00
WebSocket::with_data(
self.schema.clone(),
rx,
self.initializer.take(),
self.protocol,
)
.into_actor(self)
.map(|response, _act, ctx| {
ctx.text(response);
})
.finish()
.spawn(ctx);
2020-09-17 18:22:54 +00:00
self.messages = Some(tx);
2020-03-17 09:26:59 +00:00
}
}
impl<Query, Mutation, Subscription> StreamHandler<Result<Message, ProtocolError>>
2020-04-14 01:53:17 +00:00
for WSSubscription<Query, Mutation, Subscription>
2020-03-17 09:26:59 +00:00
where
2020-03-19 09:20:12 +00:00
Query: ObjectType + Sync + Send + 'static,
Mutation: ObjectType + Sync + Send + 'static,
Subscription: SubscriptionType + Send + Sync + 'static,
2020-03-17 09:26:59 +00:00
{
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
let msg = match msg {
Err(_) => {
ctx.stop();
return;
}
Ok(msg) => msg,
};
2020-09-17 18:22:54 +00:00
let message = match msg {
2020-03-17 09:26:59 +00:00
Message::Ping(msg) => {
2020-09-17 18:22:54 +00:00
self.last_heartbeat = Instant::now();
2020-03-17 09:26:59 +00:00
ctx.pong(&msg);
2020-09-17 18:22:54 +00:00
None
2020-03-17 09:26:59 +00:00
}
Message::Pong(_) => {
2020-09-17 18:22:54 +00:00
self.last_heartbeat = Instant::now();
None
2020-03-17 09:26:59 +00:00
}
2020-09-17 18:22:54 +00:00
Message::Continuation(item) => match item {
ws::Item::FirstText(bytes) | ws::Item::FirstBinary(bytes) => {
self.continuation = bytes.to_vec();
None
2020-03-17 09:26:59 +00:00
}
2020-09-17 18:22:54 +00:00
ws::Item::Continue(bytes) => {
self.continuation.extend_from_slice(&bytes);
None
}
ws::Item::Last(bytes) => {
self.continuation.extend_from_slice(&bytes);
Some(std::mem::take(&mut self.continuation))
}
},
Message::Text(s) => Some(s.into_bytes()),
Message::Binary(bytes) => Some(bytes.to_vec()),
Message::Close(_) => {
2020-03-17 09:26:59 +00:00
ctx.stop();
2020-09-17 18:22:54 +00:00
None
2020-03-17 09:26:59 +00:00
}
2020-09-17 18:22:54 +00:00
Message::Nop => None,
};
2020-03-17 09:26:59 +00:00
2020-09-17 18:22:54 +00:00
if let Some(message) = message {
let sender = self.messages.as_ref().unwrap().clone();
2020-09-17 18:22:54 +00:00
async move { sender.send(message).await }
.into_actor(self)
.map(|res, _actor, ctx| match res {
Ok(()) => {}
Err(_) => ctx.stop(),
})
.spawn(ctx)
}
2020-03-17 09:26:59 +00:00
}
}