Use cargo workspaces

This commit is contained in:
2022-03-10 22:45:02 +01:00
parent b2bc58f2f6
commit 5958a3ed29
30 changed files with 936 additions and 368 deletions

3
.gitignore vendored
View File

@@ -1,2 +1,3 @@
/target /target
config/local.* api/config/local.*
web/dist

View File

@@ -1,9 +1,23 @@
repos: repos:
- repo: https://github.com/doublify/pre-commit-rust - repo: local
rev: v1.0
hooks: hooks:
- id: fmt - id: format
- id: cargo-check name: format
args: ['--tests'] language: system
- id: clippy pass_filenames: false
args: ['--tests', '--', '-D', 'warnings'] entry: cargo make format-flow
- id: format-toml
name: format-toml
language: system
pass_filenames: false
entry: cargo make format-toml-flow
- id: check
name: check
language: system
pass_filenames: false
entry: cargo make check-tests
- id: clippy
name: clippy
language: system
pass_filenames: false
entry: cargo make clippy-flow

701
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +1,18 @@
[package] [package]
name = "contextswitch-api" name = "contextswitch"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
authors = ["David Rousselie <david@rousselie.name>"] authors = ["David Rousselie <david@rousselie.name>"]
[workspace]
members = ["api", "web"]
[lib] [lib]
path = "src/lib.rs" path = "src/lib.rs"
[[bin]]
path = "src/main.rs"
name = "contextswitch-api"
[dependencies] [dependencies]
contextswitch-types = { git = "https://github.com/dax/contextswitch-types.git" } serde = { version = "1.0", features = ["derive"] }
actix-web = "=4.0.0-beta.19"
actix-http = "=3.0.0-beta.18"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1.0.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
uuid = { version = "0.8.0", features = ["serde"] } uuid = { version = "0.8.0", features = ["serde"] }
chrono = { version = "0.4.0", features = ["serde"] } chrono = { version = "0.4.0", features = ["serde"] }
mktemp = "0.4.0" http = "0.2.0"
configparser = "3.0.0"
listenfd = "0.3.0"
tracing = { version = "0.1.0", features = ["log"] }
tracing-subscriber = { version = "0.3.0", features = ["std", "env-filter", "fmt", "json"] }
tracing-log = "0.1.0"
tracing-actix-web = "=0.5.0-beta.9"
regex = "1.5.0"
lazy_static = "1.4.0"
tracing-bunyan-formatter = "0.3.0"
thiserror = "1.0"
anyhow = "1.0"
http = "0.2.0"
config = "0.12.0"
[dev-dependencies]
proptest = "1.0.0"
reqwest = { version = "0.11.0", features = ["json"] }
rstest = "0.12.0"

60
Makefile.toml Normal file
View File

@@ -0,0 +1,60 @@
[env]
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
CARGO_MAKE_COVERAGE_PROVIDER = "tarpaulin"
CARGO_MAKE_CLIPPY_ARGS = "--tests -- -D warnings"
[tasks.default]
clear = true
alias = "run"
[tasks.test]
install_crate = "cargo-nextest"
args = [
"nextest",
"run",
"@@remove-empty(CARGO_MAKE_CARGO_VERBOSE_FLAGS)",
"@@split(CARGO_MAKE_CARGO_BUILD_TEST_FLAGS, )",
]
[tasks.audit]
condition = {}
workspace = false
[tasks.run-api]
install_crate = "bunyan"
env = { "CONFIG_PATH" = "api/config", "TASKRC" = "$PWD/api/taskrc" }
command = "bash"
args = ["-c", "cargo run -p contextswitch-api | bunyan"]
workspace = false
watch = { watch = ["./api/"], no_git_ignore = true }
[tasks.run-web]
install_crate = "trunk"
command = "bash"
args = ["-c", "cd web; trunk serve"]
workspace = false
[tasks.run]
run_task = { name = ["run-api", "run-web"], parallel = true, fork = true }
workspace = false
[tasks.watch-api]
watch = { watch = ["./api/"], no_git_ignore = true }
command = "bash"
args = ["-c", "cd api; cargo make watch-flow"]
workspace = false
[tasks.watch-web]
watch = { watch = ["./web/"], no_git_ignore = true }
command = "bash"
args = ["-c", "cd web; cargo make watch-flow"]
workspace = false
[tasks.watch-root]
watch = { watch = ["./src/"], no_git_ignore = true }
run_task = "dev-test-flow"
workspace = false
[tasks.watch]
run_task = { name = ["watch-api", "watch-web", "watch-root"], parallel = true, fork = true }
workspace = false

