rpc.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi::{
  19. event_graph::model::Event,
  20. rpc::{client::RpcClient, jsonrpc::JsonRequest},
  21. util::encoding::base64,
  22. Result,
  23. };
  24. use darkfi_serial::{deserialize, serialize};
  25. use genevd::GenEvent;
  26. use log::debug;
  27. use tinyjson::JsonValue;
  28. pub struct Gen {
  29. pub rpc_client: RpcClient,
  30. }
  31. impl Gen {
  32. pub async fn close_connection(&self) {
  33. self.rpc_client.stop().await;
  34. }
  35. /// Add a new task.
  36. pub async fn add(&self, event: GenEvent) -> Result<()> {
  37. let event = JsonValue::String(base64::encode(&serialize(&event)));
  38. let req = JsonRequest::new("add", vec![event]);
  39. let rep = self.rpc_client.request(req).await?;
  40. debug!("Got reply: {:?}", rep);
  41. Ok(())
  42. }
  43. /// Get current open tasks ids.
  44. pub async fn list(&self) -> Result<Vec<Event<GenEvent>>> {
  45. let req = JsonRequest::new("list", vec![]);
  46. let rep = self.rpc_client.request(req).await?;
  47. debug!("reply: {:?}", rep);
  48. let bytes: Vec<u8> = base64::decode(rep.get::<String>().unwrap()).unwrap();
  49. let events: Vec<Event<GenEvent>> = deserialize(&bytes)?;
  50. Ok(events)
  51. }
  52. }