From 806ff114bab4398ad4ec43301fb4be2d27962fb4 Mon Sep 17 00:00:00 2001 From: alemi Date: Wed, 18 Oct 2023 00:37:08 +0200 Subject: [PATCH] feat: parse well-known, store parsed struct --- Cargo.toml | 1 + src/cache.rs | 47 ++++++++++++++++++++++++++++++----------------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index bc7216b..bd89731 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ async-recursion = "1.0.5" axum = "0.6.20" chrono = "0.4.31" clap = { version = "4.4.6", features = ["derive"] } +derive_more = "0.99.17" lazy_static = "1.4.0" reqwest = { version = "0.11.20", features = ["json"] } sea-orm = { version = "0.12.3", features = ["runtime-tokio-native-tls", "sqlx-sqlite", "sqlx-postgres"] } diff --git a/src/cache.rs b/src/cache.rs index bee5da6..3b41de4 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -1,8 +1,11 @@ -use std::{sync::Arc, collections::HashMap, time::Duration}; +use std::{sync::Arc, collections::HashMap}; use chrono::Utc; +use crate::nodeinfo::model::{NodeInfoOwned, Software, Services}; use tokio::sync::RwLock; +use crate::nodeinfo::fetcher::node_info; + lazy_static::lazy_static! { pub static ref CACHE : Arc = Arc::new(InstanceCache::default()); } @@ -11,33 +14,43 @@ const MAX_CACHE_AGE : i64 = 86400; #[derive(Default)] pub struct InstanceCache { - store: RwLock)>>, + store: RwLock>, } impl InstanceCache { - pub async fn instance_metadata(&self, domain: &str) -> reqwest::Result> { + pub async fn instance_metadata(&self, domain: &str) -> reqwest::Result { let now = Utc::now().timestamp(); if let Some((age, value)) = self.store.read().await.get(domain) { if now - age < MAX_CACHE_AGE { - return Ok(value.clone()); + return Ok(clone_node_info(value)); } } - let response = reqwest::Client::builder() - .timeout(Duration::from_secs(5)) - .build()? - .get(format!("https://{}/nodeinfo/2.0.json", domain)) - .send() - .await?; + let info = node_info(domain).await?; - let value = response - .json::() - .await - .ok(); + self.store.write().await.insert(domain.to_string(), (now, clone_node_info(&info))); - self.store.write().await.insert(domain.to_string(), (now, value.clone())); - - Ok(value) + Ok(info) + } +} + +fn clone_node_info(node: &NodeInfoOwned) -> NodeInfoOwned { + NodeInfoOwned { + version: node.version.clone(), + software: Software { + name: node.software.name.clone(), + version: node.software.version.clone(), + repository: node.software.repository.clone(), + homepage: node.software.homepage.clone(), + }, + protocols: node.protocols.clone(), + services: Services { + inbound: node.services.inbound.clone(), + outbound: node.services.outbound.clone(), + }, + open_registrations: node.open_registrations, + usage: node.usage.clone(), + metadata: node.metadata.clone(), } }