Fix errors

This commit is contained in:
fluo10 2025-05-15 07:28:06 +09:00
parent 40450c72fe
commit a0356c5ed0
16 changed files with 52 additions and 223 deletions

View file

@ -6,7 +6,7 @@ edition = "2024"
[features]
default = ["desktop"]
desktop = ["dep:clap", "progress-pile-core/desktop", "dep:progress-pile-migration", "dep:sea-orm", "tokio/io-util", "tokio/fs"]
web = []
web = ["uuid/js"]
[dependencies]
chrono.workspace = true
@ -22,5 +22,5 @@ tokio.workspace = true
toml.workspace = true
uuid.workspace = true
[dev-dependencies]
[target.'cfg(not(target_family="wasm"))'.dev-dependencies]
tempfile.workspace = true

View file

@ -2,7 +2,6 @@ mod remote;
use std::{fmt::{Display, Formatter}, path::{Path, PathBuf}, str::FromStr};
pub use progress_pile_core::config::*;
pub use remote::*;
use crate::error::Error;

View file

@ -6,13 +6,9 @@ license.workspace = true
repository.workspace = true
[features]
default = ["desktop", "server"]
cli = ["dep:clap"]
desktop = ["cli", "sqlite", "fs"]
fs = []
sqlite = ["dep:sea-orm"]
postgres = ["sea-orm/sqlx-postgres"]
server = ["cli", "sqlite", "postgres", "fs"]
default = ["desktop"]
desktop = ["dep:clap", "dep:sea-orm"]
wasm = []
[dependencies]
async-graphql.workspace = true

View file

@ -1,8 +0,0 @@
#[cfg(any(feature="sqlite", feature="postgres"))]
mod database;
#[cfg(any(feature="sqlite", feature="postgres"))]
pub use database::{
DatabaseConfig,
PartialDatabaseConfig,
};

View file

