1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use crate::context::Data;
use crate::http::{GQLError, GQLRequest, GQLResponse};
use crate::{
    FieldError, FieldResult, ObjectType, QueryResponse, Result, Schema, SubscriptionStreams,
    SubscriptionTransport, SubscriptionType, Variables,
};
use bytes::Bytes;
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Serialize, Deserialize)]
struct OperationMessage {
    #[serde(rename = "type")]
    ty: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    payload: Option<serde_json::Value>,
}

/// WebSocket transport for subscription
#[derive(Default)]
pub struct WebSocketTransport {
    id_to_sid: HashMap<String, usize>,
    sid_to_id: HashMap<usize, String>,
    data: Arc<Data>,
    init_context_data: Option<Box<dyn Fn(serde_json::Value) -> FieldResult<Data> + Send + Sync>>,
}

impl WebSocketTransport {
    /// Creates a websocket transport and sets the function that converts the `payload` of the `connect_init` message to `Data`.
    pub fn new<F: Fn(serde_json::Value) -> FieldResult<Data> + Send + Sync + 'static>(
        init_context_data: F,
    ) -> Self {
        WebSocketTransport {
            init_context_data: Some(Box::new(init_context_data)),
            ..WebSocketTransport::default()
        }
    }
}

#[async_trait::async_trait]
impl SubscriptionTransport for WebSocketTransport {
    type Error = FieldError;

    async fn handle_request<Query, Mutation, Subscription>(
        &mut self,
        schema: &Schema<Query, Mutation, Subscription>,
        streams: &mut SubscriptionStreams,
        data: Bytes,
    ) -> std::result::Result<Option<Bytes>, Self::Error>
    where
        Query: ObjectType + Sync + Send + 'static,
        Mutation: ObjectType + Sync + Send + 'static,
        Subscription: SubscriptionType + Sync + Send + 'static,
    {
        match serde_json::from_slice::<OperationMessage>(&data) {
            Ok(msg) => match msg.ty.as_str() {
                "connection_init" => {
                    if let Some(payload) = msg.payload {
                        if let Some(init_context_data) = &self.init_context_data {
                            self.data = Arc::new(init_context_data(payload)?);
                        }
                    }
                    Ok(Some(
                        serde_json::to_vec(&OperationMessage {
                            ty: "connection_ack".to_string(),
                            id: None,
                            payload: None,
                        })
                        .unwrap()
                        .into(),
                    ))
                }
                "start" => {
                    if let (Some(id), Some(payload)) = (msg.id, msg.payload) {
                        if let Ok(request) = serde_json::from_value::<GQLRequest>(payload) {
                            let variables = request
                                .variables
                                .map(|value| Variables::parse_from_json(value).ok())
                                .flatten()
                                .unwrap_or_default();
                            match schema
                                .create_subscription_stream(
                                    &request.query,
                                    request.operation_name.as_deref(),
                                    variables,
                                    Some(self.data.clone()),
                                )
                                .await
                            {
                                Ok(stream) => {
                                    let stream_id = streams.add(stream);
                                    self.id_to_sid.insert(id.clone(), stream_id);
                                    self.sid_to_id.insert(stream_id, id);
                                    Ok(None)
                                }
                                Err(err) => Ok(Some(
                                    serde_json::to_vec(&OperationMessage {
                                        ty: "error".to_string(),
                                        id: Some(id),
                                        payload: Some(
                                            serde_json::to_value(GQLError(&err)).unwrap(),
                                        ),
                                    })
                                    .unwrap()
                                    .into(),
                                )),
                            }
                        } else {
                            Ok(None)
                        }
                    } else {
                        Ok(None)
                    }
                }
                "stop" => {
                    if let Some(id) = msg.id {
                        if let Some(id) = self.id_to_sid.remove(&id) {
                            self.sid_to_id.remove(&id);
                            streams.remove(id);
                        }
                    }
                    Ok(None)
                }
                "connection_terminate" => Err("connection_terminate".into()),
                _ => Err("Unknown op".into()),
            },
            Err(err) => Err(err.into()),
        }
    }

    fn handle_response(&mut self, id: usize, res: Result<serde_json::Value>) -> Option<Bytes> {
        if let Some(id) = self.sid_to_id.get(&id) {
            match res {
                Ok(value) => Some(
                    serde_json::to_vec(&OperationMessage {
                        ty: "data".to_string(),
                        id: Some(id.clone()),
                        payload: Some(
                            serde_json::to_value(GQLResponse(Ok(QueryResponse {
                                label: None,
                                path: None,
                                data: value,
                                extensions: None,
                                cache_control: Default::default(),
                            })))
                            .unwrap(),
                        ),
                    })
                    .unwrap()
                    .into(),
                ),
                Err(err) => Some(
                    serde_json::to_vec(&OperationMessage {
                        ty: "error".to_string(),
                        id: Some(id.to_string()),
                        payload: Some(serde_json::to_value(GQLError(&err)).unwrap()),
                    })
                    .unwrap()
                    .into(),
                ),
            }
        } else {
            None
        }
    }
}