Compare commits

..

4 Commits

Author SHA1 Message Date
6d16f34dd4 Add task update endpoint 2022-02-20 20:53:34 +01:00
2b1df4b6fd Use configuration file 2022-02-19 20:37:30 +01:00
f85da365e9 Add some unit tests 2022-02-19 20:35:32 +01:00
a5c74d7e4c Refactor the integration test suite 2022-02-19 14:00:07 +01:00
18 changed files with 1095 additions and 252 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
/target /target
config/local.*

View File

@@ -6,3 +6,4 @@ repos:
- id: cargo-check - id: cargo-check
args: ['--tests'] args: ['--tests']
- id: clippy - id: clippy
args: ['--tests', '--', '-D', 'warnings']

373
Cargo.lock generated
View File

@@ -29,7 +29,7 @@ dependencies = [
"actix-rt", "actix-rt",
"actix-service", "actix-service",
"actix-utils", "actix-utils",
"ahash", "ahash 0.7.6",
"base64", "base64",
"bitflags", "bitflags",
"brotli2", "brotli2",
@@ -51,7 +51,7 @@ dependencies = [
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"rand", "rand",
"sha-1", "sha-1 0.10.0",
"smallvec", "smallvec",
"zstd", "zstd",
] ]
@@ -145,7 +145,7 @@ dependencies = [
"actix-service", "actix-service",
"actix-utils", "actix-utils",
"actix-web-codegen", "actix-web-codegen",
"ahash", "ahash 0.7.6",
"bytes", "bytes",
"cfg-if", "cfg-if",
"cookie", "cookie",
@@ -187,6 +187,12 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "ahash"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "739f4a8db6605981345c5654f3a85b056ce52f37a39d34da03f25bf2151ea16e"
[[package]] [[package]]
name = "ahash" name = "ahash"
version = "0.7.6" version = "0.7.6"
@@ -222,6 +228,17 @@ version = "1.0.53"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0" checksum = "94a45b455c14666b85fc40a019e8ab9eb75e3a124e05494f5397122bc9eb06e0"
[[package]]
name = "async-trait"
version = "0.1.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "061a7acccaa286c011ddc30970520b98fa40e00c9d644633fb26b5fc63a265e3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.0.1" version = "1.0.1"
@@ -234,19 +251,55 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bit-set"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "block-buffer"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b"
dependencies = [
"block-padding",
"byte-tools",
"byteorder",
"generic-array 0.12.4",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95" checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95"
dependencies = [ dependencies = [
"generic-array", "generic-array 0.14.5",
]
[[package]]
name = "block-padding"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5"
dependencies = [
"byte-tools",
] ]
[[package]] [[package]]
@@ -275,6 +328,18 @@ version = "3.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899"
[[package]]
name = "byte-tools"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"
[[package]]
name = "byteorder"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.1.0" version = "1.1.0"
@@ -319,6 +384,25 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "config"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54ad70579325f1a38ea4c13412b82241c5900700a69785d73e2736bd65a33f86"
dependencies = [
"async-trait",
"json5",
"lazy_static",
"nom",
"pathdiff",
"ron",
"rust-ini",
"serde",
"serde_json",
"toml",
"yaml-rust",
]
[[package]] [[package]]
name = "configparser" name = "configparser"
version = "3.0.0" version = "3.0.0"
@@ -333,13 +417,14 @@ dependencies = [
"actix-web", "actix-web",
"anyhow", "anyhow",
"chrono", "chrono",
"config",
"configparser", "configparser",
"contextswitch-types", "contextswitch-types",
"dotenv",
"http", "http",
"lazy_static", "lazy_static",
"listenfd", "listenfd",
"mktemp", "mktemp",
"proptest",
"regex", "regex",
"reqwest", "reqwest",
"rstest", "rstest",
@@ -358,7 +443,7 @@ dependencies = [
[[package]] [[package]]
name = "contextswitch-types" name = "contextswitch-types"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/dax/contextswitch-types.git#d99bd6e6aebece04a41bdf62f00eaafcb73640ea" source = "git+https://github.com/dax/contextswitch-types.git#974890d5f59efd257dd77faa44ec5106efcb1330"
dependencies = [ dependencies = [
"chrono", "chrono",
"http", "http",
@@ -424,7 +509,7 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0" checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0"
dependencies = [ dependencies = [
"generic-array", "generic-array 0.14.5",
] ]
[[package]] [[package]]
@@ -440,22 +525,34 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "digest"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5"
dependencies = [
"generic-array 0.12.4",
]
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.1" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b" checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b"
dependencies = [ dependencies = [
"block-buffer", "block-buffer 0.10.0",
"crypto-common", "crypto-common",
"generic-array", "generic-array 0.14.5",
] ]
[[package]] [[package]]
name = "dotenv" name = "dlv-list"
version = "0.15.0" version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" checksum = "68df3f2b690c1b86e65ef7830956aededf3cb0a16f898f79b9a6f421a7b6211b"
dependencies = [
"rand",
]
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
@@ -466,6 +563,12 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "fake-simd"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "1.6.0" version = "1.6.0"
@@ -563,6 +666,15 @@ dependencies = [
"pin-utils", "pin-utils",
] ]
[[package]]
name = "generic-array"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd"
dependencies = [
"typenum",
]
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.5" version = "0.14.5"
@@ -613,6 +725,15 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
dependencies = [
"ahash 0.4.7",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.11.2" version = "0.11.2"
@@ -717,7 +838,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223" checksum = "282a6247722caba404c065016bbfa522806e51714c34f5dfc3e4a3a46fcb4223"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"hashbrown", "hashbrown 0.11.2",
] ]
[[package]] [[package]]
@@ -765,6 +886,17 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "json5"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1"
dependencies = [
"pest",
"pest_derive",
"serde",
]
[[package]] [[package]]
name = "language-tags" name = "language-tags"
version = "0.3.2" version = "0.3.2"
@@ -783,6 +915,12 @@ version = "0.2.112"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125" checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125"
[[package]]
name = "linked-hash-map"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]] [[package]]
name = "listenfd" name = "listenfd"
version = "0.3.5" version = "0.3.5"
@@ -830,6 +968,12 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]] [[package]]
name = "matchers" name = "matchers"
version = "0.1.0" version = "0.1.0"
@@ -857,6 +1001,12 @@ version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.4.4" version = "0.4.4"
@@ -929,6 +1079,17 @@ dependencies = [
"tempfile", "tempfile",
] ]
[[package]]
name = "nom"
version = "7.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b1d11e1ef389c76fe5b81bcaf2ea32cf88b62bc494e19f493d0b30e7a930109"
dependencies = [
"memchr",
"minimal-lexical",
"version_check",
]
[[package]] [[package]]
name = "ntapi" name = "ntapi"
version = "0.3.6" version = "0.3.6"
@@ -973,6 +1134,12 @@ version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5" checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5"
[[package]]
name = "opaque-debug"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c"
[[package]] [[package]]
name = "openssl" name = "openssl"
version = "0.10.38" version = "0.10.38"
@@ -1006,6 +1173,16 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "ordered-multimap"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c672c7ad9ec066e428c00eb917124a06f08db19e2584de982cc34b1f4c12485"
dependencies = [
"dlv-list",
"hashbrown 0.9.1",
]
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.11.2" version = "0.11.2"
@@ -1037,12 +1214,61 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0744126afe1a6dd7f394cb50a716dbe086cb06e255e53d8d0185d82828358fb5" checksum = "0744126afe1a6dd7f394cb50a716dbe086cb06e255e53d8d0185d82828358fb5"
[[package]]
name = "pathdiff"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
[[package]] [[package]]
name = "percent-encoding" name = "percent-encoding"
version = "2.1.0" version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
[[package]]
name = "pest"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53"
dependencies = [
"ucd-trie",
]
[[package]]
name = "pest_derive"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0"
dependencies = [
"pest",
"pest_generator",
]
[[package]]
name = "pest_generator"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b8db626e31e5b81787b9783425769681b347011cc59471e33ea46d2ea0cf55"
dependencies = [
"pest",
"pest_meta",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "pest_meta"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d"
dependencies = [
"maplit",
"pest",
"sha-1 0.8.2",
]
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.0.10" version = "1.0.10"
@@ -1096,6 +1322,38 @@ dependencies = [
"unicode-xid", "unicode-xid",
] ]
[[package]]
name = "proptest"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0d9cc07f18492d879586c92b485def06bc850da3118075cd45d50e9c95b0e5"
dependencies = [
"bit-set",
"bitflags",
"byteorder",
"lazy_static",
"num-traits",
"quick-error 2.0.1",
"rand",
"rand_chacha",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.14" version = "1.0.14"
@@ -1145,6 +1403,15 @@ dependencies = [
"rand_core", "rand_core",
] ]
[[package]]
name = "rand_xorshift"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f"
dependencies = [
"rand_core",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.2.10" version = "0.2.10"
@@ -1224,6 +1491,17 @@ dependencies = [
"winreg", "winreg",
] ]
[[package]]
name = "ron"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678"
dependencies = [
"base64",
"bitflags",
"serde",
]
[[package]] [[package]]
name = "rstest" name = "rstest"
version = "0.12.0" version = "0.12.0"
@@ -1237,6 +1515,16 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "rust-ini"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63471c4aa97a1cf8332a5f97709a79a4234698de6a1f5087faf66f2dae810e22"
dependencies = [
"cfg-if",
"ordered-multimap",
]
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.0" version = "0.4.0"
@@ -1246,6 +1534,18 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "rusty-fork"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f"
dependencies = [
"fnv",
"quick-error 1.2.3",
"tempfile",
"wait-timeout",
]
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.9" version = "1.0.9"
@@ -1340,6 +1640,18 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "sha-1"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df"
dependencies = [
"block-buffer 0.7.3",
"digest 0.8.1",
"fake-simd",
"opaque-debug",
]
[[package]] [[package]]
name = "sha-1" name = "sha-1"
version = "0.10.0" version = "0.10.0"
@@ -1348,7 +1660,7 @@ checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures", "cpufeatures",
"digest", "digest 0.10.1",
] ]
[[package]] [[package]]
@@ -1541,6 +1853,15 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "toml"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.1" version = "0.3.1"
@@ -1674,6 +1995,12 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
[[package]]
name = "ucd-trie"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
[[package]] [[package]]
name = "unicode-bidi" name = "unicode-bidi"
version = "0.3.7" version = "0.3.7"
@@ -1729,6 +2056,15 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wait-timeout"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "want" name = "want"
version = "0.3.0" version = "0.3.0"
@@ -1852,6 +2188,15 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]] [[package]]
name = "zstd" name = "zstd"
version = "0.9.2+zstd.1.5.1" version = "0.9.2+zstd.1.5.1"

