xdk-rs 0.1.2

Async Rust client for the X (Twitter) API: OAuth1, OAuth2 PKCE, bearer tokens, media upload, streaming. xdk is X's SDK name; this is an independent project, not affiliated with X Corp.
Documentation
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Reads X's legacy post vocabulary under the names the vendored spec uses.
//!
//! X renamed its post vocabulary and the wire followed per endpoint, so a
//! response can spell a key `edit_history_tweet_ids` where the spec says
//! `edit_history_post_ids`. [`normalize`] runs inside `decode()`, the path
//! every typed response takes, before serde parses the body:
//!
//! ```text
//! decode(value)
//!   ├─ empty-body and errors-only guards
//!   ├─ normalize(&mut value)
//!   │    each object, each legacy key k in ADMITTED or EXCLUDED:
//!   │      current spelling present? ── yes ─► drop k, report (collision)
//!   │                                 └─ no ──► k admitted? ── yes ─► rename k, report
//!   │                                                        └─ no ──► leave k
//!   │    reports: one DEBUG event per legacy key per response, on VOCABULARY_TARGET
//!   └─ serde_json::from_value::<T>
//! ```
//!
//! `build.rs` derives both tables from the vendored spec. An excluded
//! pair's legacy spelling is a current name elsewhere in the spec, so a lone
//! one stays as sent; both spellings in one object can only be the rename,
//! which the build checks. Raw requests never reach this module.

use std::collections::BTreeSet;

use serde_json::{Map, Value};

/// Target of the events reporting each legacy key a typed response was read
/// under its current name: one `DEBUG` event per legacy key per response,
/// carrying `legacy` and `normalized` (the two spellings), `value_type` (the
/// JSON type of the value X sent under the legacy key), `value_len` (its
/// length, for a string, array, or object), and `collision` (whether the
/// object also carried the current spelling, so the legacy key was dropped).
/// No event carries a value, an id, or a request path.
///
/// A subscriber on this target learns which keys X still sends in its
/// legacy post vocabulary, the drift the typed responses otherwise hide; see
/// [what the crate publishes](crate#what-the-crate-publishes).
#[doc(alias(
    "cluster_tweets_results",
    "edit_history_tweet_ids",
    "most_recent_tweet_id",
    "note_tweet",
    "pinned_tweet_id",
    "previous_tweet_id",
    "total_tweet_count"
))]
pub const VOCABULARY_TARGET: &str = "xdk::vocabulary";

mod generated {
    include!(concat!(env!("OUT_DIR"), "/vocabulary.rs"));
}

/// Rewrites every object under `value` into the spec's vocabulary. An
/// admitted legacy key is renamed to its current spelling; a legacy key
/// whose current spelling the same object carries is dropped. Values move
/// with their keys and are never altered. Each legacy key is reported once
/// per call, however many objects carry it.
pub(crate) fn normalize(value: &mut Value) {
    walk(value, &mut BTreeSet::new());
}

/// Normalizes every object under `value`; `reported` holds the legacy keys
/// this response has already reported.
fn walk(value: &mut Value, reported: &mut BTreeSet<&'static str>) {
    match value {
        Value::Object(map) => {
            normalize_keys(map, reported);
            for child in map.values_mut() {
                walk(child, reported);
            }
        }
        Value::Array(items) => {
            for item in items {
                walk(item, reported);
            }
        }
        _ => {}
    }
}

/// Applies both tables to one object's own keys.
fn normalize_keys(map: &mut Map<String, Value>, reported: &mut BTreeSet<&'static str>) {
    let admitted = generated::ADMITTED.iter().map(|pair| (pair, true));
    let excluded = generated::EXCLUDED.iter().map(|pair| (pair, false));
    for (&(legacy, current), renamed) in admitted.chain(excluded) {
        let Some(sent) = map.get(legacy) else {
            continue;
        };
        let collision = map.contains_key(current);
        if !collision && !renamed {
            continue;
        }
        if reported.insert(legacy) {
            report(legacy, current, sent, collision);
        }
        let moved = map.remove(legacy);
        if !collision && let Some(value) = moved {
            map.insert(current.to_owned(), value);
        }
    }
}

/// Emits one event on [`VOCABULARY_TARGET`]. Every field is a schema
/// identifier: the spellings come from the spec-derived tables, and the
/// value X sent contributes only its JSON type and length.
fn report(legacy: &'static str, normalized: &'static str, sent: &Value, collision: bool) {
    let (value_type, value_len) = shape(sent);
    tracing::debug!(
        target: VOCABULARY_TARGET,
        legacy,
        normalized,
        value_type,
        value_len,
        collision
    );
}

/// The JSON type name of `value`, and its length for a string (in
/// characters), an array, or an object.
fn shape(value: &Value) -> (&'static str, Option<usize>) {
    match value {
        Value::Null => ("null", None),
        Value::Bool(_) => ("boolean", None),
        Value::Number(_) => ("number", None),
        Value::String(text) => ("string", Some(text.chars().count())),
        Value::Array(items) => ("array", Some(items.len())),
        Value::Object(map) => ("object", Some(map.len())),
    }
}

