resource_proxy_pingora/metadata.rs
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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
// Copyright 2024 Wladimir Palant
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! File metadata handling
use http::{header, status::StatusCode};
use httpdate::fmt_http_date;
use mime_guess::Mime;
use pingora::http::ResponseHeader;
// use crate::session_wrapper::SessionWrapper;
use std::io::{Error, ErrorKind};
use std::path::Path;
use std::time::SystemTime;
use pingora::proxy::Session;
/// Helper wrapping file metadata information
#[derive(Debug)]
pub struct Metadata {
/// Guessed MIME types (if any) for the file
pub mime: Mime,
/// File size in bytes
pub size: u64,
/// Last modified time of the file in the format `Fri, 15 May 2015 15:34:21 GMT` if the time
/// can be retrieved
pub modified: Option<String>,
/// ETag header for the file, encoding last modified time and file size
pub etag: String,
}
impl Metadata {
/// Collects the metadata for a file. If `orig_path` is present, it will be used to determine
/// the MIME type instead of `path`.
///
/// This method will return any errors produced by [`std::fs::metadata()`]. It will also result
/// in a [`ErrorKind::InvalidInput`] error if the path given doesn’t point to a regular file.
pub fn from_path<P: AsRef<Path> + ?Sized>(
path: &P,
orig_path: Option<&P>,
) -> Result<Self, Error> {
let meta = path.as_ref().metadata()?;
if !meta.is_file() {
return Err(ErrorKind::InvalidInput.into());
}
let mime = mime_guess::from_path(orig_path.unwrap_or(path)).first_or_octet_stream();
let size = meta.len();
let modified = meta.modified().ok().map(fmt_http_date);
let etag = format!(
"\"{:x}-{:x}\"",
meta.modified()
.ok()
.and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok())
.map_or(0, |duration| duration.as_secs()),
meta.len()
);
Ok(Self {
mime,
size,
modified,
etag,
})
}
/// Checks `If-Match` and `If-Unmodified-Since` headers of the request to determine whether
/// a `412 Precondition Failed` response should be produced.
pub fn has_failed_precondition(&self, session: &Session) -> bool {
let headers = &session.req_header().headers;
if let Some(value) = headers
.get(header::IF_MATCH)
.and_then(|value| value.to_str().ok())
{
value != "*"
&& value
.split(',')
.map(str::trim)
.all(|value| value != self.etag)
} else if let Some(value) = headers
.get(header::IF_UNMODIFIED_SINCE)
.and_then(|value| value.to_str().ok())
{
self.modified
.as_ref()
.is_some_and(|modified| modified != value)
} else {
false
}
}
/// Checks `If-None-Match` and `If-Modified-Since` headers of the request to determine whether
/// a `304 Not Modified` response should be produced.
pub fn is_not_modified(&self, session: &Session) -> bool {
let headers = &session.req_header().headers;
if let Some(value) = headers
.get(header::IF_NONE_MATCH)
.and_then(|value| value.to_str().ok())
{
value == "*"
|| value
.split(',')
.map(str::trim)
.any(|value| value == self.etag)
} else if let Some(value) = headers
.get(header::IF_MODIFIED_SINCE)
.and_then(|value| value.to_str().ok())
{
self.modified
.as_ref()
.is_some_and(|modified| modified == value)
} else {
false
}
}
#[inline(always)]
fn add_content_type(
&self,
header: &mut ResponseHeader,
charset: Option<&str>,
) -> Result<(), Box<pingora::Error>> {
if let Some(charset) = charset {
header.append_header(
header::CONTENT_TYPE,
format!("{};charset={charset}", self.mime.as_ref()),
)?;
} else {
header.append_header(header::CONTENT_TYPE, self.mime.as_ref())?;
}
Ok(())
}
#[inline(always)]
fn add_etag(
&self,
header: &mut ResponseHeader,
) -> Result<(), Box<pingora::Error>> {
if let Some(modified) = &self.modified {
header.append_header(header::LAST_MODIFIED, modified)?;
}
header.append_header(header::ETAG, &self.etag)?;
Ok(())
}
/// Produces a `200 OK` response and adds headers according to file metadata.
pub(crate) fn to_response_header(
&self,
charset: Option<&str>,
) -> Result<Box<ResponseHeader>, Box<pingora::Error>> {
let mut header = ResponseHeader::build(StatusCode::OK, Some(8))?;
header.append_header(header::CONTENT_LENGTH, self.size.to_string())?;
header.append_header(header::ACCEPT_RANGES, "bytes")?;
self.add_content_type(&mut header, charset)?;
self.add_etag(&mut header)?;
Ok(Box::new(header))
}
/// Produces a `206 Partial Content` response and adds headers according to file metadata.
pub(crate) fn to_partial_content_header(
&self,
charset: Option<&str>,
start: u64,
end: u64,
) -> Result<Box<ResponseHeader>, Box<pingora::Error>> {
let mut header = ResponseHeader::build(StatusCode::PARTIAL_CONTENT, Some(8))?;
header.append_header(header::CONTENT_LENGTH, (end - start + 1).to_string())?;
header.append_header(
header::CONTENT_RANGE,
format!("bytes {start}-{end}/{}", self.size),
)?;
self.add_content_type(&mut header, charset)?;
self.add_etag(&mut header)?;
Ok(Box::new(header))
}
/// Produces a `416 Range Not Satisfiable` response and adds headers according to file
/// metadata.
pub(crate) fn to_not_satisfiable_header(
&self,
charset: Option<&str>,
) -> Result<Box<ResponseHeader>, Box<pingora::Error>> {
let mut header = ResponseHeader::build(StatusCode::RANGE_NOT_SATISFIABLE, Some(4))?;
header.append_header(header::CONTENT_RANGE, format!("bytes */{}", self.size))?;
self.add_content_type(&mut header, charset)?;
self.add_etag(&mut header)?;
Ok(Box::new(header))
}
/// Produces a response with specified status code and no response body (all headers added
/// except `Content-Length``).
pub(crate) fn to_custom_header(
&self,
status: StatusCode,
) -> Result<Box<ResponseHeader>, Box<pingora::Error>> {
let mut header = ResponseHeader::build(status, Some(4))?;
self.add_etag(&mut header)?;
Ok(Box::new(header))
}
}