AppFlowy-Cloud/tests/collab/util.rs

75 lines
1.9 KiB
Rust

use std::time::Duration;
use anyhow::Context;
use collab::core::origin::CollabOrigin;
use collab::entity::EncodedCollab;
use collab::preclude::Collab;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use redis::aio::ConnectionManager;
use tokio::time::sleep;
#[allow(dead_code)]
pub fn generate_random_bytes(size: usize) -> Vec<u8> {
let s: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(size)
.map(char::from)
.collect();
s.into_bytes()
}
#[allow(dead_code)]
pub fn generate_random_string(len: usize) -> String {
let rng = thread_rng();
rng
.sample_iter(&Alphanumeric)
.take(len)
.map(char::from)
.collect()
}
pub fn make_big_collab_doc_state(object_id: &str, key: &str, value: String) -> Vec<u8> {
let mut collab = Collab::new_with_origin(CollabOrigin::Empty, object_id, vec![], false);
collab.insert(key, value);
collab
.encode_collab_v1(|_| Ok::<(), anyhow::Error>(()))
.unwrap()
.doc_state
.to_vec()
}
pub fn test_encode_collab_v1(object_id: &str, key: &str, value: &str) -> EncodedCollab {
let mut collab = Collab::new_with_origin(CollabOrigin::Empty, object_id, vec![], false);
collab.insert(key, value);
collab
.encode_collab_v1(|_| Ok::<(), anyhow::Error>(()))
.unwrap()
}
pub async fn redis_client() -> redis::Client {
let redis_uri = "redis://localhost:6379";
redis::Client::open(redis_uri)
.context("failed to connect to redis")
.unwrap()
}
pub async fn redis_connection_manager() -> ConnectionManager {
let mut attempt = 0;
let max_attempts = 5;
let mut wait_time = 500;
loop {
match redis_client().await.get_connection_manager().await {
Ok(manager) => return manager,
Err(err) => {
if attempt >= max_attempts {
panic!("{:?}", err); // Exceeded maximum attempts, return the last error.
}
sleep(Duration::from_millis(wait_time)).await;
wait_time *= 2;
attempt += 1;
},
}
}
}