#[cfg(test)]
mod tests {
    use std::fmt;
    use std::sync::{Arc, Mutex};

    use serde_json::{Value, json};
    use tracing::field::{Field, Visit};
    use tracing::{Event, Metadata, Subscriber, span};

    use super::super::types::{
        BookmarkedResult, Post, RepostedResult, User, decode, deserialize_response,
    };
    use super::VOCABULARY_TARGET;

    #[test]
    fn edit_history_tweet_ids_reads_as_edit_history_post_ids_with_its_value_untouched() {
        for ids in [json!([""]), json!([]), json!(["2101712260468977783"])] {
            let post = deserialize_response::<Post>(json!({
                "data": {"id": "1", "text": "t", "edit_history_tweet_ids": ids}
            }))
            .expect("decodes");
            assert_eq!(post.data.extra.get("edit_history_post_ids"), Some(&ids));
            assert!(
                !post.data.extra.contains_key("edit_history_tweet_ids"),
                "extra: {:?}",
                post.data.extra
            );
        }
    }

    #[test]
    fn legacy_keys_are_renamed_at_every_depth() {
        let body = decode::<Value>(json!({
            "data": [
                {"id": "1", "public_metrics": {"retweet_count": 3}, "edit_history_tweet_ids": ["1"]},
                {"id": "2", "referenced_tweets": [{"id": "3", "type": "quoted"}]}
            ],
            "includes": {
                "tweets": [{"id": "3", "note_tweet": {"text": "long"}}],
                "users": [{"id": "9", "pinned_tweet_id": "3", "most_recent_tweet_id": "3"}]
            }
        }))
        .expect("decodes");

        assert_eq!(
            body,
            json!({
                "data": [
                    {"id": "1", "public_metrics": {"repost_count": 3}, "edit_history_post_ids": ["1"]},
                    {"id": "2", "referenced_posts": [{"id": "3", "type": "quoted"}]}
                ],
                "includes": {
                    "posts": [{"id": "3", "note_post": {"text": "long"}}],
                    "users": [{"id": "9", "pinned_post_id": "3", "most_recent_post_id": "3"}]
                }
            })
        );
    }

    #[test]
    fn keys_outside_the_table_pass_through_unchanged() {
        let body = json!({"data": {"retweeted": true, "tweet_mode": "extended", "future": [1]}});
        assert_eq!(decode::<Value>(body.clone()).expect("decodes"), body);

        let reposted = deserialize_response::<RepostedResult>(body).expect("decodes");
        assert!(reposted.data.retweeted);
        assert_eq!(reposted.data.extra["tweet_mode"], "extended");
    }

    #[test]
    fn a_lone_tweet_id_is_never_renamed() {
        let bookmarked = deserialize_response::<BookmarkedResult>(json!({
            "data": {"bookmarked": true, "tweet_id": "42"}
        }))
        .expect("decodes");
        assert_eq!(bookmarked.data.extra.get("tweet_id"), Some(&json!("42")));
        assert!(!bookmarked.data.extra.contains_key("post_id"));
    }

    #[test]
    fn both_spellings_of_a_declared_field_keep_the_current_value() {
        let post = deserialize_response::<Post>(json!({
            "data": {"id": "1", "text": "t", "public_metrics": {"retweet_count": 1, "repost_count": 2}}
        }))
        .expect("both spellings in one object decode");
        let metrics = post.data.public_metrics.expect("public_metrics present");
        assert_eq!(metrics.repost_count, 2);
        assert!(metrics.extra.is_empty(), "extra: {:?}", metrics.extra);
    }

    #[test]
    fn both_spellings_of_an_undeclared_key_keep_the_current_value() {
        let post = deserialize_response::<Post>(json!({
            "data": {
                "id": "1",
                "text": "t",
                "edit_history_tweet_ids": ["old"],
                "edit_history_post_ids": ["new"]
            }
        }))
        .expect("decodes");
        assert_eq!(
            post.data.extra.get("edit_history_post_ids"),
            Some(&json!(["new"]))
        );
        assert!(!post.data.extra.contains_key("edit_history_tweet_ids"));
    }

    #[test]
    fn both_spellings_of_an_excluded_pair_keep_the_current_value() {
        let user = deserialize_response::<User>(json!({
            "data": {
                "id": "1",
                "name": "n",
                "username": "u",
                "public_metrics": {"tweet_count": 5, "post_count": 7}
            }
        }))
        .expect("both spellings of an excluded pair decode");
        let metrics = user.data.public_metrics.expect("public_metrics present");
        assert_eq!(metrics.post_count, 7);
        assert!(metrics.extra.is_empty(), "extra: {:?}", metrics.extra);
    }

    #[test]
    fn a_lone_tweet_count_still_fills_post_count_through_its_alias() {
        let user = deserialize_response::<User>(json!({
            "data": {"id": "1", "name": "n", "username": "u", "public_metrics": {"tweet_count": 5}}
        }))
        .expect("decodes");
        assert_eq!(user.data.public_metrics.map(|m| m.post_count), Some(5));
    }

    // ── Events ──────────────────────────────────────────────────────

