timegraph-client 0.1.10

Timegraph Client
Documentation
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 {
    /// collection hashId
    pub collection: String,
    /// task associated with data
    pub task_id: u64,
    /// for repeated task it's incremented on every run
    pub task_cycle: u64,
    /// target network block number
    pub target_block_number: u64,
    /// time-chain block number
    pub timechain_block_number: u64,
    /// Shard identifier
    pub shard_id: u64,
    /// TSS signature
    pub signature: [u8; 64],
    /// data to add into collection
    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 })
    }

    /// Add data into collection (user must have Collector role)
    pub async fn submit_data(&self, data: TimegraphData) -> Result<()> {
        let variables = Variables {
            feed: 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(())
    }
}