45
api/Cargo.toml Normal file
View File

@@ -0,0 +1,45 @@
[package]
name = "contextswitch-api"
version = "0.1.0"
edition = "2021"
authors = ["David Rousselie <david@rousselie.name>"]
[lib]
path = "src/lib.rs"
[[bin]]
path = "src/main.rs"
name = "contextswitch-api"
[dependencies]
contextswitch = { path = ".." }
actix-web = "4.0.0"
actix-http = "3.0.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1.0.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "0.8.0", features = ["serde"] }
chrono = { version = "0.4.0", features = ["serde"] }
mktemp = "0.4.0"
configparser = "3.0.0"
tracing = { version = "0.1.0", features = ["log"] }
tracing-subscriber = { version = "0.3.0", features = [
"std",
"env-filter",
"fmt",
"json",
] }
tracing-log = "0.1.0"
tracing-actix-web = "0.5.0"
regex = "1.5.0"
lazy_static = "1.4.0"
tracing-bunyan-formatter = "0.3.0"
thiserror = "1.0"
anyhow = "1.0"
http = "0.2.0"
config = "0.12.0"
[dev-dependencies]
proptest = "1.0.0"
reqwest = { version = "0.11.0", features = ["json"] }
rstest = "0.12.0"

1
api/Makefile.toml Normal file
View File

@@ -0,0 +1 @@
extend = "../Makefile.toml"

View File

@@ -4,4 +4,4 @@ port = 8000
log_directive = "info" log_directive = "info"
[taskwarrior] [taskwarrior]
data_location = "/tmp" data_location = "/tmp"

2
api/config/dev.toml Normal file
View File

@@ -0,0 +1,2 @@
[application]
log_directive = "debug"

2
api/config/test.toml Normal file
View File

@@ -0,0 +1,2 @@
[application]
log_directive = "debug"

View File