@ -20,7 +20,7 @@ pub enum Error {
InitializingOnceCell(String),
#[error("Once cell is already Initialized: {0}")]
AlreadyInitializedOnceCell(String),
#[cfg(any(feature="postgres", feature="sqlite"))]
#[cfg(feature="desktop")]
#[error("DB Error: {0}")]
Db(#[from]sea_orm::DbErr),
}

View file

@ -1,7 +1,5 @@
use chrono_tz::Tz;
#[cfg(feature="sea-orm")]
use crate::config::DatabaseConfig;
use crate::error::Error;
pub trait GlobalConfig<T> {
@ -9,7 +7,5 @@ pub trait GlobalConfig<T> {
fn get_or_try_init_config(&self) -> Result<T, Error>;
fn get_or_try_init_config_from_file(&self) -> Result<T, Error>;
fn get_or_try_init_config_from_str(&self) -> Result<T, Error>;
#[cfg(feature="sea-orm")]
fn get_database_config(&self) -> Option<DatabaseConfig>;
fn get_time_zone(&self) -> Option<Tz>;
}

View file

@ -1,14 +1,9 @@
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use crate::error::Error;
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
pub trait GlobalDatabase {
fn get_database(&self) -> Option<&DatabaseConnection>;
async fn get_or_try_init_database(&self) -> Result<&DatabaseConnection, Error>;
async fn get_or_try_init_database_with_connect_options<T>(&self, options: T) -> Result<&DatabaseConnection, Error> where
T: Into<ConnectOptions>;
}
#[cfg(test)]
mod tests {
use super::*;
async fn get_or_try_init_database_with_connect_options<T>(&self, options: T) -> Result<&DatabaseConnection, Error> where
T: Into<ConnectOptions>;
}

View file

@ -1,9 +1,8 @@
mod config;
#[cfg(any(feature="sqlite", feature="postgres"))]
#[cfg(feature="desktop")]
mod database;
pub use config::GlobalConfig;
#[cfg(any(feature="sqlite", feature="postgres"))]
#[cfg(feature="desktop")]
pub use database::GlobalDatabase;

View file

@ -1,4 +1,3 @@
pub mod config;
pub mod csv;
pub mod entity;
pub mod error;

View file

@ -1,29 +0,0 @@
use crate::config::PartialServerConfig;
use clap::Parser;
use progress_pile_core::config::{
PartialDatabaseConfig,
PartialGlobalConfig,
};
use std::{
net::IpAddr,
path::PathBuf,
};
use crate::config::ServerConfig;
#[derive(Clone, Debug, Parser)]
#[command(version, about, long_about = None)]
pub struct Args {
#[command(flatten)]
pub server: PartialServerConfig,
#[command(flatten)]
pub global: PartialGlobalConfig,
#[command(flatten)]
pub database: PartialDatabaseConfig,
#[arg(short, long)]
pub config_file: Option<PathBuf>,
}

View file

@ -0,0 +1,17 @@
use crate::config::PartialServerConfig;
use clap::Parser;
use std::{
net::IpAddr,
path::PathBuf,
};
use crate::config::ServerConfig;
#[derive(Clone, Debug, Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
#[arg(short, long)]
pub config_file: Option<PathBuf>,
}

View file

@ -1,147 +0,0 @@
use crate::error::Error;
use progress_pile_core::config::{
DatabaseConfig, GlobalConfig, PartialDatabaseConfig
};
use serde::Deserialize;
use std::{
default::Default,
str::FromStr,
net::IpAddr,
};
use tokio::sync::OnceCell;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Config {
global: GlobalConfig,
database: DatabaseConfig,
server: ServerConfig,
}
impl TryFrom<PartialConfig> for Config {
type Error = Error;
fn try_from(p: PartialConfig) -> Result<Config, Self::Error> {
Ok(Config {
global: p.global.ok_or(Error::MissingConfig("global".to_string()))?,
database: p.database.ok_or(Error::MissingConfig("global".to_string()))?,
server: p.server.ok_or(Error::MissingConfig("global".to_string()))?,
})
}
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct PartialConfig {
global: Option<GlobalConfig>,
database: Option<DatabaseConfig>,
server: Option<ServerConfig>,
}
pub static SERVER_CONFIG: OnceServerConfig = OnceServerConfig::const_new();
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct ServerConfig {
pub listen_ips: Vec<IpAddr>,
pub port: u16,
}
impl ServerConfig {
}
impl TryFrom<PartialServerConfig> for ServerConfig {
type Error = Error;
fn try_from(p: PartialServerConfig) -> Result<ServerConfig, Error>{
Ok(ServerConfig{
listen_ips: p.listen_ips.ok_or(Error::MissingConfig("listen_ips".to_string()))?,
port: p.port.ok_or(Error::MissingConfig("port".to_string()))?,
})
}
}
pub struct OnceServerConfig {
inner: OnceCell<ServerConfig>,
}
impl OnceServerConfig {
const fn const_new() -> Self {
Self {
inner: OnceCell::const_new(),
}
}
pub fn get(&self) -> Option<&ServerConfig> {
self.inner.get()
}
pub async fn get_or_init<F, T>(&self, f: F) -> &ServerConfig where
F: FnOnce() -> T,
T: Future<Output = ServerConfig>
{
self.inner.get_or_init(f).await
}
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[derive(clap::Args)]
pub struct PartialServerConfig {
#[arg(short, long,)]
pub listen_ips: Option<Vec<IpAddr>>,
#[arg(short, long,)]
pub port: Option<u16>,
}
impl PartialServerConfig {
pub fn try_from_toml(s: &str) -> Result<Self, Error> {
Ok(toml::from_str(s)?)
}
}
impl Default for PartialServerConfig {
fn default() -> Self {
PartialServerConfig {
listen_ips: Some(vec!["127.0.0.1".parse().unwrap(), "::1".parse().unwrap()]),
port: Some(3000),
}
}
}
impl FromStr for PartialServerConfig {
type Err = Error;
/// #Examples
/// ```
/// use dpts_config::{
/// PartialServerConfig,
/// PartialDatabaseConfig,
/// };
/// use std::{
/// default::Default,
/// net::IpAddr
/// };
/// let config_from_str: PartialServerConfig = r#"
/// listen_ips = ["0.0.0.0"]
/// port = 8000
/// time_zone = "Asia/Tokyo"
///
/// [database]
/// url = "sqlite::memory:"
/// sqlx_logging = true
/// "#.parse().unwrap();
///
/// let config: PartialServerConfig = PartialServerConfig{
/// listen_ips : Some(vec!["0.0.0.0".parse().unwrap()]),
/// port: Some(8000),
/// time_zone: Some(chrono_tz::Asia::Tokyo),
/// database: Some(PartialDatabaseConfig {
/// url: Some("sqlite::memory:".to_string()),
/// sqlx_logging: Some(true),
/// ..Default::default()
/// }),
/// };
///
/// assert_eq!(config_from_str, config);
/// ```
///
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(toml::from_str(s)?)
}
}

View file

@ -1,6 +1,5 @@
use std::time::Duration;
#[cfg(feature="cli")]
use clap::Args;
use sea_orm::ConnectOptions;
use serde::Deserialize;
@ -63,23 +62,26 @@ impl TryFrom<PartialDatabaseConfig> for DatabaseConfig{
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(feature="cli", derive(Args))]
#[derive(Args)]
pub struct PartialDatabaseConfig {
#[arg(long)]
pub url: Option<String>,
#[arg(long)]
pub max_connections: Option<u32>,
#[arg(long)]
pub min_connections: Option<u32>,
#[cfg_attr(feature="cli", arg(value_parser = parse_duration ))]
#[arg(long, value_parser = parse_duration )]
pub connect_timeout: Option<Duration>,
#[cfg_attr(feature="cli", arg(value_parser = parse_duration ))]
#[arg(long, value_parser = parse_duration )]
pub acquire_timeout: Option<Duration>,
#[cfg_attr(feature="cli", arg(value_parser = parse_duration ))]
#[arg(long, value_parser = parse_duration )]
pub idle_timeout: Option<Duration>,
#[cfg_attr(feature="cli", arg(value_parser = parse_duration ))]
#[arg(long, value_parser = parse_duration )]
pub max_lifetime: Option<Duration>,
#[arg(long)]
pub sqlx_logging: Option<bool>
}
#[cfg(feature="cli")]
fn parse_duration(arg: &str) -> Result<std::time::Duration, Error> {
let seconds = arg.parse()?;
Ok(std::time::Duration::from_secs(seconds))

View file

@ -0,0 +1,10 @@
mod database;
pub use database::{
DatabaseConfig,
PartialDatabaseConfig
};
pub struct ServerConfig {}
pub struct PartialServerConfig {}

View file

@ -1,12 +1,12 @@
mod args;
mod auth;
mod config;
pub mod cli;
pub mod auth;
pub mod config;
pub mod entity;
pub mod global;
pub mod graphql;
pub use progress_pile_core::error;
pub use args::Args;
pub use cli::Cli;
use async_graphql::{EmptySubscription, Schema};
use async_graphql_axum::{
GraphQL,

View file

@ -1,7 +1,7 @@
use async_graphql::{http::{playground_source, GraphQLPlaygroundConfig}, *};
use async_graphql_axum::GraphQL;
use progress_pile_server::{build_app, Args};
use progress_pile_server::{build_app, cli::Cli};
use axum::{response::{Html, IntoResponse}, routing::get, Router};
use clap::Parser;