Skip to main content

link_cli/graphql/
server.rs

1//! HTTP and WebSocket transport of the GraphQL layer.
2//!
3//! Connections have threads; requests run on the serving thread through a
4//! channel, as in [`crate::protocol`], so the store needs no locks. After each
5//! write every subscription runs again, and is sent if its answer changed.
6//! WebSocket speaks the subprotocols `graphql-ws` (`subscriptions-transport-ws`,
7//! which `DeepClient` uses) and `graphql-transport-ws` (the `graphql-ws`
8//! library).
9
10use std::collections::HashMap;
11use std::io::{BufRead, BufReader, Read, Write};
12use std::net::{SocketAddr, TcpListener, TcpStream};
13use std::sync::mpsc::{channel, Receiver, Sender};
14use std::sync::{Arc, Mutex};
15
16use anyhow::Result;
17
18use super::crypto::websocket_accept;
19use super::execute::{execute, Auth, GqlError, Settings};
20use super::json::Json;
21use super::store::DeepStore;
22
23const MAX_BODY: usize = 64 * 1024 * 1024;
24
25type Shared = Arc<Mutex<TcpStream>>;
26
27enum Job {
28    Http {
29        body: Json,
30        auth: Auth,
31        reply: Sender<Json>,
32    },
33    Subscribe {
34        connection: u64,
35        id: String,
36        payload: Json,
37        auth: Auth,
38        legacy: bool,
39        socket: Shared,
40    },
41    Stop {
42        connection: u64,
43        id: Option<String>,
44    },
45}
46
47struct Subscription {
48    connection: u64,
49    id: String,
50    query: String,
51    operation: Option<String>,
52    variables: Json,
53    auth: Auth,
54    legacy: bool,
55    socket: Shared,
56    last: String,
57}
58
59pub struct GraphqlServer {
60    listener: TcpListener,
61}
62
63fn request_parts(body: &Json) -> (String, Option<String>, Json) {
64    (
65        body.get("query")
66            .and_then(Json::as_str)
67            .unwrap_or("")
68            .to_string(),
69        body.get("operationName")
70            .and_then(Json::as_str)
71            .map(str::to_string),
72        body.get("variables").cloned().unwrap_or(Json::Null),
73    )
74}
75
76impl GraphqlServer {
77    pub fn bind(address: &str) -> Result<Self> {
78        Ok(Self {
79            listener: TcpListener::bind(address)?,
80        })
81    }
82
83    pub fn local_addr(&self) -> Result<SocketAddr> {
84        Ok(self.listener.local_addr()?)
85    }
86
87    /// Serves until the process stops.
88    pub fn serve(self, store: &mut DeepStore, settings: Settings) -> Result<()> {
89        let (jobs, inbox) = channel();
90        let settings = Arc::new(settings);
91        let thread_settings = Arc::clone(&settings);
92        let listener = self.listener;
93        std::thread::spawn(move || {
94            let mut next = 0;
95            for stream in listener.incoming().flatten() {
96                next += 1;
97                let (jobs, settings, connection) =
98                    (jobs.clone(), Arc::clone(&thread_settings), next);
99                std::thread::spawn(move || {
100                    let _ = handle(stream, jobs, &settings, connection);
101                });
102            }
103        });
104        run_jobs(store, &settings, inbox);
105        Ok(())
106    }
107}
108
109fn run_jobs(store: &mut DeepStore, settings: &Settings, inbox: Receiver<Job>) {
110    let mut subscriptions: Vec<Subscription> = Vec::new();
111    for job in inbox {
112        match job {
113            Job::Http { body, auth, reply } => {
114                let (query, operation, variables) = request_parts(&body);
115                let before = store.generation;
116                let (response, _) = execute(
117                    store,
118                    settings,
119                    &query,
120                    operation.as_deref(),
121                    &variables,
122                    auth,
123                );
124                let _ = reply.send(response);
125                if store.generation != before {
126                    refresh(store, settings, &mut subscriptions);
127                }
128            }
129            Job::Subscribe {
130                connection,
131                id,
132                payload,
133                auth,
134                legacy,
135                socket,
136            } => {
137                let (query, operation, variables) = request_parts(&payload);
138                let before = store.generation;
139                let (response, _) = execute(
140                    store,
141                    settings,
142                    &query,
143                    operation.as_deref(),
144                    &variables,
145                    auth,
146                );
147                if response.get("errors").is_some() {
148                    let _ = send_error(&socket, &id, &response, legacy);
149                } else {
150                    let last = response.write();
151                    let _ = send_data(&socket, &id, &last, legacy);
152                    subscriptions.push(Subscription {
153                        connection,
154                        id,
155                        query,
156                        operation,
157                        variables,
158                        auth,
159                        legacy,
160                        socket,
161                        last,
162                    });
163                }
164                if store.generation != before {
165                    refresh(store, settings, &mut subscriptions);
166                }
167            }
168            Job::Stop { connection, id } => subscriptions.retain(|subscription| {
169                subscription.connection != connection
170                    || id.as_ref().is_some_and(|id| *id != subscription.id)
171            }),
172        }
173    }
174}
175
176fn refresh(store: &mut DeepStore, settings: &Settings, subscriptions: &mut Vec<Subscription>) {
177    subscriptions.retain_mut(|subscription| {
178        let (response, _) = execute(
179            store,
180            settings,
181            &subscription.query,
182            subscription.operation.as_deref(),
183            &subscription.variables,
184            subscription.auth,
185        );
186        let text = response.write();
187        if text == subscription.last {
188            return true;
189        }
190        subscription.last = text;
191        send_data(
192            &subscription.socket,
193            &subscription.id,
194            &subscription.last,
195            subscription.legacy,
196        )
197        .is_ok()
198    });
199}
200
201fn message(kind: &str, id: Option<&str>, payload: Option<&str>) -> String {
202    let id = id.map_or_else(String::new, |id| {
203        format!(",\"id\":{}", Json::str(id).write())
204    });
205    let payload = payload.map_or_else(String::new, |payload| format!(",\"payload\":{payload}"));
206    format!("{{\"type\":\"{kind}\"{id}{payload}}}")
207}
208
209fn send_data(socket: &Shared, id: &str, payload: &str, legacy: bool) -> std::io::Result<()> {
210    let kind = if legacy { "data" } else { "next" };
211    send_frame(socket, 1, message(kind, Some(id), Some(payload)).as_bytes())
212}
213
214fn send_error(socket: &Shared, id: &str, response: &Json, legacy: bool) -> std::io::Result<()> {
215    if legacy {
216        return send_data(socket, id, &response.write(), true);
217    }
218    let errors = response
219        .get("errors")
220        .map_or_else(|| "[]".to_string(), Json::write);
221    send_frame(
222        socket,
223        1,
224        message("error", Some(id), Some(&errors)).as_bytes(),
225    )
226}
227
228fn send_frame(socket: &Shared, opcode: u8, payload: &[u8]) -> std::io::Result<()> {
229    let mut frame = vec![0x80 | opcode];
230    match payload.len() {
231        length @ 0..=125 => frame.push(length as u8),
232        length @ 126..=65535 => {
233            frame.push(126);
234            frame.extend_from_slice(&(length as u16).to_be_bytes());
235        }
236        length => {
237            frame.push(127);
238            frame.extend_from_slice(&(length as u64).to_be_bytes());
239        }
240    }
241    frame.extend_from_slice(payload);
242    let mut stream = socket
243        .lock()
244        .map_err(|_| std::io::Error::other("poisoned"))?;
245    stream.write_all(&frame)
246}
247
248/// Reads one WebSocket message, joining fragments and answering pings.
249fn read_message(reader: &mut impl Read, socket: &Shared) -> std::io::Result<Option<String>> {
250    let mut text = Vec::new();
251    loop {
252        let mut header = [0; 2];
253        reader.read_exact(&mut header)?;
254        let opcode = header[0] & 0x0f;
255        let mut length = u64::from(header[1] & 0x7f);
256        if length == 126 {
257            let mut bytes = [0; 2];
258            reader.read_exact(&mut bytes)?;
259            length = u64::from(u16::from_be_bytes(bytes));
260        } else if length == 127 {
261            let mut bytes = [0; 8];
262            reader.read_exact(&mut bytes)?;
263            length = u64::from_be_bytes(bytes);
264        }
265        if length as usize > MAX_BODY {
266            return Ok(None);
267        }
268        let mut mask = [0; 4];
269        if header[1] & 0x80 != 0 {
270            reader.read_exact(&mut mask)?;
271        }
272        let mut payload = vec![0; length as usize];
273        reader.read_exact(&mut payload)?;
274        for (at, byte) in payload.iter_mut().enumerate() {
275            *byte ^= mask[at % 4];
276        }
277        match opcode {
278            8 => {
279                let _ = send_frame(socket, 8, &payload);
280                return Ok(None);
281            }
282            9 => send_frame(socket, 10, &payload)?,
283            10 => {}
284            _ => {
285                text.extend_from_slice(&payload);
286                if header[0] & 0x80 != 0 {
287                    return Ok(Some(String::from_utf8_lossy(&text).into_owned()));
288                }
289            }
290        }
291    }
292}
293
294fn header<'h>(headers: &'h HashMap<String, String>, name: &str) -> Option<&'h str> {
295    headers.get(name).map(String::as_str)
296}
297
298const CORS: &str =
299    "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\n";
300/// Headers allowed when a preflight does not name any; Hasura echoes the ones it is asked about.
301const CORS_HEADERS: &str = "authorization, content-type, x-hasura-admin-secret, x-hasura-client, x-hasura-role, x-hasura-user-id";
302
303fn respond(stream: &mut TcpStream, status: &str, body: &str) -> std::io::Result<()> {
304    write!(
305        stream,
306        "HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\n{CORS}Access-Control-Allow-Headers: {CORS_HEADERS}\r\nContent-Length: {}\r\n\r\n{body}",
307        body.len()
308    )
309}
310
311fn handle(
312    stream: TcpStream,
313    jobs: Sender<Job>,
314    settings: &Settings,
315    connection: u64,
316) -> Result<()> {
317    let mut writer = stream.try_clone()?;
318    let mut reader = BufReader::new(stream);
319    loop {
320        let mut line = String::new();
321        if reader.read_line(&mut line)? == 0 {
322            return Ok(());
323        }
324        let mut words = line.split_whitespace();
325        let (method, path) = (
326            words.next().unwrap_or("").to_string(),
327            words.next().unwrap_or("").to_string(),
328        );
329        let path = path.split('?').next().unwrap_or("").to_string();
330        let mut headers = HashMap::new();
331        loop {
332            let mut line = String::new();
333            if reader.read_line(&mut line)? == 0 {
334                return Ok(());
335            }
336            let line = line.trim_end();
337            if line.is_empty() {
338                break;
339            }
340            if let Some((name, value)) = line.split_once(':') {
341                headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
342            }
343        }
344        let graphql = path == "/v1/graphql" || path == "/gql" || path == "/v1alpha1/graphql";
345        if header(&headers, "upgrade")
346            .is_some_and(|upgrade| upgrade.eq_ignore_ascii_case("websocket"))
347            && graphql
348        {
349            return websocket(reader, writer, &headers, jobs, settings, connection);
350        }
351        let length: usize = header(&headers, "content-length")
352            .and_then(|l| l.parse().ok())
353            .unwrap_or(0);
354        if length > MAX_BODY {
355            respond(&mut writer, "413 Payload Too Large", "{}")?;
356            return Ok(());
357        }
358        let mut body = vec![0; length];
359        reader.read_exact(&mut body)?;
360        match (method.as_str(), path.as_str()) {
361            ("OPTIONS", _) => write!(
362                writer,
363                "HTTP/1.1 204 No Content\r\n{CORS}Access-Control-Allow-Headers: {}\r\nContent-Length: 0\r\n\r\n",
364                header(&headers, "access-control-request-headers").unwrap_or(CORS_HEADERS)
365            )?,
366            ("GET", "/healthz" | "/api/healthz" | "/v1/healthz") => {
367                respond(&mut writer, "200 OK", "{\"status\":\"ok\"}")?
368            }
369            ("GET", "/v1/version" | "/v1/version/") => {
370                respond(&mut writer, "200 OK", "{\"version\":\"clink\"}")?
371            }
372            ("POST", _) if graphql => {
373                let auth = settings.authorize(
374                    header(&headers, "authorization"),
375                    header(&headers, "x-hasura-admin-secret"),
376                );
377                let response = match (auth, Json::parse(&String::from_utf8_lossy(&body))) {
378                    (Ok(auth), Ok(body)) => {
379                        let (reply, answer) = channel();
380                        jobs.send(Job::Http { body, auth, reply })?;
381                        answer.recv()?
382                    }
383                    (Err(message), _) => GqlError {
384                        message,
385                        code: "invalid-jwt",
386                        path: "$".to_string(),
387                    }
388                    .to_json(),
389                    (_, Err(error)) => GqlError::validation(error.to_string(), "$").to_json(),
390                };
391                respond(&mut writer, "200 OK", &response.write())?;
392            }
393            _ => respond(
394                &mut writer,
395                "404 Not Found",
396                "{\"error\":\"resource does not exist\"}",
397            )?,
398        }
399    }
400}
401
402fn websocket(
403    mut reader: BufReader<TcpStream>,
404    mut writer: TcpStream,
405    headers: &HashMap<String, String>,
406    jobs: Sender<Job>,
407    settings: &Settings,
408    connection: u64,
409) -> Result<()> {
410    let key = header(headers, "sec-websocket-key").unwrap_or("");
411    let offered = header(headers, "sec-websocket-protocol").unwrap_or("");
412    let modern = offered
413        .split(',')
414        .any(|name| name.trim() == "graphql-transport-ws");
415    let chosen = if modern {
416        "graphql-transport-ws"
417    } else {
418        "graphql-ws"
419    };
420    let legacy = !modern;
421    write!(
422        writer,
423        "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {}\r\nSec-WebSocket-Protocol: {chosen}\r\n\r\n",
424        websocket_accept(key)
425    )?;
426    let socket: Shared = Arc::new(Mutex::new(writer));
427    let first = (
428        header(headers, "authorization").map(str::to_string),
429        header(headers, "x-hasura-admin-secret").map(str::to_string),
430    );
431    let mut auth = settings
432        .authorize(first.0.as_deref(), first.1.as_deref())
433        .unwrap_or_default();
434    let result = (|| -> Result<()> {
435        while let Some(text) = read_message(&mut reader, &socket)? {
436            let Ok(incoming) = Json::parse(&text) else {
437                continue;
438            };
439            let id = incoming
440                .get("id")
441                .and_then(Json::as_str)
442                .map(str::to_string);
443            let payload = incoming.get("payload").cloned().unwrap_or(Json::Null);
444            match incoming.get("type").and_then(Json::as_str).unwrap_or("") {
445                "connection_init" => {
446                    let holder = payload.get("headers").unwrap_or(&payload);
447                    let found = |name: &str, lower: &str| {
448                        holder
449                            .get(name)
450                            .or_else(|| holder.get(lower))
451                            .and_then(Json::as_str)
452                            .map(str::to_string)
453                    };
454                    let authorization = found("Authorization", "authorization");
455                    let admin = found("x-hasura-admin-secret", "x-hasura-admin-secret");
456                    match settings.authorize(authorization.as_deref(), admin.as_deref()) {
457                        Ok(found) => {
458                            if authorization.is_some() || admin.is_some() {
459                                auth = found;
460                            }
461                            send_frame(
462                                &socket,
463                                1,
464                                message("connection_ack", None, None).as_bytes(),
465                            )?;
466                            if legacy {
467                                send_frame(&socket, 1, message("ka", None, None).as_bytes())?;
468                            }
469                        }
470                        Err(problem) => {
471                            let error = Json::object(vec![("message", Json::str(problem))]).write();
472                            send_frame(
473                                &socket,
474                                1,
475                                message("connection_error", None, Some(&error)).as_bytes(),
476                            )?;
477                            return Ok(());
478                        }
479                    }
480                }
481                "start" | "subscribe" => {
482                    jobs.send(Job::Subscribe {
483                        connection,
484                        id: id.unwrap_or_default(),
485                        payload,
486                        auth,
487                        legacy,
488                        socket: Arc::clone(&socket),
489                    })?;
490                }
491                "stop" | "complete" => {
492                    let done = id.clone();
493                    jobs.send(Job::Stop { connection, id })?;
494                    if legacy {
495                        send_frame(
496                            &socket,
497                            1,
498                            message("complete", done.as_deref(), None).as_bytes(),
499                        )?;
500                    }
501                }
502                "ping" => send_frame(&socket, 1, message("pong", None, None).as_bytes())?,
503                "connection_terminate" => return Ok(()),
504                _ => {}
505            }
506        }
507        Ok(())
508    })();
509    let _ = jobs.send(Job::Stop {
510        connection,
511        id: None,
512    });
513    result
514}