Use cargo workspaces

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

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"

7
api/config/default.toml Normal file
View File

@@ -0,0 +1,7 @@
[application]
port = 8000
# See https://docs.rs/tracing-subscriber/latest/tracing_subscriber/struct.EnvFilter.html
log_directive = "info"
[taskwarrior]
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"

43
api/src/configuration.rs Normal file
View File

@@ -0,0 +1,43 @@
use config::{Config, ConfigError, Environment, File};
use serde::Deserialize;
use std::env;
#[derive(Deserialize)]
pub struct Settings {
pub application: ApplicationSettings,
pub taskwarrior: TaskwarriorSettings,
}
#[derive(Deserialize)]
pub struct ApplicationSettings {
pub port: u16,
pub log_directive: String,
}
#[derive(Deserialize)]
pub struct TaskwarriorSettings {
pub data_location: Option<String>,
pub taskrc: Option<String>,
}
impl Settings {
pub fn new_from_file(file: Option<String>) -> Result<Self, ConfigError> {
let config_file_required = file.is_some();
let config_file =
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()
.add_source(File::with_name(&format!("{}/default", config_path)))
.add_source(File::with_name(&format!("{}/local", config_path)).required(false))
.add_source(File::with_name(&config_file).required(config_file_required))
.add_source(Environment::with_prefix("cs"))
.build()?;
config.try_deserialize()
}
pub fn new() -> Result<Self, ConfigError> {
Settings::new_from_file(None)
}
}

View File

