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.
150 lines
4.8 KiB
Rust
150 lines
4.8 KiB
Rust
use actix::{
|
|
Actor, ActorContext, ActorFuture, ActorStream, AsyncContext, ContextFutureSpawner,
|
|
StreamHandler, WrapFuture, WrapStream,
|
|
};
|
|
use actix_http::ws;
|
|
use actix_web_actors::ws::{Message, ProtocolError, WebsocketContext};
|
|
use async_graphql::http::WebSocket;
|
|
use async_graphql::{resolver_utils::ObjectType, Data, Result, Schema, SubscriptionType};
|
|
use futures::channel::mpsc;
|
|
use futures::SinkExt;
|
|
use std::time::{Duration, Instant};
|
|
|
|
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
|
|
|
/// Actor for subscription via websocket
|
|
pub struct WSSubscription<Query, Mutation, Subscription> {
|
|
schema: Option<Schema<Query, Mutation, Subscription>>,
|
|
last_heartbeat: Instant,
|
|
messages: Option<mpsc::UnboundedSender<Vec<u8>>>,
|
|
initializer: Option<Box<dyn FnOnce(serde_json::Value) -> Result<Data> + Send + Sync>>,
|
|
continuation: Vec<u8>,
|
|
}
|
|
|
|
impl<Query, Mutation, Subscription> WSSubscription<Query, Mutation, Subscription>
|
|
where
|
|
Query: ObjectType + Send + Sync + 'static,
|
|
Mutation: ObjectType + Send + Sync + 'static,
|
|
Subscription: SubscriptionType + Send + Sync + 'static,
|
|
{
|
|
/// Create an actor for subscription connection via websocket.
|
|
pub fn new(schema: Schema<Query, Mutation, Subscription>) -> Self {
|
|
Self {
|
|
schema: Some(schema),
|
|
last_heartbeat: Instant::now(),
|
|
messages: None,
|
|
initializer: None,
|
|
continuation: Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// Set a context data initialization function.
|
|
pub fn initializer<F>(self, f: F) -> Self
|
|
where
|
|
F: FnOnce(serde_json::Value) -> Result<Data> + Send + Sync + 'static,
|
|
{
|
|
Self {
|
|
initializer: Some(Box::new(f)),
|
|
..self
|
|
}
|
|
}
|
|
|
|
fn send_heartbeats(&self, ctx: &mut WebsocketContext<Self>) {
|
|
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
|
|
if Instant::now().duration_since(act.last_heartbeat) > CLIENT_TIMEOUT {
|
|
ctx.stop();
|
|
}
|
|
ctx.ping(b"");
|
|
});
|
|
}
|
|
}
|
|
|
|
impl<Query, Mutation, Subscription> Actor for WSSubscription<Query, Mutation, Subscription>
|
|
where
|
|
Query: ObjectType + Sync + Send + 'static,
|
|
Mutation: ObjectType + Sync + Send + 'static,
|
|
Subscription: SubscriptionType + Send + Sync + 'static,
|
|
{
|
|
type Context = WebsocketContext<Self>;
|
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
|
self.send_heartbeats(ctx);
|
|
|
|
let (tx, rx) = mpsc::unbounded();
|
|
|
|
WebSocket::with_data(self.schema.take().unwrap(), rx, self.initializer.take())
|
|
.into_actor(self)
|
|
.map(|response, _act, ctx| {
|
|
ctx.text(response);
|
|
})
|
|
.finish()
|
|
.spawn(ctx);
|
|
|
|
self.messages = Some(tx);
|
|
}
|
|
}
|
|
|
|
impl<Query, Mutation, Subscription> StreamHandler<Result<Message, ProtocolError>>
|
|
for WSSubscription<Query, Mutation, Subscription>
|
|
where
|
|
Query: ObjectType + Sync + Send + 'static,
|
|
Mutation: ObjectType + Sync + Send + 'static,
|
|
Subscription: SubscriptionType + Send + Sync + 'static,
|
|
{
|
|
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
|
|
let msg = match msg {
|
|
Err(_) => {
|
|
ctx.stop();
|
|
return;
|
|
}
|
|
Ok(msg) => msg,
|
|
};
|
|
|
|
let message = match msg {
|
|
Message::Ping(msg) => {
|
|
self.last_heartbeat = Instant::now();
|
|
ctx.pong(&msg);
|
|
None
|
|
}
|
|
Message::Pong(_) => {
|
|
self.last_heartbeat = Instant::now();
|
|
None
|
|
}
|
|
Message::Continuation(item) => match item {
|
|
ws::Item::FirstText(bytes) | ws::Item::FirstBinary(bytes) => {
|
|
self.continuation = bytes.to_vec();
|
|
None
|
|
}
|
|
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(_) => {
|
|
ctx.stop();
|
|
None
|
|
}
|
|
Message::Nop => None,
|
|
};
|
|
|
|
if let Some(message) = message {
|
|
let mut sender = self.messages.as_ref().unwrap().clone();
|
|
|
|
async move { sender.send(message).await }
|
|
.into_actor(self)
|
|
.map(|res, _actor, ctx| match res {
|
|
Ok(()) => {}
|
|
Err(_) => ctx.stop(),
|
|
})
|
|
.spawn(ctx)
|
|
}
|
|
}
|
|
}
|