jsonrpc.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. use async_trait::async_trait;
  2. use log::error;
  3. use serde_json::{json, Value};
  4. use darkfi::{
  5. rpc::{
  6. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  7. server::RequestHandler,
  8. },
  9. Error,
  10. };
  11. use crate::Patch;
  12. pub struct JsonRpcInterface {
  13. sender: async_channel::Sender<(String, bool, Vec<String>)>,
  14. receiver: async_channel::Receiver<Vec<Vec<Patch>>>,
  15. }
  16. #[async_trait]
  17. impl RequestHandler for JsonRpcInterface {
  18. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  19. if !req.params.is_array() {
  20. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  21. }
  22. let params = req.params.as_array().unwrap();
  23. let rep = match req.method.as_str() {
  24. Some("update") => self.update(req.id, params).await,
  25. Some("restore") => self.restore(req.id, params).await,
  26. Some("log") => self.log(req.id, params).await,
  27. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  28. };
  29. rep
  30. }
  31. }
  32. fn patch_to_tuple(p: &Patch, colorize: bool) -> (String, String, String) {
  33. (p.path.to_owned(), p.workspace.to_owned(), if colorize { p.colorize() } else { p.to_string() })
  34. }
  35. fn printable_patches(
  36. patches: Vec<Vec<Patch>>,
  37. colorize: bool,
  38. ) -> Vec<Vec<(String, String, String)>> {
  39. let mut response = vec![];
  40. for ps in patches {
  41. response.push(ps.iter().map(|p| patch_to_tuple(p, colorize)).collect())
  42. }
  43. response
  44. }
  45. impl JsonRpcInterface {
  46. pub fn new(
  47. sender: async_channel::Sender<(String, bool, Vec<String>)>,
  48. receiver: async_channel::Receiver<Vec<Vec<Patch>>>,
  49. ) -> Self {
  50. Self { sender, receiver }
  51. }
  52. // RPCAPI:
  53. // Update files
  54. // --> {"jsonrpc": "2.0", "method": "update", "params": [], "id": 1}
  55. // <-- {"jsonrpc": "2.0", "result": [[(String, String)]], "id": 1}
  56. async fn update(&self, id: Value, params: &[Value]) -> JsonResult {
  57. let dry = params[0].as_bool().unwrap();
  58. let files: Vec<String> =
  59. params[1].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
  60. let res = self.sender.send(("update".into(), dry, files)).await.map_err(Error::from);
  61. if let Err(e) = res {
  62. error!("Failed to update: {}", e);
  63. return JsonError::new(ErrorCode::InternalError, None, id).into()
  64. }
  65. let response = self.receiver.recv().await.unwrap();
  66. let response = printable_patches(response, true);
  67. JsonResponse::new(json!(response), id).into()
  68. }
  69. // RPCAPI:
  70. // Undo the local changes
  71. // --> {"jsonrpc": "2.0", "method": "restore", "params": [dry, files], "id": 1}
  72. // <-- {"jsonrpc": "2.0", "result": [String, ..], "id": 1}
  73. async fn restore(&self, id: Value, params: &[Value]) -> JsonResult {
  74. let dry = params[0].as_bool().unwrap();
  75. let files: Vec<String> =
  76. params[1].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
  77. let res = self.sender.send(("restore".into(), dry, files)).await.map_err(Error::from);
  78. if let Err(e) = res {
  79. error!("Failed to restore: {}", e);
  80. return JsonError::new(ErrorCode::InternalError, None, id).into()
  81. }
  82. let response = self.receiver.recv().await.unwrap();
  83. let response = printable_patches(response, false);
  84. JsonResponse::new(json!(response), id).into()
  85. }
  86. // RPCAPI:
  87. // Show all patches
  88. // --> {"jsonrpc": "2.0", "method": "log", "params": [dry, files], "id": 1}
  89. // <-- {"jsonrpc": "2.0", "result": [[(String, String)]], "id": 1}
  90. async fn log(&self, id: Value, _params: &[Value]) -> JsonResult {
  91. JsonResponse::new(json!(true), id).into()
  92. }
  93. }