    /// One captured event: the fields its callsite declares, and the ones
    /// it recorded, with their values.
    #[derive(Debug, Clone, PartialEq)]
    struct Captured {
        declared: Vec<&'static str>,
        recorded: Vec<(&'static str, String)>,
    }

    /// Collects every event on the vocabulary target.
    #[derive(Clone, Default)]
    struct Capture(Arc<Mutex<Vec<Captured>>>);

    impl Subscriber for Capture {
        fn enabled(&self, metadata: &Metadata<'_>) -> bool {
            metadata.target() == VOCABULARY_TARGET
        }
        fn new_span(&self, _: &span::Attributes<'_>) -> span::Id {
            span::Id::from_u64(1)
        }
        fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
        fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
        fn event(&self, event: &Event<'_>) {
            let mut recorded = Recorded::default();
            event.record(&mut recorded);
            let declared = event.metadata().fields().iter().map(|f| f.name()).collect();
            self.0.lock().expect("capture lock").push(Captured {
                declared,
                recorded: recorded.0,
            });
        }
        fn enter(&self, _: &span::Id) {}
        fn exit(&self, _: &span::Id) {}
    }

    #[derive(Default)]
    struct Recorded(Vec<(&'static str, String)>);

    impl Visit for Recorded {
        fn record_str(&mut self, field: &Field, value: &str) {
            self.0.push((field.name(), value.to_string()));
        }
        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
            self.0.push((field.name(), format!("{value:?}")));
        }
    }

    /// Decodes `body` under a capturing subscriber and returns its events.
    fn events(body: Value) -> Vec<Captured> {
        let capture = Capture::default();
        tracing::subscriber::with_default(capture.clone(), || {
            decode::<Value>(body).expect("decodes");
        });
        capture.0.lock().expect("capture lock").clone()
    }

    const FIVE: [&str; 5] = [
        "legacy",
        "normalized",
        "value_type",
        "value_len",
        "collision",
    ];

    fn recorded(fields: &[(&'static str, &str)]) -> Vec<(&'static str, String)> {
        fields
            .iter()
            .map(|(name, value)| (*name, (*value).to_string()))
            .collect()
    }

    #[test]
    fn a_renamed_key_reports_one_event_with_exactly_the_five_fields() {
        let events = events(json!({"data": {"id": "1", "edit_history_tweet_ids": [""]}}));

        assert_eq!(
            events,
            [Captured {
                declared: FIVE.to_vec(),
                recorded: recorded(&[
                    ("legacy", "edit_history_tweet_ids"),
                    ("normalized", "edit_history_post_ids"),
                    ("value_type", "array"),
                    ("value_len", "1"),
                    ("collision", "false"),
                ]),
            }]
        );
    }

    #[test]
    fn a_key_repeated_across_posts_reports_once_per_response() {
        let body = json!({"data": [
            {"id": "1", "edit_history_tweet_ids": ["1"]},
            {"id": "2", "edit_history_tweet_ids": ["2"]},
            {"id": "3", "edit_history_tweet_ids": ["3"]}
        ]});

        assert_eq!(events(body.clone()).len(), 1);
        assert_eq!(events(body).len(), 1, "a second response reports again");
    }

    #[test]
    fn a_collision_reports_one_event_marked_as_one() {
        let events = events(json!({
            "data": {"public_metrics": {"retweet_count": 1, "repost_count": 2}}
        }));

        let fields: Vec<_> = events.iter().map(|e| e.recorded.clone()).collect();
        assert_eq!(
            fields,
            [recorded(&[
                ("legacy", "retweet_count"),
                ("normalized", "repost_count"),
                ("value_type", "number"),
                ("collision", "true"),
            ])]
        );
    }

    #[test]
    fn an_excluded_pair_reports_its_collision_and_never_a_lone_legacy_key() {
        let collided = events(json!({
            "data": {"public_metrics": {"tweet_count": 5, "post_count": 7}}
        }));
        let fields: Vec<_> = collided.iter().map(|e| e.recorded.clone()).collect();
        assert_eq!(
            fields,
            [recorded(&[
                ("legacy", "tweet_count"),
                ("normalized", "post_count"),
                ("value_type", "number"),
                ("collision", "true"),
            ])]
        );

        assert_eq!(
            events(json!({"data": {"public_metrics": {"tweet_count": 5}, "tweet_id": "9"}})),
            []
        );
    }

    #[test]
    fn a_string_reports_its_length_in_characters() {
        let events = events(json!({"data": {"pinned_tweet_id": "ñ12"}}));
        let fields: Vec<_> = events.iter().map(|e| e.recorded.clone()).collect();
        assert_eq!(
            fields,
            [recorded(&[
                ("legacy", "pinned_tweet_id"),
                ("normalized", "pinned_post_id"),
                ("value_type", "string"),
                ("value_len", "3"),
                ("collision", "false"),
            ])]
        );
    }

    #[test]
    fn keys_outside_the_table_report_nothing() {
        assert_eq!(
            events(json!({"data": {"retweeted": true, "tweet_mode": "extended"}})),
            []
        );
    }
}