Skip to main content

gql/
upload.rs

1//! File uploads carried through the GraphQL value model.
2//!
3//! The GraphQL multipart request specification replaces each file in the operation's variables
4//! with `null` and sends the bytes in a separate part. A transport parses those parts and inserts
5//! an [`Upload`] into the already-converted variable value:
6//!
7//! ```no_run
8//! use gql::{Value, Upload};
9//!
10//! # fn attach(variables: &mut gql::Object, bytes: Vec<u8>) {
11//! let upload = Upload::new("avatar.png", "image/png", bytes);
12//! variables.insert("file", Value::from(upload));
13//! # }
14//! ```
15//!
16//! Execution never understands the bytes. A custom scalar owns them: its `parse_value` function
17//! receives the [`Value::External`] and downcasts it with
18//! [`Value::as_external::<Upload>`](Value::as_external), after which a resolver can read
19//! [`Upload::bytes`], [`Upload::filename`] and [`Upload::content_type`].
20//!
21//! Keeping the type in `gql` lets a transport crate depend on `gql` without making the execution
22//! engine depend on that transport, or on a high-level schema builder.
23
24use std::{fmt, sync::Arc};
25
26use crate::Value;
27
28/// A file supplied by a multipart request.
29///
30/// The bytes are immutable and shared through an [`Arc`], so cloning an upload into several
31/// variable paths (the specification allows one file to be mapped to multiple places) does not
32/// copy the contents.
33///
34/// `Debug` deliberately prints the name, content type and length but never the bytes; uploads are
35/// commonly logged alongside request metadata.
36#[derive(Clone, PartialEq, Eq)]
37pub struct Upload {
38    filename: Option<Arc<str>>,
39    content_type: Option<Arc<str>>,
40    bytes: Arc<[u8]>,
41}
42
43impl Upload {
44    /// Create an upload with a filename and content type.
45    #[must_use]
46    pub fn new(
47        filename: impl Into<Arc<str>>,
48        content_type: impl Into<Arc<str>>,
49        bytes: impl Into<Arc<[u8]>>,
50    ) -> Self {
51        Self {
52            filename: Some(filename.into()),
53            content_type: Some(content_type.into()),
54            bytes: bytes.into(),
55        }
56    }
57
58    /// Create an upload from optional metadata.
59    ///
60    /// A multipart part is not required to carry a `filename` or `Content-Type`; transports use
61    /// this constructor so the missing values stay missing rather than becoming empty strings.
62    #[must_use]
63    pub fn from_parts(
64        filename: Option<Arc<str>>,
65        content_type: Option<Arc<str>>,
66        bytes: Arc<[u8]>,
67    ) -> Self {
68        Self {
69            filename,
70            content_type,
71            bytes,
72        }
73    }
74
75    /// The multipart part's filename, if it declared one.
76    #[must_use]
77    pub fn filename(&self) -> Option<&str> {
78        self.filename.as_deref()
79    }
80
81    /// The multipart part's content type, if it declared one.
82    ///
83    /// This value is supplied by the client and is not verified against the bytes.
84    #[must_use]
85    pub fn content_type(&self) -> Option<&str> {
86        self.content_type.as_deref()
87    }
88
89    /// The file contents.
90    #[must_use]
91    pub fn bytes(&self) -> &[u8] {
92        &self.bytes
93    }
94
95    /// Consume the upload, returning its shared contents.
96    #[must_use]
97    pub fn into_bytes(self) -> Arc<[u8]> {
98        self.bytes
99    }
100
101    /// The number of bytes.
102    #[must_use]
103    pub fn len(&self) -> usize {
104        self.bytes.len()
105    }
106
107    /// Whether the file is empty.
108    #[must_use]
109    pub fn is_empty(&self) -> bool {
110        self.bytes.is_empty()
111    }
112}
113
114impl fmt::Debug for Upload {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("Upload")
117            .field("filename", &self.filename)
118            .field("content_type", &self.content_type)
119            .field("len", &self.bytes.len())
120            .finish()
121    }
122}
123
124impl From<Upload> for Value {
125    fn from(value: Upload) -> Self {
126        Self::external(value)
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn debug_does_not_print_contents() {
136        let upload = Upload::new("a.txt", "text/plain", b"top secret".to_vec());
137        let debug = format!("{upload:?}");
138        assert!(debug.contains("a.txt"));
139        assert!(debug.contains("text/plain"));
140        assert!(!debug.contains("top secret"));
141    }
142
143    #[test]
144    fn value_round_trips_through_external() {
145        let upload = Upload::new("a.txt", "text/plain", b"hello".to_vec());
146        let value = Value::from(upload);
147        let borrowed = value.as_external::<Upload>().expect("upload");
148        assert_eq!(borrowed.filename(), Some("a.txt"));
149        assert_eq!(borrowed.bytes(), b"hello");
150    }
151}