make directories configurable

This commit is contained in:
xenofem 2022-04-16 01:57:34 -04:00
parent 774f3195de
commit 4eeabbb770
3 changed files with 24 additions and 10 deletions

View file

@ -36,10 +36,20 @@
})
{ inherit pkgs; };
in rec {
packages.${name} = project.rootCrate.build;
packages.${name} = pkgs.symlinkJoin {
inherit name;
paths = [ packages."${name}-unwrapped" ];
buildInputs = [ pkgs.makeWrapper ];
postBuild = ''
wrapProgram $out/bin/${name} \
--set STATIC_DIR ${./static}
'';
};
defaultPackage = packages.${name};
packages."${name}-unwrapped" = project.rootCrate.build;
devShell = pkgs.mkShell {
nativeBuildInputs = with pkgs; [ rustc cargo cargo-audit stdenv.cc ];
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";

View file

@ -1,4 +1,4 @@
use std::time::{Duration, Instant, SystemTime};
use std::{time::{Duration, Instant, SystemTime}, path::PathBuf};
use futures::{sink::SinkExt, TryStreamExt};
use lazy_static::lazy_static;
@ -14,7 +14,6 @@ lazy_static! {
static ref MIN_CHECK_INTERVAL: Duration = Duration::from_secs(300);
}
const CACHED_PDF_PATH: &str = "data.pdf";
const LAST_MODIFIED_FORMAT: &[time::format_description::FormatItem] = time::macros::format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour repr:24]:[minute]:[second] GMT"
);
@ -39,13 +38,15 @@ pub enum Error {
pub struct PdfFetcher {
client: reqwest::Client,
cached_pdf_path: PathBuf,
last_checked: Option<Instant>,
}
impl PdfFetcher {
pub fn new() -> Result<Self, Error> {
pub fn new(cached_pdf_path: PathBuf) -> Result<Self, Error> {
Ok(Self {
client: reqwest::ClientBuilder::new().build()?,
cached_pdf_path,
last_checked: None,
})
}
@ -53,7 +54,7 @@ impl PdfFetcher {
pub async fn fetch(&mut self) -> Result<pdf::file::File<Vec<u8>>, Error> {
info!("Fetching data PDF");
let cache_modtime = match tokio::fs::File::open(CACHED_PDF_PATH).await {
let cache_modtime = match tokio::fs::File::open(&self.cached_pdf_path).await {
Ok(file) => Some(
file.metadata()
.await?
@ -125,7 +126,7 @@ impl PdfFetcher {
.bytes_stream()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e));
let cache_file = tokio::fs::File::create(CACHED_PDF_PATH).await?;
let cache_file = tokio::fs::File::create(&self.cached_pdf_path).await?;
let mut sink = codec::FramedWrite::new(cache_file, codec::BytesCodec::new());
sink.send_all(&mut pdf_stream).await?;
<dyn futures::Sink<bytes::Bytes, Error = std::io::Error> + Unpin>::close(&mut sink)
@ -138,6 +139,6 @@ impl PdfFetcher {
}
fn cached_pdf(&self) -> Result<pdf::file::File<Vec<u8>>, Error> {
Ok(pdf::file::File::open(CACHED_PDF_PATH)?)
Ok(pdf::file::File::open(&self.cached_pdf_path)?)
}
}

View file

@ -1,4 +1,4 @@
use std::{sync::Arc, time::Duration};
use std::{path::PathBuf, sync::Arc, time::Duration};
use actix_web::{
get, http::header::ContentType, middleware::Logger, web, App, HttpResponse, HttpServer,
@ -41,7 +41,8 @@ async fn try_update(state: &AppState, fetcher: &mut PdfFetcher) -> Result<(), Er
}
async fn start_updater() -> Result<web::Data<AppState>, Error> {
let mut fetcher = PdfFetcher::new()?;
let cached_pdf_path = PathBuf::from(std::env::var("CACHED_PDF_PATH").unwrap_or_else(|_| String::from("data.pdf")));
let mut fetcher = PdfFetcher::new(cached_pdf_path)?;
let state = web::Data::new(AppState {
dataset: RwLock::new(Arc::new(load_data(&mut fetcher).await?)),
});
@ -65,6 +66,8 @@ async fn start_updater() -> Result<web::Data<AppState>, Error> {
async fn main() -> std::io::Result<()> {
simple_logger::init_with_level(log::Level::Info).unwrap();
let static_dir = PathBuf::from(std::env::var("STATIC_DIR").unwrap_or_else(|_| String::from("static")));
let state = start_updater().await.expect("Failed to initialize state");
HttpServer::new(move || {
@ -73,7 +76,7 @@ async fn main() -> std::io::Result<()> {
.wrap(Logger::default())
.service(csv)
.service(json)
.service(actix_files::Files::new("/", "./static/").index_file("index.html"))
.service(actix_files::Files::new("/", static_dir.clone()).index_file("index.html"))
})
.bind("127.0.0.1:8080")?
.run()