@@ -0,0 +1,56 @@
use crate::contextswitch::taskwarrior;
use contextswitch::Task;
use serde_json;
fn error_chain_fmt(
e: &impl std::error::Error,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
writeln!(f, "{}\n", e)?;
let mut current = e.source();
while let Some(cause) = current {
writeln!(f, "Caused by:\n\t{}", cause)?;
current = cause.source();
}
Ok(())
}
impl std::fmt::Debug for ContextswitchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_chain_fmt(self, f)
}
}
#[derive(thiserror::Error)]
pub enum ContextswitchError {
#[error("Invalid Contextswitch data")]
InvalidDataError(#[from] serde_json::Error),
#[error(transparent)]
UnexpectedError(#[from] anyhow::Error),
}
#[tracing::instrument(level = "debug")]
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<Task>, ContextswitchError> {
let tasks: Vec<Task> = taskwarrior::list_tasks(filters)
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?
.iter()
.map(Task::from)
.collect();
Ok(tasks)
}
#[tracing::instrument(level = "debug")]
pub async fn add_task(add_args: Vec<&str>) -> Result<Task, ContextswitchError> {
let taskwarrior_task = taskwarrior::add_task(add_args)
.await
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?;
Ok(taskwarrior_task.into())
}
#[tracing::instrument(level = "debug")]
pub async fn update_task(task_to_update: Task) -> Result<Task, ContextswitchError> {
let taskwarrior_task = taskwarrior::update_task(task_to_update.try_into()?)
.await
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?;
Ok(taskwarrior_task.into())
}

View File

@@ -0,0 +1,4 @@
mod api;
pub mod taskwarrior;
pub use api::*;

View File

@@ -0,0 +1,633 @@
use crate::configuration::TaskwarriorSettings;
use anyhow::{anyhow, Context};
use chrono::{DateTime, Utc};
use configparser::ini::Ini;
use contextswitch::{ContextswitchData, Task, TaskId};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json;
use std::env;
use std::fmt;
use std::path::Path;
use std::process::Command;
use std::str;
use tokio::sync::Mutex;
use tracing::{debug, warn};
use uuid::Uuid;
use super::ContextswitchError;
#[tracing::instrument(level = "debug")]
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<TaskwarriorTask>, TaskwarriorError> {
let args = [filters, vec!["export"]].concat();
let export_output = Command::new("task")
.args(args)
.output()
.map_err(TaskwarriorError::ExecutionError)?;
let output =
String::from_utf8(export_output.stdout).context("Failed to read Taskwarrior output")?;
let tasks: Vec<TaskwarriorTask> = serde_json::from_str(&output)
.map_err(|e| TaskwarriorError::OutputParsingError { source: e, output })?;
Ok(tasks)
}
#[tracing::instrument(level = "debug")]
pub fn get_task_by_local_id(
id: &TaskwarriorTaskLocalId,
) -> Result<Option<TaskwarriorTask>, TaskwarriorError> {
let mut tasks: Vec<TaskwarriorTask> = list_tasks(vec![&id.to_string()])?;
if tasks.len() > 1 {
return Err(TaskwarriorError::UnexpectedError(anyhow!(
"Found more than 1 task when searching for task with local ID {}",
id
)));
}
Ok(tasks.pop())
}
#[tracing::instrument(level = "debug")]
pub fn get_task_by_id(
uuid: &TaskwarriorTaskId,
) -> Result<Option<TaskwarriorTask>, TaskwarriorError> {
let mut tasks: Vec<TaskwarriorTask> = list_tasks(vec![&uuid.to_string()])?;
if tasks.len() > 1 {
return Err(TaskwarriorError::UnexpectedError(anyhow!(
"Found more than 1 task when searching for task with UUID {}",
uuid
)));
}
Ok(tasks.pop())
}
lazy_static! {
static ref RE: Regex = Regex::new(r"Modified 1 task.").unwrap();
static ref TW_WRITE_LOCK: Mutex<u32> = Mutex::new(0);
}
#[tracing::instrument(level = "debug")]
pub async fn add_task(add_args: Vec<&str>) -> Result<TaskwarriorTask, TaskwarriorError> {
lazy_static! {
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap();
}
let _lock = TW_WRITE_LOCK.lock().await;
let args = [vec!["add"], add_args].concat();
let add_output = Command::new("task")
.args(args)
.output()
.map_err(TaskwarriorError::ExecutionError)?;
let output =
String::from_utf8(add_output.stdout).context("Failed to read Taskwarrior output")?;
let task_id_capture = RE
.captures(&output)
.ok_or_else(|| anyhow!("Cannot extract task ID from: {}", &output))?;
let task_id_str = task_id_capture
.name("id")
.ok_or_else(|| anyhow!("Cannot extract task ID value from: {}", &output))?
.as_str();
let task_id = TaskwarriorTaskLocalId(
task_id_str
.parse::<u64>()
.context("Cannot parse task ID value")?,
);
let task = get_task_by_local_id(&task_id)?;
task.ok_or_else(|| {
TaskwarriorError::UnexpectedError(anyhow!(
"Newly created task with ID {} was not found",
task_id
))
})
}
#[tracing::instrument(level = "debug")]
pub async fn update_task(action: TaskwarriorAction) -> Result<TaskwarriorTask, TaskwarriorError> {
lazy_static! {
static ref RE: Regex = Regex::new(r"Modified 1 task.").unwrap();
}
let _lock = TW_WRITE_LOCK.lock().await;
let args = [
vec![action.uuid.to_string(), "mod".to_string()],
action.args,
]
.concat();
Command::new("task")
.args(args)
.output()
.map_err(TaskwarriorError::ExecutionError)?;
let updated_task = get_task_by_id(&action.uuid)?;
updated_task.ok_or_else(|| {
TaskwarriorError::UnexpectedError(anyhow!(
"Updated task with UUID {} was not found",
action.uuid
))
})
}
// Types
// TaskwarriorTask
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct TaskwarriorTaskLocalId(pub u64);
impl fmt::Display for TaskwarriorTaskLocalId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct TaskwarriorTaskId(pub Uuid);
impl fmt::Display for TaskwarriorTaskId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<TaskwarriorTaskId> for TaskId {
fn from(task: TaskwarriorTaskId) -> Self {
TaskId(task.0)
}
}
impl From<TaskId> for TaskwarriorTaskId {
fn from(task: TaskId) -> Self {
TaskwarriorTaskId(task.0)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct TaskwarriorTask {
pub uuid: TaskwarriorTaskId,
pub id: TaskwarriorTaskLocalId,
#[serde(with = "contextswitch::tw_date_format")]
pub entry: DateTime<Utc>,
#[serde(with = "contextswitch::tw_date_format")]
pub modified: DateTime<Utc>,
pub status: contextswitch::Status,
pub description: String,
pub urgency: f64,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "contextswitch::opt_tw_date_format"
)]
pub due: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "contextswitch::opt_tw_date_format"
)]
pub start: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "contextswitch::opt_tw_date_format"
)]
pub end: Option<DateTime<Utc>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "contextswitch::opt_tw_date_format"
)]
pub wait: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<TaskwarriorTaskId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub priority: Option<contextswitch::Priority>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recur: Option<contextswitch::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<String>,
}
impl From<TaskwarriorTask> for Task {
fn from(task: TaskwarriorTask) -> Self {
(&task).into()
}
}
impl From<&TaskwarriorTask> for Task {
fn from(task: &TaskwarriorTask) -> Self {
let cs_data =
task.contextswitch
.as_ref()
.and_then(|cs_string| -> Option<ContextswitchData> {
let contextswitch_data_result = serde_json::from_str(cs_string);
if contextswitch_data_result.is_err() {
warn!(
"Invalid Contextswitch data found in {}: {}",
&task.uuid, cs_string
);
}
contextswitch_data_result.ok()
});
Task {
id: task.uuid.clone().into(),
entry: task.entry,
modified: task.modified,
status: task.status,
description: task.description.clone(),
urgency: task.urgency,
due: task.due,
start: task.start,
end: task.end,
wait: task.wait,
parent: task.parent.clone().map(|id| id.into()),
project: task.project.clone(),
priority: task.priority,
recur: task.recur,
tags: task.tags.clone(),
contextswitch: cs_data,
}
}
}
// TaskwarriorAction
#[derive(Debug)]
pub struct TaskwarriorAction {
pub uuid: TaskwarriorTaskId,
pub args: Vec<String>,
}
fn to_arg(arg: &str) -> impl Fn(String) -> String + '_ {
move |value: String| format!("{}:{}", arg, value)
}
fn format_date(date: DateTime<Utc>) -> String {
date.format("%Y-%m-%dT%H:%M:%SZ").to_string()
}
impl TryFrom<Task> for TaskwarriorAction {
type Error = ContextswitchError;
fn try_from(task: Task) -> Result<Self, Self::Error> {
(&task).try_into()
}
}
fn format_json<T>(data_opt: &Option<T>) -> Result<Option<String>, ContextswitchError>
where
T: Sized + Serialize,
{
data_opt
.as_ref()
.map(|data| serde_json::to_string(data).map_err(ContextswitchError::InvalidDataError))
.transpose()
}
impl TryFrom<&Task> for TaskwarriorAction {
type Error = ContextswitchError;
fn try_from(task: &Task) -> Result<Self, Self::Error> {
let args = vec![task.description.clone()];
let tags_args = task
.tags
.clone()
.map(|tags| {
tags.iter()
.map(|tag| format!("+{}", tag)) // TODO remove tags
.collect::<Vec<String>>()
})
.unwrap_or_else(Vec::new);
let opt_args = [
task.due
.map(format_date)
.or_else(|| Some("".to_string()))
.map(to_arg("due")),
task.start
.map(format_date)
.or_else(|| Some("".to_string()))
.map(to_arg("start")),
task.end
.map(format_date)
.or_else(|| Some("".to_string()))
.map(to_arg("end")),
task.wait
.map(format_date)
.or_else(|| Some("".to_string()))
.map(to_arg("wait")),
task.parent
.as_ref()
.map(|id| id.to_string())
.or_else(|| Some("".to_string()))
.map(to_arg("parent")),
task.project
.clone()
.or_else(|| Some("".to_string()))
.map(to_arg("project")),
task.priority
.map(|priority| priority.to_string())
.or_else(|| Some("".to_string()))
.map(to_arg("priority")),
task.recur
.map(|recur| recur.to_string())
.or_else(|| Some("".to_string()))
.map(to_arg("recur")),
format_json(&task.contextswitch)?
.or_else(|| Some("".to_string()))
.map(to_arg("contextswitch")),
];
Ok(TaskwarriorAction {
uuid: task.id.clone().into(),
args: [
args,
tags_args,
opt_args
.iter()
.filter_map(|arg| arg.clone())
.collect::<Vec<String>>(),
]
.concat(),
})
}
}
// Errors
#[derive(thiserror::Error, Debug)]
pub enum TaskwarriorError {
#[error("Error while executing Taskwarrior")]
ExecutionError(#[from] std::io::Error),
#[error("Error while parsing Taskwarrior output")]
OutputParsingError {
#[source]
source: serde_json::Error,
output: String,
},
#[error(transparent)]
UnexpectedError(#[from] anyhow::Error),
}
// Taskwarrior config functions
fn write_default_config(data_location: &str) -> String {
let mut taskrc = Ini::new();
taskrc.setstr("default", "data.location", Some(data_location));
taskrc.setstr("default", "uda.contextswitch.type", Some("string"));
taskrc.setstr(
"default",
"uda.contextswitch.label",
Some("Contextswitch data"),
);
taskrc.setstr("default", "uda.contextswitch.default", Some("{}"));
let taskrc_path = Path::new(&data_location).join(".taskrc");
let taskrc_location = taskrc_path.to_str().unwrap();
taskrc.write(taskrc_location).unwrap();
taskrc_location.into()
}
pub fn load_config(settings: &TaskwarriorSettings) -> String {
if let Some(taskrc_location) = &settings.taskrc {
let mut taskrc = Ini::new();
taskrc
.load(&taskrc_location)
.unwrap_or_else(|_| panic!("Cannot load taskrc file {}", taskrc_location));
let data_location = taskrc.get("default", "data.location").unwrap_or_else(|| {
panic!(
"'data.location' must be set in taskrc file {}",
taskrc_location
)
});
env::set_var("TASKRC", &taskrc_location);
debug!(
"Extracted data location `{}` from existing taskrc `{}`",
data_location, taskrc_location
);
data_location
} else {
let data_location = settings
.data_location
.as_ref()
.expect("Expecting taskwarrior.taskrc or taskwarrior.data_location setting to be set")
.to_string();
let taskrc_location = write_default_config(&data_location);
env::set_var("TASKRC", &taskrc_location);
debug!("Default taskrc written in `{}`", &taskrc_location);
data_location
}
}
#[cfg(test)]
mod tests {
mod from_taskwarrior_task_to_contextswitch_task {
use super::super::*;
use chrono::TimeZone;
use contextswitch::Bookmark;
use http::uri::Uri;
use proptest::prelude::*;
#[test]
fn test_successful_full_convertion() {
let tw_task = TaskwarriorTask {
uuid: TaskwarriorTaskId(Uuid::new_v4()),
id: TaskwarriorTaskLocalId(42),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch::Status::Pending,
description: "simple task".to_string(),
urgency: 0.5,
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),
start: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 3)),
end: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 4)),
wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)),
parent: Some(TaskwarriorTaskId(Uuid::new_v4())),
project: Some("simple project".to_string()),
priority: Some(contextswitch::Priority::H),
recur: Some(contextswitch::Recurrence::Daily),
tags: Some(vec!["tag1".to_string(), "tag2".to_string()]),
contextswitch: Some(String::from(
r#"{"bookmarks": [{"uri": "https://www.example.com/path"}]}"#,
)),
};
let cs_task: Task = (&tw_task).into();
assert_eq!(tw_task.uuid.0, cs_task.id.0);
assert_eq!(tw_task.entry, cs_task.entry);
assert_eq!(tw_task.modified, cs_task.modified);
assert_eq!(tw_task.status, cs_task.status);
assert_eq!(tw_task.description, cs_task.description);
assert_eq!(tw_task.urgency, cs_task.urgency);
assert_eq!(tw_task.due, cs_task.due);
assert_eq!(tw_task.start, cs_task.start);
assert_eq!(tw_task.end, cs_task.end);
assert_eq!(tw_task.wait, cs_task.wait);
assert_eq!(
tw_task.parent.map(|id| id.to_string()),
cs_task.parent.map(|id| id.to_string())
);
assert_eq!(tw_task.project, cs_task.project);
assert_eq!(tw_task.priority, cs_task.priority);
assert_eq!(tw_task.recur, cs_task.recur);
assert_eq!(tw_task.tags, cs_task.tags);
assert_eq!(
Some(ContextswitchData {
bookmarks: vec![Bookmark {
uri: "https://www.example.com/path".parse::<Uri>().unwrap(),
content: None
}]
}),
cs_task.contextswitch
);
}
proptest! {
#[test]
fn test_conversion_with_invalid_contextswitch_data_format(cs_data in ".*") {
let tw_task = TaskwarriorTask {
uuid: TaskwarriorTaskId(Uuid::new_v4()),
id: TaskwarriorTaskLocalId(42),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch::Status::Pending,
description: "simple task".to_string(),
urgency: 0.5,
due: None,
start: None,
end: None,
wait: None,
parent: None,
project: None,
priority: None,
recur: None,
tags: None,
contextswitch: Some(cs_data),
};
let cs_task: Task = (&tw_task).into();
assert_eq!(tw_task.uuid.0, cs_task.id.0);
assert_eq!(tw_task.entry, cs_task.entry);
assert_eq!(tw_task.modified, cs_task.modified);
assert_eq!(tw_task.status, cs_task.status);
assert_eq!(tw_task.description, cs_task.description);
assert_eq!(tw_task.urgency, cs_task.urgency);
assert_eq!(None, cs_task.contextswitch);
}
}
}
mod from_contextswitch_task_to_taskwarrior_action {
use super::super::*;
use chrono::TimeZone;
use contextswitch::{Bookmark, Priority, Recurrence};
use http::Uri;
#[test]
fn test_successful_convertion() {
let task = Task {
id: TaskId(Uuid::new_v4()),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch::Status::Pending,
description: "simple task".to_string(),
urgency: 0.5,
due: None,
start: None,
end: None,
wait: None,
parent: None,
project: None,
priority: None,
recur: None,
tags: None,
contextswitch: None,
};
let action: TaskwarriorAction = (&task)
.try_into()
.expect("Failed to convert Task into TaskwarriorAction");
assert_eq!(task.id.0, action.uuid.0);
assert_eq!(
vec![
task.description,
"due:".to_string(),
"start:".to_string(),
"end:".to_string(),
"wait:".to_string(),
"parent:".to_string(),
"project:".to_string(),
"priority:".to_string(),
"recur:".to_string(),
"contextswitch:".to_string(),
],
action.args
);
}
#[test]
fn test_successful_full_convertion() {
let task = Task {
id: TaskId(Uuid::new_v4()),
entry: Utc.ymd(2022, 1, 1).and_hms(1, 0, 0),
modified: Utc.ymd(2022, 1, 1).and_hms(1, 0, 1),
status: contextswitch::Status::Pending,
description: "simple task".to_string(),
urgency: 0.5,
due: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 2)),
start: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 3)),
end: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 4)),
wait: Some(Utc.ymd(2022, 1, 1).and_hms(1, 0, 5)),
parent: Some(TaskId(Uuid::new_v4())),
project: Some("myproject".to_string()),
priority: Some(Priority::H),
recur: Some(Recurrence::Monthly),
tags: Some(vec!["tag1".to_string(), "tag2".to_string()]),
contextswitch: Some(ContextswitchData {
bookmarks: vec![
Bookmark {
uri: "https://www.example.com/path".parse::<Uri>().unwrap(),
content: None,
},
Bookmark {
uri: "https://www.example.com/path2".parse::<Uri>().unwrap(),
content: None,
},
],
}),
};
let action: TaskwarriorAction = (&task)
.try_into()
.expect("Failed to convert Task into TaskwarriorAction");
assert_eq!(task.id.0, action.uuid.0);
assert_eq!(
vec![
task.description,
"+tag1".to_string(),
"+tag2".to_string(),
"due:2022-01-01T01:00:02Z".to_string(),
"start:2022-01-01T01:00:03Z".to_string(),
"end:2022-01-01T01:00:04Z".to_string(),
"wait:2022-01-01T01:00:05Z".to_string(),
format!("parent:{}", task.parent.unwrap()),
"project:myproject".to_string(),
"priority:H".to_string(),
"recur:monthly".to_string(),
String::from(
r#"contextswitch:{"bookmarks":[{"uri":"https://www.example.com/path"},{"uri":"https://www.example.com/path2"}]}"#
)
],
action.args
);
}
}
}

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())
}