View File

@@ -22,7 +22,6 @@ 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" mktemp = "0.4.0"
configparser = "3.0.0" configparser = "3.0.0"
dotenv = "0.15.0"
listenfd = "0.3.0" listenfd = "0.3.0"
tracing = { version = "0.1.0", features = ["log"] } tracing = { version = "0.1.0", features = ["log"] }
tracing-subscriber = { version = "0.3.0", features = ["std", "env-filter", "fmt", "json"] } tracing-subscriber = { version = "0.3.0", features = ["std", "env-filter", "fmt", "json"] }
@@ -34,7 +33,9 @@ tracing-bunyan-formatter = "0.3.0"
thiserror = "1.0" thiserror = "1.0"
anyhow = "1.0" anyhow = "1.0"
http = "0.2.0" http = "0.2.0"
config = "0.12.0"
[dev-dependencies] [dev-dependencies]
proptest = "1.0.0"
reqwest = { version = "0.11.0", features = ["json"] } reqwest = { version = "0.11.0", features = ["json"] }
rstest = "0.12.0" rstest = "0.12.0"

7
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
config/test.toml Normal file
View File

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

42
src/configuration.rs Normal file
View File

@@ -0,0 +1,42 @@
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 = Config::builder()
.add_source(File::with_name("config/default"))
.add_source(File::with_name("config/local").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

@@ -23,12 +23,8 @@ impl std::fmt::Debug for ContextswitchError {
#[derive(thiserror::Error)] #[derive(thiserror::Error)]
pub enum ContextswitchError { pub enum ContextswitchError {
#[error("Invalid Contextswitch data: {data}")] #[error("Invalid Contextswitch data")]
InvalidDataError { InvalidDataError(#[from] serde_json::Error),
#[source]
source: serde_json::Error,
data: String,
},
#[error(transparent)] #[error(transparent)]
UnexpectedError(#[from] anyhow::Error), UnexpectedError(#[from] anyhow::Error),
} }
@@ -48,5 +44,13 @@ pub async fn add_task(add_args: Vec<&str>) -> Result<Task, ContextswitchError> {
let taskwarrior_task = taskwarrior::add_task(add_args) let taskwarrior_task = taskwarrior::add_task(add_args)
.await .await
.map_err(|e| ContextswitchError::UnexpectedError(e.into()))?; .map_err(|e| ContextswitchError::UnexpectedError(e.into()))?;
Ok((&taskwarrior_task).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

@@ -1,3 +1,4 @@
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;
@@ -14,6 +15,125 @@ use tokio::sync::Mutex;
use tracing::{debug, warn}; use tracing::{debug, warn};
use uuid::Uuid; 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)] #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
pub struct TaskwarriorTaskLocalId(pub u64); pub struct TaskwarriorTaskLocalId(pub u64);
@@ -32,12 +152,18 @@ impl fmt::Display for TaskwarriorTaskId {
} }
} }
impl From<&TaskwarriorTaskId> for TaskId { impl From<TaskwarriorTaskId> for TaskId {
fn from(task: &TaskwarriorTaskId) -> Self { fn from(task: TaskwarriorTaskId) -> Self {
TaskId(task.0) TaskId(task.0)
} }
} }
impl From<TaskId> for TaskwarriorTaskId {
fn from(task: TaskId) -> Self {
TaskwarriorTaskId(task.0)
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)] #[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct TaskwarriorTask { pub struct TaskwarriorTask {
pub uuid: TaskwarriorTaskId, pub uuid: TaskwarriorTaskId,
@@ -74,7 +200,7 @@ pub struct TaskwarriorTask {
)] )]
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")]
pub parent: Option<Uuid>, pub parent: Option<TaskwarriorTaskId>,
#[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")]
@@ -87,6 +213,12 @@ pub struct TaskwarriorTask {
pub contextswitch: Option<String>, pub contextswitch: Option<String>,
} }
impl From<TaskwarriorTask> for Task {
fn from(task: TaskwarriorTask) -> Self {
(&task).into()
}
}
impl From<&TaskwarriorTask> for Task { impl From<&TaskwarriorTask> for Task {
fn from(task: &TaskwarriorTask) -> Self { fn from(task: &TaskwarriorTask) -> Self {
let cs_data = let cs_data =
@@ -104,7 +236,7 @@ impl From<&TaskwarriorTask> for Task {
}); });
Task { Task {
id: (&task.uuid).into(), id: task.uuid.clone().into(),
entry: task.entry, entry: task.entry,
modified: task.modified, modified: task.modified,
status: task.status, status: task.status,
@@ -114,7 +246,7 @@ impl From<&TaskwarriorTask> for Task {
start: task.start, start: task.start,
end: task.end, end: task.end,
wait: task.wait, wait: task.wait,
parent: task.parent, parent: task.parent.clone().map(|id| id.into()),
project: task.project.clone(), project: task.project.clone(),
priority: task.priority, priority: task.priority,
recur: task.recur, recur: task.recur,
@@ -124,6 +256,108 @@ impl From<&TaskwarriorTask> for Task {
} }
} }
// 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)] #[derive(thiserror::Error, Debug)]
pub enum TaskwarriorError { pub enum TaskwarriorError {
#[error("Error while executing Taskwarrior")] #[error("Error while executing Taskwarrior")]
@@ -138,6 +372,7 @@ pub enum TaskwarriorError {
UnexpectedError(#[from] anyhow::Error), UnexpectedError(#[from] anyhow::Error),
} }
// Taskwarrior config functions
fn write_default_config(data_location: &str) -> String { fn write_default_config(data_location: &str) -> String {
let mut taskrc = Ini::new(); let mut taskrc = Ini::new();
taskrc.setstr("default", "data.location", Some(data_location)); taskrc.setstr("default", "data.location", Some(data_location));
@@ -156,8 +391,8 @@ fn write_default_config(data_location: &str) -> String {
taskrc_location.into() taskrc_location.into()
} }
pub fn load_config(task_data_location: Option<&str>) -> String { pub fn load_config(settings: &TaskwarriorSettings) -> String {
if let Ok(taskrc_location) = env::var("TASKRC") { if let Some(taskrc_location) = &settings.taskrc {
let mut taskrc = Ini::new(); let mut taskrc = Ini::new();
taskrc taskrc
.load(&taskrc_location) .load(&taskrc_location)
@@ -168,6 +403,8 @@ pub fn load_config(task_data_location: Option<&str>) -> String {
taskrc_location taskrc_location
) )
}); });
env::set_var("TASKRC", &taskrc_location);
debug!( debug!(
"Extracted data location `{}` from existing taskrc `{}`", "Extracted data location `{}` from existing taskrc `{}`",
data_location, taskrc_location data_location, taskrc_location
@@ -175,12 +412,11 @@ pub fn load_config(task_data_location: Option<&str>) -> String {
data_location data_location
} else { } else {
let data_location = task_data_location let data_location = settings
.map(|s| s.to_string()) .data_location
.unwrap_or_else(|| { .as_ref()
env::var("TASK_DATA_LOCATION") .expect("Expecting taskwarrior.taskrc or taskwarrior.data_location setting to be set")
.expect("Expecting TASKRC or TASK_DATA_LOCATION environment variable value") .to_string();
});
let taskrc_location = write_default_config(&data_location); let taskrc_location = write_default_config(&data_location);
env::set_var("TASKRC", &taskrc_location); env::set_var("TASKRC", &taskrc_location);
@@ -190,73 +426,208 @@ pub fn load_config(task_data_location: Option<&str>) -> String {
} }
} }
#[tracing::instrument(level = "debug")] #[cfg(test)]
pub fn list_tasks(filters: Vec<&str>) -> Result<Vec<TaskwarriorTask>, TaskwarriorError> { mod tests {
let args = [filters, vec!["export"]].concat();
let export_output = Command::new("task")
.args(args)
.output()
.map_err(TaskwarriorError::ExecutionError)?;
let output = mod from_taskwarrior_task_to_contextswitch_task {
String::from_utf8(export_output.stdout).context("Failed to read Taskwarrior output")?; use super::super::*;
use chrono::TimeZone;
use contextswitch_types::Bookmark;
use http::uri::Uri;
use proptest::prelude::*;
let tasks: Vec<TaskwarriorTask> = serde_json::from_str(&output) #[test]
.map_err(|e| TaskwarriorError::OutputParsingError { source: e, output })?; 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_types::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_types::Priority::H),
recur: Some(contextswitch_types::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();
Ok(tasks) 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);
#[tracing::instrument(level = "debug")] assert_eq!(tw_task.status, cs_task.status);
pub fn get_task_by_local_id( assert_eq!(tw_task.description, cs_task.description);
id: &TaskwarriorTaskLocalId, assert_eq!(tw_task.urgency, cs_task.urgency);
) -> Result<Option<TaskwarriorTask>, TaskwarriorError> { assert_eq!(tw_task.due, cs_task.due);
let mut tasks: Vec<TaskwarriorTask> = list_tasks(vec![&id.to_string()])?; assert_eq!(tw_task.start, cs_task.start);
if tasks.len() > 1 { assert_eq!(tw_task.end, cs_task.end);
return Err(TaskwarriorError::UnexpectedError(anyhow!( assert_eq!(tw_task.wait, cs_task.wait);
"Found more than 1 task when searching for task with local ID {}", assert_eq!(
id tw_task.parent.map(|id| id.to_string()),
))); cs_task.parent.map(|id| id.to_string())
} );
assert_eq!(tw_task.project, cs_task.project);
Ok(tasks.pop()) assert_eq!(tw_task.priority, cs_task.priority);
} assert_eq!(tw_task.recur, cs_task.recur);
assert_eq!(tw_task.tags, cs_task.tags);
#[tracing::instrument(level = "debug")] assert_eq!(
pub async fn add_task(add_args: Vec<&str>) -> Result<TaskwarriorTask, TaskwarriorError> { Some(ContextswitchData {
lazy_static! { bookmarks: vec![Bookmark {
static ref RE: Regex = Regex::new(r"Created task (?P<id>\d+).").unwrap(); uri: "https://www.example.com/path".parse::<Uri>().unwrap(),
static ref LOCK: Mutex<u32> = Mutex::new(0); content: None
} }]
let _lock = LOCK.lock().await; }),
cs_task.contextswitch
let mut args = vec!["add"];
args.extend(add_args);
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(|| { proptest! {
TaskwarriorError::UnexpectedError(anyhow!( #[test]
"Newly created task with ID {} was not found", fn test_conversion_with_invalid_contextswitch_data_format(cs_data in ".*") {
task_id 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_types::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_types::{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_types::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_types::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
);
}
}
} }

View File

@@ -7,6 +7,7 @@ use tracing_actix_web::TracingLogger;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
pub mod configuration;
pub mod contextswitch; pub mod contextswitch;
pub mod observability; pub mod observability;
pub mod routes; pub mod routes;
@@ -30,6 +31,7 @@ pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
.route("/ping", web::get().to(routes::ping)) .route("/ping", web::get().to(routes::ping))
.route("/tasks", web::get().to(routes::list_tasks)) .route("/tasks", web::get().to(routes::list_tasks))
.route("/tasks", web::post().to(routes::add_task)) .route("/tasks", web::post().to(routes::add_task))
.route("/tasks/{task_id}", web::put().to(routes::update_task))
.route( .route(
"/tasks", "/tasks",
web::method(http::Method::OPTIONS).to(routes::option_task), web::method(http::Method::OPTIONS).to(routes::option_task),

View File

@@ -1,22 +1,19 @@
extern crate dotenv;
extern crate listenfd; extern crate listenfd;
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};
use dotenv::dotenv;
use std::env;
use std::net::TcpListener; use std::net::TcpListener;
#[tokio::main] #[tokio::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let subscriber = get_subscriber("info".into()); let settings = Settings::new().expect("Cannot load Contextswitch configuration");
let subscriber = get_subscriber(&settings.application.log_directive);
init_subscriber(subscriber); init_subscriber(subscriber);
dotenv().ok(); taskwarrior::load_config(&settings.taskwarrior);
let port = env::var("PORT").unwrap_or_else(|_| "8000".to_string()); let listener = TcpListener::bind(format!("0.0.0.0:{}", settings.application.port))
taskwarrior::load_config(None); .expect("Failed to bind port");
let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).expect("Failed to bind port");
run(listener)?.await run(listener)?.await
} }

View File

@@ -4,7 +4,7 @@ use tracing_log::LogTracer;
use tracing_subscriber::fmt::TestWriter; use tracing_subscriber::fmt::TestWriter;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter}; use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
pub fn get_subscriber(env_filter_str: String) -> impl Subscriber + Send + Sync { pub fn get_subscriber(env_filter_str: &str) -> impl Subscriber + Send + Sync {
let formatting_layer = BunyanFormattingLayer::new("contextswitch-api".into(), TestWriter::new); let formatting_layer = BunyanFormattingLayer::new("contextswitch-api".into(), TestWriter::new);
let env_filter = let env_filter =

View File

@@ -1,7 +1,7 @@
use crate::contextswitch; use crate::contextswitch;
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}; use contextswitch_types::{NewTask, Task, TaskId};
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -37,17 +37,33 @@ pub async fn list_tasks(
.body(serde_json::to_string(&tasks).context("Cannot serialize Contextswitch task")?)) .body(serde_json::to_string(&tasks).context("Cannot serialize Contextswitch task")?))
} }
#[tracing::instrument(level = "debug", skip_all, fields(definition = %task.definition))] #[tracing::instrument(level = "debug", skip_all, fields(definition = %new_task.definition))]
pub async fn add_task( pub async fn add_task(
task: web::Json<NewTask>, new_task: web::Json<NewTask>,
) -> Result<HttpResponse, contextswitch::ContextswitchError> { ) -> Result<HttpResponse, contextswitch::ContextswitchError> {
let task: Task = contextswitch::add_task(task.definition.split(' ').collect()).await?; let task: Task = contextswitch::add_task(new_task.definition.split(' ').collect()).await?;
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(serde_json::to_string(&task).context("Cannot serialize Contextswitch task")?)) .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, contextswitch::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 = contextswitch::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")] #[tracing::instrument(level = "debug")]
pub fn option_task() -> HttpResponse { pub fn option_task() -> HttpResponse {
HttpResponse::Ok().finish() HttpResponse::Ok().finish()

View File

@@ -1,6 +1,5 @@
pub mod test_helper; use crate::helpers::app_address;
use rstest::*; use rstest::*;
use test_helper::app_address;
#[rstest] #[rstest]
#[tokio::test] #[tokio::test]

View File

@@ -1,14 +1,14 @@
use contextswitch_api::configuration::Settings;
use contextswitch_api::contextswitch::taskwarrior; use contextswitch_api::contextswitch::taskwarrior;
use contextswitch_api::observability::{get_subscriber, init_subscriber}; use contextswitch_api::observability::{get_subscriber, init_subscriber};
use mktemp::Temp; use mktemp::Temp;
use rstest::*; use rstest::*;
use std::fs;
use std::net::TcpListener; use std::net::TcpListener;
use tracing::info; use tracing::info;
fn setup_tracing() { fn setup_tracing(settings: &Settings) {
info!("Setting up tracing"); info!("Setting up tracing");
let subscriber = get_subscriber("debug".to_string()); let subscriber = get_subscriber(&settings.application.log_directive);
init_subscriber(subscriber); init_subscriber(subscriber);
} }
@@ -22,23 +22,22 @@ fn setup_server() -> String {
format!("http://127.0.0.1:{}", port) format!("http://127.0.0.1:{}", port)
} }
fn setup_taskwarrior() -> String { fn setup_taskwarrior(mut settings: Settings) -> String {
info!("Setting up TW"); info!("Setting up Taskwarrior");
let tmp_dir = Temp::new_dir().unwrap(); let tmp_dir = Temp::new_dir().unwrap();
let task_data_location = taskwarrior::load_config(tmp_dir.to_str()); settings.taskwarrior.data_location = tmp_dir.to_str().map(String::from);
let task_data_location = taskwarrior::load_config(&settings.taskwarrior);
tmp_dir.release(); tmp_dir.release();
task_data_location task_data_location
} }
pub fn clear_tasks(task_data_location: String) {
fs::remove_dir_all(task_data_location).unwrap();
}
#[fixture] #[fixture]
#[once] #[once]
pub fn app_address() -> String { pub fn app_address() -> String {
setup_tracing(); let settings = Settings::new_from_file(Some("config/test".to_string()))
setup_taskwarrior(); .expect("Cannot load test configuration");
setup_tracing(&settings);
setup_taskwarrior(settings);
setup_server() setup_server()
} }

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

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

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

@@ -0,0 +1,181 @@
use crate::helpers::app_address;
use contextswitch_api::contextswitch;
use contextswitch_types::{Bookmark, ContextswitchData, NewTask, Task};
use http::uri::Uri;
use rstest::*;
mod list_tasks {
use super::*;
#[rstest]
#[tokio::test]
async fn list_tasks(app_address: &str) {
let task = contextswitch::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_contextswitch_data(app_address: &str) {
let task = contextswitch::add_task(vec![
"test",
"list_tasks_with_unknown_contextswitch_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_contextswitch_data"
);
assert!(tasks[0].contextswitch.is_none());
}
#[rstest]
#[tokio::test]
async fn list_tasks_with_invalid_contextswitch_data(app_address: &str) {
let task = contextswitch::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 = contextswitch::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
}

View File

@@ -1,128 +0,0 @@
pub mod test_helper;
use contextswitch_api::contextswitch;
use contextswitch_types::{Bookmark, ContextswitchData, NewTask, Task, TaskId};
use http::uri::Uri;
use rstest::*;
use test_helper::app_address;
use uuid::Uuid;
#[rstest]
#[tokio::test]
async fn list_tasks(app_address: &str) {
let task = contextswitch::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_contextswitch_data(app_address: &str) {
let task = contextswitch::add_task(vec![
"test",
"list_tasks_with_unknown_contextswitch_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_contextswitch_data"
);
assert!(tasks[0].contextswitch.is_none());
}
#[rstest]
#[tokio::test]
async fn list_tasks_with_invalid_contextswitch_data(app_address: &str) {
let task = contextswitch::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());
}
#[rstest]
#[tokio::test]
async fn add_task(app_address: &str) {
let response: serde_json::Value = 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");
let new_task_id = TaskId(Uuid::parse_str(response["id"].as_str().unwrap()).unwrap());
let tasks = contextswitch::list_tasks(vec![&new_task_id.to_string()]).unwrap();
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].id, new_task_id);
assert_eq!(tasks[0].description, "test add_task");
assert_eq!(
tasks[0].contextswitch.as_ref().unwrap(),
&ContextswitchData {
bookmarks: vec![Bookmark {
uri: "https://example.com/path?filter=1".parse::<Uri>().unwrap(),
content: None
}]
}
);
}