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