Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): add serve command #748

Merged
merged 4 commits into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ odict = { path = "../lib", features = [
"charabia",
"sql",
"search",
"serve",
"json",
] }
clap = { version = "4.5.4", features = ["derive", "cargo"] }
console = "0.15.8"
once_cell = "1.19.0"
indicatif = "0.17.8"
pulldown-cmark = "0.10.2"
actix-web = "4.5.1"
serde = { version = "1.0.197", features = ["derive"] }
env_logger = "0.11.3"
derive_more = "0.99.17"
5 changes: 5 additions & 0 deletions cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use clap::{command, crate_version, Parser, Subcommand};
use crate::alias::AliasCommands;
use crate::{
CompileArgs, DumpArgs, IndexArgs, LexiconArgs, LookupArgs, MergeArgs, NewArgs, SearchArgs,
ServeArgs,
};

#[derive(Debug, Parser)]
Expand Down Expand Up @@ -57,4 +58,8 @@ pub enum Commands {
/// Run a full-text query on a compiled dictionary
#[command(arg_required_else_help = true)]
Search(SearchArgs),

/// Start a local web server to serve one or several dictionaries
#[command(arg_required_else_help = true)]
Serve(ServeArgs),
}
8 changes: 6 additions & 2 deletions cli/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,14 @@ impl<'a> CLIContext<'a> {
}
}

pub fn println(&mut self, msg: String) {
pub fn println<S>(&mut self, msg: S)
where
S: AsRef<str>,
{
self.stdout
.write_all(format!("{}\n", msg).as_bytes())
.write_all(format!("{}\n", msg.as_ref()).as_bytes())
.unwrap();

self.stdout.flush().unwrap();
}
}
2 changes: 2 additions & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod merge;
mod new;
mod print;
mod search;
mod serve;
mod utils;

pub use alias::*;
Expand All @@ -25,4 +26,5 @@ pub use merge::*;
pub use new::*;
pub use print::*;
pub use search::*;
pub use serve::*;
pub use utils::*;
12 changes: 8 additions & 4 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::io::Write;

use clap::Parser;
use cli::{alias, compile, lexicon, lookup, merge, search, t, CLIContext, Commands, CLI};
use cli::{
alias, compile, dump, index, lexicon, lookup, merge, new, search, serve, t, CLIContext,
Commands, CLI,
};

fn main() {
let cli = CLI::parse();
Expand All @@ -11,13 +14,14 @@ fn main() {
|c| match cli.command {
Commands::Alias(ref args) => alias(c, args),
Commands::Compile(ref args) => compile(c, args),
Commands::Dump(ref args) => cli::dump(c, args),
Commands::Index(ref args) => cli::index(c, args),
Commands::Dump(ref args) => dump(c, args),
Commands::Index(ref args) => index(c, args),
Commands::Lexicon(ref args) => lexicon(c, args),
Commands::Lookup(ref args) => lookup(c, args),
Commands::Merge(ref args) => merge(c, args),
Commands::New(ref args) => cli::new(c, args),
Commands::New(ref args) => new(c, args),
Commands::Search(ref args) => search(c, args),
Commands::Serve(ref args) => serve(c, args),
},
&mut ctx,
);
Expand Down
101 changes: 101 additions & 0 deletions cli/src/serve/lookup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::collections::HashMap;

use actix_web::{
get,
http::{header::ContentType, StatusCode},
web::{Data, Path, Query},
HttpResponse, Responder, ResponseError,
};
use derive_more::{Display, Error};
use odict::{DictionaryFile, LookupOptions, ToJSON};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct LookupRequest {
queries: String,
follow: Option<bool>,
split: Option<usize>,
}

#[derive(Debug, Display, Error)]
enum LookupError {
#[display(fmt = "Dictionary not found: {}", name)]
DictionaryNotFound { name: String },

#[display(fmt = "Failed to read dictionary: {}", name)]
DictionaryReadError { name: String },

#[display(fmt = "Lookup error: {}", message)]
LookupError { message: String },

#[display(fmt = "Failed to serialize response")]
SerializeError,
}

impl ResponseError for LookupError {
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code())
.insert_header(ContentType::html())
.body(self.to_string())
}