@@ -25,10 +25,11 @@ impl Settings {
let config_file_required = file.is_some(); let config_file_required = file.is_some();
let config_file = let config_file =
file.unwrap_or_else(|| env::var("CONFIG").unwrap_or_else(|_| "dev".into())); file.unwrap_or_else(|| env::var("CONFIG").unwrap_or_else(|_| "dev".into()));
let config_path = env::var("CONFIG_PATH").unwrap_or_else(|_| "config".into());
let config = Config::builder() let config = Config::builder()
.add_source(File::with_name("config/default")) .add_source(File::with_name(&format!("{}/default", config_path)))
.add_source(File::with_name("config/local").required(false)) .add_source(File::with_name(&format!("{}/local", config_path)).required(false))
.add_source(File::with_name(&config_file).required(config_file_required)) .add_source(File::with_name(&config_file).required(config_file_required))
.add_source(Environment::with_prefix("cs")) .add_source(Environment::with_prefix("cs"))
.build()?; .build()?;

View File

@@ -1,5 +1,5 @@
use crate::contextswitch::taskwarrior; use crate::contextswitch::taskwarrior;
use contextswitch_types::Task; use contextswitch::Task;
use serde_json; use serde_json;
fn error_chain_fmt( fn error_chain_fmt(

View File

@@ -2,7 +2,7 @@ use crate::configuration::TaskwarriorSettings;
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use configparser::ini::Ini; use configparser::ini::Ini;
use contextswitch_types::{ContextswitchData, Task, TaskId}; use contextswitch::{ContextswitchData, Task, TaskId};
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json; use serde_json;
@@ -168,35 +168,35 @@ impl From<TaskId> for TaskwarriorTaskId {
pub struct TaskwarriorTask { pub struct TaskwarriorTask {
pub uuid: TaskwarriorTaskId, pub uuid: TaskwarriorTaskId,
pub id: TaskwarriorTaskLocalId, pub id: TaskwarriorTaskLocalId,
#[serde(with = "contextswitch_types::tw_date_format")] #[serde(with = "contextswitch::tw_date_format")]
pub entry: DateTime<Utc>, pub entry: DateTime<Utc>,
#[serde(with = "contextswitch_types::tw_date_format")] #[serde(with = "contextswitch::tw_date_format")]
pub modified: DateTime<Utc>, pub modified: DateTime<Utc>,
pub status: contextswitch_types::Status, pub status: contextswitch::Status,
pub description: String, pub description: String,
pub urgency: f64, pub urgency: f64,
#[serde( #[serde(
default, default,
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
with = "contextswitch_types::opt_tw_date_format" with = "contextswitch::opt_tw_date_format"
)] )]
pub due: Option<DateTime<Utc>>, pub due: Option<DateTime<Utc>>,
#[serde( #[serde(
default, default,
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
with = "contextswitch_types::opt_tw_date_format" with = "contextswitch::opt_tw_date_format"
)] )]
pub start: Option<DateTime<Utc>>, pub start: Option<DateTime<Utc>>,
#[serde( #[serde(
default, default,
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
with = "contextswitch_types::opt_tw_date_format" with = "contextswitch::opt_tw_date_format"
)] )]
pub end: Option<DateTime<Utc>>, pub end: Option<DateTime<Utc>>,
#[serde( #[serde(
default, default,
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
with = "contextswitch_types::opt_tw_date_format" with = "contextswitch::opt_tw_date_format"
)] )]
pub wait: Option<DateTime<Utc>>, pub wait: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -204,9 +204,9 @@ pub struct TaskwarriorTask {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<String>, pub project: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<contextswitch_types::Priority>, pub priority: Option<contextswitch::Priority>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub recur: Option<contextswitch_types::Recurrence>, pub recur: Option<contextswitch::Recurrence>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>, pub tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -432,7 +432,7 @@ mod tests {
mod from_taskwarrior_task_to_contextswitch_task { mod from_taskwarrior_task_to_contextswitch_task {
use super::super::*; use super::super::*;
use chrono::TimeZone; use chrono::TimeZone;
use contextswitch_types::Bookmark; use contextswitch::Bookmark;
use http::uri::Uri; use http::uri::Uri;
use proptest::prelude::*; use proptest::prelude::*;
@@ -443,7 +443,7 @@ mod tests {
id: TaskwarriorTaskLocalId(42), id: TaskwarriorTaskLocalId(42),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0), entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1), modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch_types::Status::Pending, status: contextswitch::Status::Pending,
description: "simple task".to_string(), description: "simple task".to_string(),
urgency: 0.5, urgency: 0.5,
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)), due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),
@@ -452,8 +452,8 @@ mod tests {
wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)), wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)),
parent: Some(TaskwarriorTaskId(Uuid::new_v4())), parent: Some(TaskwarriorTaskId(Uuid::new_v4())),
project: Some("simple project".to_string()), project: Some("simple project".to_string()),
priority: Some(contextswitch_types::Priority::H), priority: Some(contextswitch::Priority::H),
recur: Some(contextswitch_types::Recurrence::Daily), recur: Some(contextswitch::Recurrence::Daily),
tags: Some(vec!["tag1".to_string(), "tag2".to_string()]), tags: Some(vec!["tag1".to_string(), "tag2".to_string()]),
contextswitch: Some(String::from( contextswitch: Some(String::from(
r#"{"bookmarks": [{"uri": "https://www.example.com/path"}]}"#, r#"{"bookmarks": [{"uri": "https://www.example.com/path"}]}"#,
@@ -498,7 +498,7 @@ mod tests {
id: TaskwarriorTaskLocalId(42), id: TaskwarriorTaskLocalId(42),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0), entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1), modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch_types::Status::Pending, status: contextswitch::Status::Pending,
description: "simple task".to_string(), description: "simple task".to_string(),
urgency: 0.5, urgency: 0.5,
due: None, due: None,
@@ -528,7 +528,7 @@ mod tests {
mod from_contextswitch_task_to_taskwarrior_action { mod from_contextswitch_task_to_taskwarrior_action {
use super::super::*; use super::super::*;
use chrono::TimeZone; use chrono::TimeZone;
use contextswitch_types::{Bookmark, Priority, Recurrence}; use contextswitch::{Bookmark, Priority, Recurrence};
use http::Uri; use http::Uri;
#[test] #[test]
@@ -537,7 +537,7 @@ mod tests {
id: TaskId(Uuid::new_v4()), id: TaskId(Uuid::new_v4()),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0), entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1), modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch_types::Status::Pending, status: contextswitch::Status::Pending,
description: "simple task".to_string(), description: "simple task".to_string(),
urgency: 0.5, urgency: 0.5,
due: None, due: None,
@@ -579,7 +579,7 @@ mod tests {
id: TaskId(Uuid::new_v4()), id: TaskId(Uuid::new_v4()),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0), entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1), modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch_types::Status::Pending, status: contextswitch::Status::Pending,
description: "simple task".to_string(), description: "simple task".to_string(),
urgency: 0.5, urgency: 0.5,
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)), due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),

45
api/src/lib.rs Normal file
View File

@@ -0,0 +1,45 @@
use actix_web::{dev::Server, http, middleware, web, App, HttpServer};
use core::time::Duration;
use std::env;
use std::net::TcpListener;
use tracing_actix_web::TracingLogger;
#[macro_use]
extern crate lazy_static;
pub mod configuration;
pub mod contextswitch;
pub mod observability;
pub mod routes;
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let cs_front_base_url =
env::var("CS_FRONT_BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string());
let server = HttpServer::new(move || {
App::new()
.wrap(TracingLogger::default())
.wrap(middleware::Compress::default())
.wrap(
middleware::DefaultHeaders::new()
.add(("Access-Control-Allow-Origin", cs_front_base_url.as_bytes()))
.add((
"Access-Control-Allow-Methods",
"POST, GET, OPTIONS".as_bytes(),
))
.add(("Access-Control-Allow-Headers", "content-type".as_bytes())),
)
.route("/ping", web::get().to(routes::ping))
.route("/tasks", web::get().to(routes::list_tasks))
.route("/tasks", web::post().to(routes::add_task))
.route("/tasks/{task_id}", web::put().to(routes::update_task))
.route(
"/tasks",
web::method(http::Method::OPTIONS).to(routes::option_task),
)
})
.keep_alive(http::KeepAlive::Timeout(Duration::from_secs(60)))
.shutdown_timeout(60)
.listen(listener)?;
Ok(server.run())
}

View File

@@ -1,5 +1,3 @@
extern crate listenfd;
use contextswitch_api::configuration::Settings; use contextswitch_api::configuration::Settings;
use contextswitch_api::observability::{get_subscriber, init_subscriber}; use contextswitch_api::observability::{get_subscriber, init_subscriber};
use contextswitch_api::{contextswitch::taskwarrior, run}; use contextswitch_api::{contextswitch::taskwarrior, run};

View File

@@ -1,7 +1,7 @@
use crate::contextswitch; use crate::contextswitch as cs;
use actix_web::{http::StatusCode, web, HttpResponse, ResponseError}; use actix_web::{http::StatusCode, web, HttpResponse, ResponseError};
use anyhow::Context; use anyhow::Context;
use contextswitch_types::{NewTask, Task, TaskId}; use contextswitch::{NewTask, Task, TaskId};
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -9,15 +9,11 @@ pub struct TaskQuery {
filter: Option<String>, filter: Option<String>,
} }
impl ResponseError for contextswitch::ContextswitchError { impl ResponseError for cs::ContextswitchError {
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
match self { match self {
contextswitch::ContextswitchError::InvalidDataError { .. } => { cs::ContextswitchError::InvalidDataError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
StatusCode::INTERNAL_SERVER_ERROR cs::ContextswitchError::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
contextswitch::ContextswitchError::UnexpectedError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
} }
} }
} }
@@ -25,12 +21,12 @@ impl ResponseError for contextswitch::ContextswitchError {
#[tracing::instrument(level = "debug", skip_all, fields(filter = %task_query.filter.as_ref().unwrap_or(&"".to_string())))] #[tracing::instrument(level = "debug", skip_all, fields(filter = %task_query.filter.as_ref().unwrap_or(&"".to_string())))]
pub async fn list_tasks( pub async fn list_tasks(
task_query: web::Query<TaskQuery>, task_query: web::Query<TaskQuery>,
) -> Result<HttpResponse, contextswitch::ContextswitchError> { ) -> Result<HttpResponse, cs::ContextswitchError> {
let filter = task_query let filter = task_query
.filter .filter
.as_ref() .as_ref()
.map_or(vec![], |filter| filter.split(' ').collect()); .map_or(vec![], |filter| filter.split(' ').collect());
let tasks: Vec<Task> = contextswitch::list_tasks(filter)?; let tasks: Vec<Task> = cs::list_tasks(filter)?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
@@ -40,8 +36,8 @@ pub async fn list_tasks(
#[tracing::instrument(level = "debug", skip_all, fields(definition = %new_task.definition))] #[tracing::instrument(level = "debug", skip_all, fields(definition = %new_task.definition))]
pub async fn add_task( pub async fn add_task(
new_task: web::Json<NewTask>, new_task: web::Json<NewTask>,
) -> Result<HttpResponse, contextswitch::ContextswitchError> { ) -> Result<HttpResponse, cs::ContextswitchError> {
let task: Task = contextswitch::add_task(new_task.definition.split(' ').collect()).await?; let task: Task = cs::add_task(new_task.definition.split(' ').collect()).await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
@@ -52,12 +48,12 @@ pub async fn add_task(
pub async fn update_task( pub async fn update_task(
path: web::Path<TaskId>, path: web::Path<TaskId>,
task: web::Json<Task>, task: web::Json<Task>,
) -> Result<HttpResponse, contextswitch::ContextswitchError> { ) -> Result<HttpResponse, cs::ContextswitchError> {
let task_to_update = task.into_inner(); let task_to_update = task.into_inner();
if path.into_inner() != task_to_update.id { if path.into_inner() != task_to_update.id {
return Ok(HttpResponse::BadRequest().finish()); return Ok(HttpResponse::BadRequest().finish());
} }
let task_updated: Task = contextswitch::update_task(task_to_update).await?; let task_updated: Task = cs::update_task(task_to_update).await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
@@ -65,6 +61,6 @@ pub async fn update_task(
} }
#[tracing::instrument(level = "debug")] #[tracing::instrument(level = "debug")]
pub fn option_task() -> HttpResponse { pub async fn option_task() -> HttpResponse {
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
} }

View File

@@ -1,6 +1,6 @@
use crate::helpers::app_address; use crate::helpers::app_address;
use contextswitch_api::contextswitch; use contextswitch::{Bookmark, ContextswitchData, NewTask, Task};
use contextswitch_types::{Bookmark, ContextswitchData, NewTask, Task}; use contextswitch_api::contextswitch as cs;
use http::uri::Uri; use http::uri::Uri;
use rstest::*; use rstest::*;
@@ -10,7 +10,7 @@ mod list_tasks {
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]
async fn list_tasks(app_address: &str) { async fn list_tasks(app_address: &str) {
let task = contextswitch::add_task(vec![ let task = cs::add_task(vec![
"test", "test",
"list_tasks", "list_tasks",
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'", "contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",
@@ -40,10 +40,10 @@ mod list_tasks {
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]
async fn list_tasks_with_unknown_contextswitch_data(app_address: &str) { async fn list_tasks_with_unknown_cs_data(app_address: &str) {
let task = contextswitch::add_task(vec![ let task = cs::add_task(vec![
"test", "test",
"list_tasks_with_unknown_contextswitch_data", "list_tasks_with_unknown_cs_data",
"contextswitch:'{\"unknown\": 1}'", "contextswitch:'{\"unknown\": 1}'",
]) ])
.await .await
@@ -59,17 +59,14 @@ mod list_tasks {
.expect("Cannot parse JSON result"); .expect("Cannot parse JSON result");
assert_eq!(tasks.len(), 1); assert_eq!(tasks.len(), 1);
assert_eq!( assert_eq!(tasks[0].description, "test list_tasks_with_unknown_cs_data");
tasks[0].description,
"test list_tasks_with_unknown_contextswitch_data"
);
assert!(tasks[0].contextswitch.is_none()); assert!(tasks[0].contextswitch.is_none());
} }
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]
async fn list_tasks_with_invalid_contextswitch_data(app_address: &str) { async fn list_tasks_with_invalid_cs_data(app_address: &str) {
let task = contextswitch::add_task(vec![ let task = cs::add_task(vec![
"test", "test",
"list_tasks_with_invalid_contextswitch_data", "list_tasks_with_invalid_contextswitch_data",
"contextswitch:'}'", "contextswitch:'}'",
@@ -134,7 +131,7 @@ mod update_task {
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]
async fn update_task(app_address: &str) { async fn update_task(app_address: &str) {
let mut task = contextswitch::add_task(vec![ let mut task = cs::add_task(vec![
"test", "test",
"update_task", "update_task",
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'", "contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",

View File

@@ -1,2 +0,0 @@
[application]
log_directive = "debug"

View File

@@ -1,52 +1,202 @@
use actix_web::{dev::Server, http, middleware, web, App, HttpServer}; use chrono::{DateTime, Utc};
use listenfd::ListenFd; use http::uri::Uri;
use std::env; use serde::{Deserialize, Serialize};
use std::net::TcpListener; use std::fmt;
use tracing_actix_web::TracingLogger; use uuid::Uuid;
#[macro_use] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
extern crate lazy_static; #[serde(rename_all = "lowercase")]
pub enum Recurrence {
pub mod configuration; Daily,
pub mod contextswitch; Weekly,
pub mod observability; Monthly,
pub mod routes; Yearly,
}
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let cs_front_base_url = impl fmt::Display for Recurrence {
env::var("CS_FRONT_BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()); fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut server = HttpServer::new(move || { write!(f, "{}", format!("{:?}", self).to_lowercase())
App::new() }
.wrap(TracingLogger::default()) }
.wrap(middleware::Compress::default())
.wrap( #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
middleware::DefaultHeaders::new() #[serde(rename_all = "lowercase")]
.add(("Access-Control-Allow-Origin", cs_front_base_url.as_bytes())) pub enum Status {
.add(( Pending,
"Access-Control-Allow-Methods", Completed,
"POST, GET, OPTIONS".as_bytes(), Recurring,
)) Deleted,
.add(("Access-Control-Allow-Headers", "content-type".as_bytes())), }
)
.route("/ping", web::get().to(routes::ping)) impl fmt::Display for Status {
.route("/tasks", web::get().to(routes::list_tasks)) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
.route("/tasks", web::post().to(routes::add_task)) write!(f, "{}", format!("{:?}", self).to_lowercase())
.route("/tasks/{task_id}", web::put().to(routes::update_task)) }
.route( }
"/tasks",
web::method(http::Method::OPTIONS).to(routes::option_task), #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy, Eq)]
) pub enum Priority {
}) H,
.keep_alive(60) M,
.shutdown_timeout(60); L,
}
let mut listenfd = ListenFd::from_env();
impl fmt::Display for Priority {
server = if let Some(fdlistener) = listenfd.take_tcp_listener(0)? { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
server.listen(fdlistener)? write!(f, "{:?}", self)
} else { }
server.listen(listener)? }
};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
Ok(server.run()) pub struct Bookmark {
#[serde(with = "uri")]
pub uri: Uri,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<BookmarkContent>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct BookmarkContent {
pub title: String,
pub content_preview: Option<String>,
}
pub mod uri {
use http::uri::Uri;
use serde::{self, Deserialize, Deserializer, Serializer};
pub fn serialize<S>(uri: &Uri, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let uri_str = uri.to_string();
serializer.serialize_str(&uri_str)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Uri, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse::<Uri>().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct ContextswitchData {
pub bookmarks: Vec<Bookmark>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct TaskId(pub Uuid);
impl fmt::Display for TaskId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Task {
pub id: TaskId,
#[serde(with = "tw_date_format")]
pub entry: DateTime<Utc>,
#[serde(with = "tw_date_format")]
pub modified: DateTime<Utc>,
pub status: Status,
pub description: String,
pub urgency: f64,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "opt_tw_date_format"
)]
pub due: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "opt_tw_date_format"
)]
pub start: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "opt_tw_date_format"
)]
pub end: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "opt_tw_date_format"
)]
pub wait: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<TaskId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<Priority>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recur: Option<Recurrence>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contextswitch: Option<ContextswitchData>,
}
#[derive(Deserialize, Serialize)]
pub struct NewTask {
pub definition: String,
}
pub mod tw_date_format {
use chrono::{DateTime, TimeZone, Utc};
use serde::{self, Deserialize, Deserializer, Serializer};
const FORMAT: &str = "%Y%m%dT%H%M%SZ";
pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = format!("{}", date.format(FORMAT));
serializer.serialize_str(&s)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Utc.datetime_from_str(&s, FORMAT)
.map_err(serde::de::Error::custom)
}
}
pub mod opt_tw_date_format {
use chrono::{DateTime, TimeZone, Utc};
use serde::{self, Deserialize, Deserializer, Serializer};
const FORMAT: &str = "%Y%m%dT%H%M%SZ";
pub fn serialize<S>(date: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Some(ref d) = *date {
return serializer.serialize_str(&d.format(FORMAT).to_string());
}
serializer.serialize_none()
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Utc.datetime_from_str(&s, FORMAT)
.map(Some)
.map_err(serde::de::Error::custom)
}
} }

12
web/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "contextswitch-web"
version = "0.1.0"
edition = "2021"
authors = ["David Rousselie <david@rousselie.name>"]
[[bin]]
path = "src/main.rs"
name = "contextswitch-web"
[dependencies]
yew = "0.19"

1
web/Makefile.toml Normal file
View File

@@ -0,0 +1 @@
extend = "../Makefile.toml"

7
web/index.html Normal file
View File

@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Contextswitch</title>
</head>
</html>

12
web/src/main.rs Normal file
View File

@@ -0,0 +1,12 @@
use yew::prelude::*;
#[function_component(App)]
fn app() -> Html {
html! {
<h1>{ "Hello World" }</h1>
}
}
fn main() {
yew::start_app::<App>();
}