use crate::query::{CollectData, ResponseData, Variables};
use anyhow::{anyhow, Context, Result};
use graphql_client::{GraphQLQuery, Response};
use reqwest::header::AUTHORIZATION;
use reqwest::Client;
mod query;
const TW_LOG: &str = "timegraph";
#[derive(Clone, Debug)]
pub struct TimegraphData {
pub collection: String,
pub task_id: u64,
pub task_cycle: u64,
pub target_block_number: u64,
pub timechain_block_number: u64,
pub shard_id: u64,
pub signature: [u8; 64],
pub data: Vec<String>,
}
pub struct Timegraph {
client: Client,
url: String,
ssk: String,
}
impl Timegraph {
pub fn new(url: String, ssk: String) -> Result<Self> {
let client = Client::new();
Ok(Self { client, url, ssk })
}
pub async fn submit_data(&self, data: TimegraphData) -> Result<()> {
let variables = Variables {
collection: data.collection,
task_id: data.task_id as _,
task_cycle: data.task_cycle as _,
target_block: data.target_block_number as _,
timechain_block: data.timechain_block_number as _,
shard_id: data.shard_id as _,
signature: hex::encode(data.signature),
data: data.data,
};
let request = CollectData::build_query(variables);
let response = self
.client
.post(&self.url)
.json(&request)
.header(AUTHORIZATION, &self.ssk)
.send()
.await
.map_err(|e| anyhow!("error post to timegraph {e}"))?;
let json = response
.json::<Response<ResponseData>>()
.await
.map_err(|e| anyhow!("Failed to parse timegraph response {e}"))?;
let data = json.data.context(format!(
"timegraph migrate collect status fail: No reponse {:?}",
json.errors
))?;
log::info!(
target: TW_LOG,
"timegraph migrate collect status: {:?}",
data.collect.status
);
Ok(())
}
}