Skip to main content

hyperlane_plugin_static_files/
impl.rs

1use super::*;
2
3impl Default for StaticFilesConfig {
4    /// Builds the configuration the static file plugin uses when none is
5    /// given.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - The default configuration.
10    fn default() -> Self {
11        Self {
12            root: PathBuf::from("."),
13            index: INDEX_DEFAULT.to_owned(),
14        }
15    }
16}
17
18impl StaticFilesConfig {
19    /// The rules the configuration works from.
20    ///
21    /// # Returns
22    ///
23    /// - `StaticFileResolver<'_>` - The rules of the configuration.
24    fn resolver(&self) -> StaticFileResolver<'_> {
25        StaticFileResolver {
26            root: self.get_root().as_path(),
27            index: self.get_index(),
28        }
29    }
30
31    /// The file a path names under the root, when the path is allowed.
32    ///
33    /// A path that climbs out of the root is refused, so a request cannot
34    /// reach a file the root does not hold.
35    ///
36    /// # Arguments
37    ///
38    /// - `&str` - The path of the file, relative to the root.
39    ///
40    /// # Returns
41    ///
42    /// - `Option<PathBuf>` - The file, when the path is allowed.
43    pub fn resolve(&self, path: &str) -> Option<PathBuf> {
44        self.resolver().resolve(path)
45    }
46
47    /// The content type of a file, by the extension of its name.
48    ///
49    /// A file whose extension the framework does not know is served as a
50    /// stream of bytes.
51    ///
52    /// # Arguments
53    ///
54    /// - `&Path` - The file that is served.
55    ///
56    /// # Returns
57    ///
58    /// - `String` - The content type of the file.
59    pub fn content_type(&self, file: &Path) -> String {
60        let path: String = file.to_string_lossy().to_string();
61        let extension: String = FileExtension::get_extension_name(path);
62        let content_type: &str = FileExtension::parse(extension).get_content_type();
63        if content_type.is_empty() {
64            return APPLICATION_OCTET_STREAM.to_owned();
65        }
66        content_type.to_owned()
67    }
68}
69
70impl StaticFilesPlugin {
71    /// Stores the configuration the plugin works from.
72    ///
73    /// # Arguments
74    ///
75    /// - `StaticFilesConfig` - The configuration to store.
76    ///
77    /// # Returns
78    ///
79    /// - `Result<(), String>` - Nothing, or the reason the configuration was
80    ///   refused.
81    pub fn init(config: StaticFilesConfig) -> Result<(), String> {
82        CONFIG.set(config).map_err(|_: StaticFilesConfig| {
83            "the static file configuration was already set".to_owned()
84        })
85    }
86
87    /// The configuration the plugin works from.
88    ///
89    /// # Returns
90    ///
91    /// - `Option<&'static StaticFilesConfig>` - The configuration, when it was
92    ///   set.
93    pub fn get() -> Option<&'static StaticFilesConfig> {
94        CONFIG.get()
95    }
96
97    /// The route pattern that serves the files under a prefix.
98    ///
99    /// # Arguments
100    ///
101    /// - `&str` - The path the files are served under.
102    ///
103    /// # Returns
104    ///
105    /// - `String` - The pattern of the route.
106    pub fn pattern(prefix: &str) -> String {
107        PATTERN_FORMAT.replace("{prefix}", prefix)
108    }
109}
110
111impl ServerHook for StaticFilesRoute {
112    /// Builds the route.
113    ///
114    /// # Arguments
115    ///
116    /// - `&mut Stream` - The stream the request arrived on.
117    /// - `&mut Context` - The context of the request.
118    ///
119    /// # Returns
120    ///
121    /// - `Self` - The route.
122    async fn new(_: &mut Stream, _: &mut Context) -> Self {
123        Self
124    }
125
126    /// Answers with the file the path names.
127    ///
128    /// A path that names no file is answered with the status of a missing
129    /// file.
130    ///
131    /// # Arguments
132    ///
133    /// - `Self` - The route.
134    /// - `&mut Stream` - The stream the request arrived on.
135    /// - `&mut Context` - The context of the request.
136    ///
137    /// # Returns
138    ///
139    /// - `Status` - Whether the pipeline continues.
140    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
141        let config: &'static StaticFilesConfig = match CONFIG.get() {
142            Some(config) => config,
143            None => return Status::Continue,
144        };
145        let path: String = ctx.get_route_param(PARAM_PATH);
146        let file: Option<PathBuf> = config.resolver().resolve(&path);
147        let file: PathBuf = match file {
148            Some(file) => file,
149            None => return Self::not_found(ctx),
150        };
151        let data: Vec<u8> = match fs::read(&file).await {
152            Ok(data) => data,
153            Err(_) => return Self::not_found(ctx),
154        };
155        let content_type: String = config.content_type(&file);
156        let response: &mut Response = ctx.get_mut_response();
157        response.set_status_code(HttpStatus::Ok.code());
158        response.set_header(CONTENT_TYPE, content_type);
159        response.set_body(data);
160        Status::Continue
161    }
162}
163
164impl StaticFilesRoute {
165    /// Answers with the status of a file that is not there.
166    ///
167    /// # Arguments
168    ///
169    /// - `&mut Context` - The context of the request.
170    ///
171    /// # Returns
172    ///
173    /// - `Status` - Whether the pipeline continues.
174    fn not_found(ctx: &mut Context) -> Status {
175        let response: &mut Response = ctx.get_mut_response();
176        response.set_status_code(HttpStatus::NotFound.code());
177        Status::Continue
178    }
179}