在先前的文章中,有介绍过用 Rust 编程语言搭配 MongoDB 来保存文件的方式,那么要如何将其应用到 Rocket 框架中,使 Rocket 框架能够回应文件中心保存的数据呢?

File Center Raw Response on MongoDB for Rocket Framework

「File Center Raw Response on MongoDB for Rocket Framework」是笔者开发的套件,可以让「Mongo File Center」套件融入 Rocket 框架中,能直接从文件中心回应文件数据,并且支持 HTTP 的 ETag 机制。

Crates.io

Cargo.toml

rocket-mongo-file-center-raw-response = "*"

使用方法

先将 mongo_file_center 这个 crate 下的 FileCenter 结构实体注册至 Rocket 框架的应用程序状态中。在路由处理程序中,可以利用 State<FileCenter> 的 inner 方法取得 FileCenter 结构实体的参考。

rocket_mongo_file_center_raw_response 这个 crate 提供了 FileCenterRawResponse 结构体和 EtagIfNoneMatch 结构体(来自 rocket_etag_if_none_match 这个 crate,请参考这篇文章来了解 EtagIfNoneMatch 结构体)。

FileCenterRawResponse 结构体有三个关联函数可以用来产生 FileCenterRawResponse 结构体的实体。

首先介绍最常用的 from_id_token 函数。调用 from_id_token 函数时,要从参数传入 FileCenter 结构实体的参考、EtagIfNoneMatch 结构实体的参考、文件中心加密过的 Object ID(ID token) 和文件名称(如果不设置则使用文件中心保存的文件名称)。

以下是一个完整的例子:

#[macro_use]
extern crate rocket;

use std::error::Error;
use std::path::Path;

use rocket_mongo_file_center_raw_response::mongo_file_center::{mime, FileCenter};
use rocket_mongo_file_center_raw_response::{EtagIfNoneMatch, FileCenterRawResponse};

use rocket::http::Status;
use rocket::State;

const URL: &str = "mongodb://localhost:27017";

#[get("/<id_token>")]
async fn view(
    etag_if_none_match: &EtagIfNoneMatch<'_>,
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
    FileCenterRawResponse::from_id_token(
        file_center.inner(),
        etag_if_none_match,
        id_token,
        None::<String>,
    )
    .await
    .map_err(|_| Status::InternalServerError)
}


#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let file_center = FileCenter::new(URL).await?;

    let path = Path::new("examples").join("images").join("image(猫).jpg");

    let file_id =
        file_center.put_file_by_path(path, None::<String>, Some(mime::IMAGE_JPEG)).await?;

    let id_token = file_center.encrypt_id(file_id);

    println!("The ID token is: {}", id_token);

    println!();

    rocket::build().manage(file_center).mount("/", routes![view]).launch().await?;

    Ok(())
}

程序一开始,会将工作目录下的 examples/images/image(猫).jpg 这张 JPEG 图档保存到文件中心中,然后在屏幕上显示出这笔加密过的 Object ID(也就是「ID token」)。接着将文件中心注册给 Rocket,并启动 Rocket。在 view 这个路由处理程序中,会读取网址路径中带的 ID token。from_id_token 会根据这个 ID token 来查找文件中心里对应的文件,并回传 Result<Option<FileCenterRawResponse>, FileCenterError>,注意因为这边的 FileCenterError 并没有实作 rocket::response::Responder 特性,所以不能直接拿来回传,要像范例程序这样先用 map_err 方法转成 Status 等有实作 Responder 特性的类型。

使用 from_id_token 关联函数来创建 FileCenterRawResponse 结构实体会强制使用 ETag 机制,ETag 值即为 ID token。如果是用 from_object_id 关联函数来创建 FileCenterRawResponse 结构实体,若要使用 ETag 机制,就要自行去计算 ETag 值并透过参数传给 from_object_id 关联函数来使用。例如把以上的 view 路由处理程序用 from_object_id 关联函数改写的话就会变成以下这样:

#[get("/<id_token>")]
async fn view(
    etag_if_none_match: &EtagIfNoneMatch<'_>,
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
    let object_id =
        file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;

    let etag = FileCenterRawResponse::create_etag_by_id_token(id_token);

    FileCenterRawResponse::from_object_id(
        file_center.inner(),
        Some(etag_if_none_match),
        Some(etag),
        object_id,
        None::<String>,
    )
    .await
    .map_err(|_| Status::InternalServerError)
}

以上程序中,FileCenterRawResponse 结构体的 create_etag_by_id_token 关联函数可以拿来将 ID token 转成 rocket_etag_if_none_match::entity_tag::EntityTag 结构实体。

如果已经从文件中心拿到 FileItem 了,可以使用 FileCenterRawResponse 结构体的 from_file_item 关联函数来产生 FileCenterRawResponse 结构实体,如下:

#[get("/<id_token>")]
async fn view(
    etag_if_none_match: &EtagIfNoneMatch<'_>,
    file_center: &State<FileCenter>,
    id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
    let object_id =
        file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;

    let etag = FileCenterRawResponse::create_etag_by_id_token(id_token);

    if etag_if_none_match.weak_eq(&etag) {
        Err(Status::NotModified)
    } else {
        let file_item = file_center
            .get_file_item_by_id(object_id)
            .await
            .map_err(|_| Status::InternalServerError)?;

        match file_item {
            Some(file_item) => {
                Ok(Some(FileCenterRawResponse::from_file_item(
                    Some(etag),
                    file_item,
                    None::<String>,
                )))
            }
            None => Ok(None),
        }
    }
}

from_file_item 关联函数不能帮忙判断 HTTP 请求中的 If-None-Match 字段,因为这个动作需在调用 from_file_item 关联函数之前就完成才比较有意义(如果判断结果是 304,就不需要再浪费时间查找数据库)。因此以上程序是在路由处理程序中另外撰写代码来判断 ETag。