use crate::query::{CollectData, ResponseData, Variables};
use anyhow::{Context, Result};
use graphql_client::{GraphQLQuery, Response};
use reqwest::{header, Client};
mod query;
#[cfg(test)]
mod test;
const TW_LOG: &str = "timegraph";
pub struct TimegraphData {
pub collection: String,
pub task_id: u64,
pub cycle: u64,
pub target_block_number: u64,
pub timechain_block_number: u64,
pub signature: [u8; 64],
pub data: Vec<String>,
}
pub struct Timegraph {
client: Client,
url: String,
ssk: String,
}
impl Timegraph {
pub fn new() -> Result<Self> {
dotenv::dotenv().ok();
let url = std::env::var("TIMEGRAPH_GRAPHQL_URL")
.context("Unable to get timegraph graphql url")?;
let ssk = std::env::var("SSK").context("Unable to get timegraph ssk")?;
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 i64,
task_counter: data.cycle as i64,
block: data.target_block_number as i64,
cycle: data.timechain_block_number as i64,
tss: hex::encode(data.signature),
data: data.data,
};
let request = CollectData::build_query(variables);
let response = self
.client
.post(&self.url)
.json(&request)
.header(header::AUTHORIZATION, &self.ssk)
.send()
.await
.map_err(|e| anyhow::anyhow!("error post to timegraph {}", e))?;
let json = response
.json::<Response<ResponseData>>()
.await
.context("Failed to parse timegraph response")?;
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(())
}
}