forked from xai-org/x-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrato_client.rs
More file actions
233 lines (201 loc) · 6.75 KB
/
Copy pathstrato_client.rs
File metadata and controls
233 lines (201 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use anyhow::{anyhow, Context, Result};
use log::warn;
use reqwest::Client;
use serde::Deserialize;
use std::time::Duration;
use crate::metrics;
#[derive(Debug, Deserialize)]
struct StratoResponse<T> {
v: T,
}
fn deserialize_string_to_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, Deserialize};
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrInt {
String(String),
Int(i64),
}
match StringOrInt::deserialize(deserializer)? {
StringOrInt::String(s) => s.parse::<i64>().map_err(de::Error::custom),
StringOrInt::Int(i) => Ok(i),
}
}
#[derive(Debug, Deserialize)]
struct UserProfile {
name: String,
#[serde(rename = "screenName")]
screen_name: String,
}
#[derive(Debug, Deserialize)]
struct UserCounts {
#[serde(deserialize_with = "deserialize_string_to_i64")]
followers: i64,
#[serde(deserialize_with = "deserialize_string_to_i64")]
following: i64,
}
#[derive(Debug, Deserialize)]
struct UserData {
profile: UserProfile,
counts: UserCounts,
}
#[derive(Debug, Clone)]
pub struct UserMetadata {
pub user_id: i64,
pub name: String,
pub screen_name: String,
pub followers: i64,
pub following: i64,
}
pub struct StratoClient {
client: Client,
base_url: String,
}
impl Default for StratoClient {
fn default() -> Self {
let client = Client::builder()
.timeout(Duration::from_secs(30))
.pool_max_idle_per_host(10000)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(10))
.build()
.unwrap();
Self {
client,
base_url: "https://strato.twitter.biz".to_string(),
}
}
}
impl StratoClient {
pub fn new() -> Self {
Self::default()
}
pub async fn fetch_following_list(&self, user_id: i64, limit: i32) -> Result<Vec<i64>> {
let ans = self.fetch_following_list_internal(user_id, limit).await?;
ans.into_iter()
.map(|x| x.parse::<i64>().context("Failed to parse user ID"))
.collect()
}
async fn fetch_following_list_internal(&self, user_id: i64, limit: i32) -> Result<Vec<String>> {
let start = std::time::Instant::now();
let url = format!(
"{}/op/fetch/socialgraph/serviceV2/followingInternal.User",
self.base_url
);
let payload = serde_json::json!([user_id, {"limit": limit}]);
let response = self
.client
.post(&url)
.header("Content-Type", "application/json")
.body(serde_json::to_string(&payload)?)
.send()
.await
.context("Failed to fetch following list")?;
let duration = start.elapsed();
metrics::STRATO_REQUEST_DURATION
.with_label_values(&["fetch_following_list"])
.observe(duration.as_secs_f64());
if !response.status().is_success() {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_following_list", "error"])
.inc();
warn!(
"Following list fetch failed for {}: {}",
user_id,
response.status()
);
return Err(anyhow!(response.status().to_string()));
}
let text = response.text().await?;
if text == "{\"ttl\":-1}" {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_following_list", "not_found"])
.inc();
return Err(anyhow!("ttl=-1"));
}
match serde_json::from_str::<StratoResponse<Vec<String>>>(&text) {
Ok(result) => {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_following_list", "success"])
.inc();
Ok(result.v)
}
Err(e) => {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_following_list", "parse_error"])
.inc();
warn!(
"Failed to parse following list response for {}: {}. Response preview: {}",
user_id,
e,
&text[..text.len().min(300)]
);
Err(anyhow!(e))
}
}
}
pub async fn fetch_user_metadata(&self, user_id: i64) -> Result<Option<UserMetadata>> {
let start = std::time::Instant::now();
let url = format!("{}/op/fetch/gizmoduck/composite.User", self.base_url);
let payload = serde_json::json!([user_id, (serde_json::json!({}), ["profile", "counts"])]);
let response = self
.client
.post(&url)
.header("Content-Type", "application/json")
.body(serde_json::to_string(&payload)?)
.send()
.await
.context("Failed to fetch user metadata")?;
let duration = start.elapsed();
metrics::STRATO_REQUEST_DURATION
.with_label_values(&["fetch_user_metadata"])
.observe(duration.as_secs_f64());
if !response.status().is_success() {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_user_metadata", "error"])
.inc();
warn!(
"User metadata fetch failed for {}: {}",
user_id,
response.status()
);
return Ok(None);
}
let text = response.text().await?;
if text == "{\"ttl\":-1}" {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_user_metadata", "not_found"])
.inc();
return Ok(None);
}
match serde_json::from_str::<StratoResponse<UserData>>(&text) {
Ok(result) => {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_user_metadata", "success"])
.inc();
Ok(Some(UserMetadata {
user_id,
name: result.v.profile.name,
screen_name: result.v.profile.screen_name,
followers: result.v.counts.followers,
following: result.v.counts.following,
}))
}
Err(e) => {
metrics::STRATO_REQUESTS
.with_label_values(&["fetch_user_metadata", "parse_error"])
.inc();
warn!(
"Failed to parse user metadata response for {}: {}. Response preview: {}",
user_id,
e,
&text[..text.len().min(300)]
);
Ok(None)
}
}
}
}