17
api/src/main.rs Normal file
View File

@@ -0,0 +1,17 @@
use contextswitch_api::configuration::Settings;
use contextswitch_api::observability::{get_subscriber, init_subscriber};
use contextswitch_api::{contextswitch::taskwarrior, run};
use std::net::TcpListener;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let settings = Settings::new().expect("Cannot load Contextswitch configuration");
let subscriber = get_subscriber(&settings.application.log_directive);
init_subscriber(subscriber);
taskwarrior::load_config(&settings.taskwarrior);
let listener = TcpListener::bind(format!("0.0.0.0:{}", settings.application.port))
.expect("Failed to bind port");
run(listener)?.await
}

22
api/src/observability.rs Normal file
View File

@@ -0,0 +1,22 @@
use tracing::{subscriber::set_global_default, Subscriber};
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::fmt::TestWriter;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
pub fn get_subscriber(env_filter_str: &str) -> impl Subscriber + Send + Sync {
let formatting_layer = BunyanFormattingLayer::new("contextswitch-api".into(), TestWriter::new);
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter_str));
tracing_subscriber::registry()
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}
pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {
LogTracer::init().expect("Failed to set logger");
set_global_default(subscriber).expect("Failed to set subscriber");
}

View File

@@ -0,0 +1,5 @@
use actix_web::HttpResponse;
pub async fn ping() -> HttpResponse {
HttpResponse::Ok().finish()
}

