common.rs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 std::time::Duration;
  19. use smol::io::{AsyncReadExt, AsyncWriteExt};
  20. use super::jsonrpc::*;
  21. use crate::{error::RpcError, net::transport::PtStream, system::io_timeout, Result};
  22. pub(super) const INIT_BUF_SIZE: usize = 4096; // 4K
  23. pub(super) const MAX_BUF_SIZE: usize = 1024 * 8192; // 8M
  24. pub(super) const READ_TIMEOUT: Duration = Duration::from_secs(30);
  25. /// Internal read function that reads from the active stream into a buffer.
  26. pub(super) async fn read_from_stream(
  27. stream: &mut Box<dyn PtStream>,
  28. buf: &mut Vec<u8>,
  29. with_timeout: bool,
  30. ) -> Result<usize> {
  31. let mut total_read = 0;
  32. while total_read < MAX_BUF_SIZE {
  33. buf.resize(total_read + INIT_BUF_SIZE, 0);
  34. // Lame we have to duplicate this code, but it is what it is.
  35. if with_timeout {
  36. match io_timeout(READ_TIMEOUT, stream.read(&mut buf[total_read..])).await {
  37. Ok(0) if total_read == 0 => {
  38. return Err(
  39. RpcError::ConnectionClosed("Connection closed cleanly".to_string()).into()
  40. )
  41. }
  42. Ok(0) => break, // Finished reading
  43. Ok(n) => {
  44. total_read += n;
  45. if buf[total_read - 1] == b'\n' {
  46. break
  47. }
  48. }
  49. Err(e) => return Err(RpcError::IoError(e.kind()).into()),
  50. }
  51. } else {
  52. match stream.read(&mut buf[total_read..]).await {
  53. Ok(0) if total_read == 0 => {
  54. return Err(
  55. RpcError::ConnectionClosed("Connection closed cleanly".to_string()).into()
  56. )
  57. }
  58. Ok(0) => break, // Finished reading
  59. Ok(n) => {
  60. total_read += n;
  61. if buf[total_read - 1] == b'\n' {
  62. break
  63. }
  64. }
  65. Err(e) => return Err(RpcError::IoError(e.kind()).into()),
  66. }
  67. }
  68. }
  69. // Truncate buffer to actual data size
  70. buf.truncate(total_read);
  71. Ok(total_read)
  72. }
  73. /// Internal write function that writes a JSON-RPC object to the active stream.
  74. pub(super) async fn write_to_stream(
  75. stream: &mut Box<dyn PtStream>,
  76. object: &JsonResult,
  77. ) -> Result<()> {
  78. let object_str = match object {
  79. JsonResult::Notification(v) => v.stringify()?,
  80. JsonResult::Response(v) => v.stringify()?,
  81. JsonResult::Error(v) => v.stringify()?,
  82. JsonResult::Request(v) => v.stringify()?,
  83. _ => unreachable!(),
  84. };
  85. // As we're a line-based protocol, we append the '\n' char at
  86. // the end of the JSON string.
  87. for i in [object_str.as_bytes(), &[b'\n']] {
  88. if let Err(e) = stream.write_all(i).await {
  89. return Err(e.into())
  90. }
  91. }
  92. Ok(())
  93. }