Skip to content

Commit

Permalink
Stream response instead of load into Body
Browse files Browse the repository at this point in the history
  • Loading branch information
evanjt committed Nov 5, 2024
1 parent 6cd26ca commit 3dcc4a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
8 changes: 4 additions & 4 deletions src/external/k8s/services.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::models::PodName;
use crate::config::Config;
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Error, Result};
use chrono::{DateTime, Utc};
use k8s_openapi::api::core::v1::Pod;
use kube::{
Expand Down Expand Up @@ -59,18 +59,18 @@ fn extract_refresh_token(kubeconfig: &Kubeconfig) -> Option<String> {
None
}

pub async fn get_pods() -> Result<Vec<crate::external::k8s::models::PodName>, kube::Error> {
pub async fn get_pods() -> Result<Vec<crate::external::k8s::models::PodName>, Error> {
// Get app config and kube client
let app_config = Config::from_env();
let client = refresh_token_and_get_client().await.unwrap();
let client = refresh_token_and_get_client().await?;

// Get pods from Kubernetes API
let pods: Api<Pod> = Api::namespaced(client, &app_config.kube_namespace);
let lp = ListParams::default();

let pod_list = match pods.list(&lp).await {
Ok(pod_list) => pod_list,
Err(e) => return Err(e),
Err(e) => return Err(e.into()),
};
let pod_infos: Vec<crate::external::k8s::models::PodName> = pod_list
.clone()
Expand Down
26 changes: 14 additions & 12 deletions src/submissions/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use crate::external::k8s::crd::{
};
use anyhow::Result;
use aws_sdk_s3::Client as S3Client;
use axum::body::Body;
use axum::{
body::Bytes,
debug_handler,
extract::{Path, Query, State},
http::{header, StatusCode},
Expand All @@ -28,6 +28,7 @@ use sea_orm::{
ModelTrait, SqlErr,
};
use std::sync::Arc;
use tokio_util::io::ReaderStream;
use uuid::Uuid;

pub fn router(
Expand Down Expand Up @@ -422,19 +423,20 @@ pub async fn download_file(
.await
.map_err(|_| (StatusCode::NOT_FOUND, "File not found".to_string()))?;

let body = object.body.collect().await.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to read file".to_string(),
)
})?;
// Stream the S3 object body directly using `Body::from_stream`
let stream = ReaderStream::new(object.body.into_async_read());
let body = Body::from_stream(stream);

// Return response with streaming body
Ok((
StatusCode::OK,
[(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{}\"", claims.filename),
)],
Bytes::from(body.into_bytes()), // Ensures compatibility with `IntoResponse`
[
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{}\"", claims.filename),
),
(header::CONTENT_TYPE, "application/octet-stream".to_string()),
],
body,
))
}

0 comments on commit 3dcc4a8

Please sign in to comment.