fn status_code(&self) -> StatusCode {
match *self {
LookupError::DictionaryNotFound { .. } => StatusCode::NOT_FOUND,
LookupError::DictionaryReadError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
LookupError::LookupError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
LookupError::SerializeError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}

#[get("/{name}/lookup")]
async fn handle_lookup(
params: Query<LookupRequest>,
dict: Path<String>,
dictionary_map: Data<HashMap<String, DictionaryFile>>,
) -> Result<impl Responder, LookupError> {
let LookupRequest {
queries: raw_queries,
follow,
split,
} = params.0;

let queries = raw_queries
.split(',')
.map(|s| s.to_string())
.collect::<Vec<_>>();

let dictionary_name = dict.into_inner();

let file = dictionary_map
.get(&dictionary_name)
.ok_or(LookupError::DictionaryNotFound {
name: dictionary_name.to_string(),
})?;

let dictionary = file
.to_archive()
.map_err(|_e| LookupError::DictionaryReadError {
name: dictionary_name.to_string(),
})?;

let entries = dictionary
.lookup(
&queries,
LookupOptions::default()
.follow(follow.unwrap_or(false))
.split(split.unwrap_or(0)),
)
.map_err(|e| LookupError::LookupError {
message: e.to_string(),
})?;

let json = entries
.to_json(true)
.map_err(|_e| LookupError::SerializeError)?;

Ok(HttpResponse::Ok()
.content_type("application/json")
.body(json))
}
131 changes: 131 additions & 0 deletions cli/src/serve/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use std::{
collections::HashMap,
error::Error,
fmt::{self, Display, Formatter},
path::PathBuf,
};

use actix_web::{middleware::Logger, web::Data, App, HttpServer};
use clap::{command, Args, ValueEnum};
use console::style;
use env_logger::Env;
use odict::{config::AliasManager, DictionaryFile, DictionaryReader};

use crate::CLIContext;

mod lookup;
mod search;

#[derive(Debug, Clone, ValueEnum)]
enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}

impl Display for LogLevel {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
LogLevel::Trace => write!(f, "trace"),
LogLevel::Debug => write!(f, "debug"),
LogLevel::Info => write!(f, "info"),
LogLevel::Warn => write!(f, "warn"),
LogLevel::Error => write!(f, "error"),
}
}
}

#[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = true)]
#[command(flatten_help = true)]
pub struct ServeArgs {
#[arg(short, default_value_t = 5005, help = "Port to listen on")]
port: u16,

// Sets the default log level
#[arg(short, long)]
level: Option<LogLevel>,

// List of dictionary paths or aliases to serve
#[arg()]
dictionaries: Vec<String>,
}

pub(self) fn get_dictionary_map(
reader: &DictionaryReader,
alias_manager: &AliasManager,
dictionaries: &Vec<String>,
) -> Result<HashMap<String, DictionaryFile>, Box<dyn Error>> {
let mut dictionary_map = HashMap::<String, DictionaryFile>::new();

for dictionary in dictionaries {
let dict = reader.read_from_path_or_alias_with_manager(&dictionary, &alias_manager)?;

dictionary_map.insert(
PathBuf::from(dictionary)
.file_stem()
.unwrap()
.to_string_lossy()
.to_string(),
dict,
);
}

Ok(dictionary_map)
}

#[actix_web::main]
pub async fn serve(ctx: &mut CLIContext, args: &ServeArgs) -> Result<(), Box<dyn Error>> {
let ServeArgs {
port,
dictionaries,
level,
} = args;

let CLIContext {
alias_manager,
reader,
..
} = ctx;

let dictionary_map = get_dictionary_map(reader, alias_manager, &dictionaries)?;
let log_level = format!("{}", level.as_ref().unwrap_or(&LogLevel::Info));

ctx.println(format!(
"\n🟢 Serving the following dictionaries on port {} with log level \"{}\":\n",
port, log_level
));

for (name, dict) in &dictionary_map {
ctx.println(format!(
" • {} {}",
style(name).bold(),
style(format!(
"({})",
dict.path.as_ref().unwrap().to_string_lossy()
))
.dim()
));
}

ctx.println("");

env_logger::init_from_env(Env::new().default_filter_or(log_level));

let data = Data::new(dictionary_map);

HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.app_data(Data::clone(&data))
.service(lookup::handle_lookup)
.service(search::handle_search)
})
.bind(("127.0.0.1", *port))?
.run()
.await?;

Ok(())
}
Loading
Loading