5
api/src/routes/mod.rs Normal file
View File

@@ -0,0 +1,5 @@
mod health_check;
mod tasks;
pub use health_check::*;
pub use tasks::*;

66
api/src/routes/tasks.rs Normal file
View File

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

View File

@@ -0,0 +1,15 @@
use crate::helpers::app_address;
use rstest::*;
#[rstest]
#[tokio::test]
async fn health_check_works(app_address: &str) {
let response = reqwest::Client::new()
.get(&format!("{}/ping", &app_address))
.send()
.await
.expect("Failed to execute request.");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}

43
api/tests/api/helpers.rs Normal file
View File

@@ -0,0 +1,43 @@
use contextswitch_api::configuration::Settings;
use contextswitch_api::contextswitch::taskwarrior;
use contextswitch_api::observability::{get_subscriber, init_subscriber};
use mktemp::Temp;
use rstest::*;
use std::net::TcpListener;
use tracing::info;
fn setup_tracing(settings: &Settings) {
info!("Setting up tracing");
let subscriber = get_subscriber(&settings.application.log_directive);
init_subscriber(subscriber);
}
fn setup_server() -> String {
info!("Setting up server");
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = contextswitch_api::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
fn setup_taskwarrior(mut settings: Settings) -> String {
info!("Setting up Taskwarrior");
let tmp_dir = Temp::new_dir().unwrap();
settings.taskwarrior.data_location = tmp_dir.to_str().map(String::from);
let task_data_location = taskwarrior::load_config(&settings.taskwarrior);
tmp_dir.release();
task_data_location
}
#[fixture]
#[once]
pub fn app_address() -> String {
let settings = Settings::new_from_file(Some("config/test".to_string()))
.expect("Cannot load test configuration");
setup_tracing(&settings);
setup_taskwarrior(settings);
setup_server()
}

3
api/tests/api/main.rs Normal file
View File

@@ -0,0 +1,3 @@
mod health_check;
mod helpers;
mod tasks;

178
api/tests/api/tasks.rs Normal file
View File

@@ -0,0 +1,178 @@
use crate::helpers::app_address;
use contextswitch::{Bookmark, ContextswitchData, NewTask, Task};
use contextswitch_api::contextswitch as cs;
use http::uri::Uri;
use rstest::*;
mod list_tasks {
use super::*;
#[rstest]
#[tokio::test]
async fn list_tasks(app_address: &str) {
let task = cs::add_task(vec![
"test",
"list_tasks",
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",
])
.await
.unwrap();
let tasks: Vec<Task> = reqwest::Client::new()
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
.send()
.await
.expect("Failed to execute request")
.json()
.await
.expect("Cannot parse JSON result");
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].description, "test list_tasks");
let cs_data = tasks[0].contextswitch.as_ref().unwrap();
assert_eq!(cs_data.bookmarks.len(), 1);
assert_eq!(cs_data.bookmarks[0].content, None);
assert_eq!(
cs_data.bookmarks[0].uri,
"https://example.com/path?filter=1".parse::<Uri>().unwrap()
);
}
#[rstest]
#[tokio::test]
async fn list_tasks_with_unknown_cs_data(app_address: &str) {
let task = cs::add_task(vec![
"test",
"list_tasks_with_unknown_cs_data",
"contextswitch:'{\"unknown\": 1}'",
])
.await
.unwrap();
let tasks: Vec<Task> = reqwest::Client::new()
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
.send()
.await
.expect("Failed to execute request")
.json()
.await
.expect("Cannot parse JSON result");
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].description, "test list_tasks_with_unknown_cs_data");
assert!(tasks[0].contextswitch.is_none());
}
#[rstest]
#[tokio::test]
async fn list_tasks_with_invalid_cs_data(app_address: &str) {
let task = cs::add_task(vec![
"test",
"list_tasks_with_invalid_contextswitch_data",
"contextswitch:'}'",
])
.await
.unwrap();
let tasks: Vec<Task> = reqwest::Client::new()
.get(&format!("{}/tasks?filter={}", &app_address, task.id))
.send()
.await
.expect("Failed to execute request")
.json()
.await
.expect("Cannot parse JSON result");
assert_eq!(tasks.len(), 1);
assert_eq!(
tasks[0].description,
"test list_tasks_with_invalid_contextswitch_data"
);
assert!(tasks[0].contextswitch.is_none());
}
}
mod add_task {
use super::*;
#[rstest]
#[tokio::test]
async fn add_task(app_address: &str) {
let task: Task = reqwest::Client::new()
.post(&format!("{}/tasks", &app_address))
.json(&NewTask {
definition:
"test add_task contextswitch:{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}"
.to_string(),
})
.send()
.await
.expect("Failed to execute request")
.json()
.await
.expect("Cannot parse JSON result");
assert_eq!(task.description, "test add_task");
assert_eq!(
task.contextswitch.as_ref().unwrap(),
&ContextswitchData {
bookmarks: vec![Bookmark {
uri: "https://example.com/path?filter=1".parse::<Uri>().unwrap(),
content: None
}]
}
);
}
}
mod update_task {
use super::*;
#[rstest]
#[tokio::test]
async fn update_task(app_address: &str) {
let mut task = cs::add_task(vec![
"test",
"update_task",
"contextswitch:'{\"bookmarks\":[{\"uri\":\"https://example.com/path?filter=1\"}]}'",
])
.await
.unwrap();
task.description = "updated task description".to_string();
let cs_data = task.contextswitch.as_mut().unwrap();
cs_data.bookmarks.push(Bookmark {
uri: "https://example.com/path2".parse::<Uri>().unwrap(),
content: None,
});
let updated_task: Task = reqwest::Client::new()
.put(&format!("{}/tasks/{}", &app_address, task.id))
.json(&task)
.send()
.await
.expect("Failed to execute request")
.json()
.await
.expect("Cannot parse JSON result");
assert_eq!(updated_task.description, "updated task description");
assert_eq!(
updated_task.contextswitch.as_ref().unwrap(),
&ContextswitchData {
bookmarks: vec![
Bookmark {
uri: "https://example.com/path?filter=1".parse::<Uri>().unwrap(),
content: None
},
Bookmark {
uri: "https://example.com/path2".parse::<Uri>().unwrap(),
content: None
}
]
}
);
}
// TODO : test incoherent task id
}