skybase 0.1.11

The Open-Source Backend & Developer Platform for the AT Protocol (Firebase for ATProto, powered by skyauth)
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Read-only AppView XRPC client for Bluesky/ATProto public queries.
//!
//! Provides typed access to common AppView reads (actor profiles, posts, follow
//! graphs, repository records) plus a generic cursor paginator and a raw JSON
//! `get`. Every method degrades gracefully — returning `None`/empty on transport
//! or decode failure — so callers can enrich opportunistically without coupling
//! their pipelines to AppView availability.

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::time::Duration;

use crate::error::SkybaseError;

/// Default public Bluesky AppView endpoint for read-only XRPC resolution.
pub const DEFAULT_APPVIEW_ENDPOINT: &str = "https://public.api.bsky.app";

/// Default public Bluesky CDN endpoint for image thumbnail retrieval.
pub const DEFAULT_CDN_ENDPOINT: &str = "https://cdn.bsky.app";

/// Default timeout for AppView requests.
pub const DEFAULT_APPVIEW_TIMEOUT_MS: u64 = 1500;

/// Maximum number of pages followed by [`AppViewClient::paginate`].
pub const DEFAULT_MAX_PAGES: usize = 100;

/// Profile metadata returned by `app.bsky.actor.getProfile`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActorProfile {
    /// Subject Decentralized Identifier (`did:plc:...` or `did:web:...`), if returned.
    #[serde(default)]
    pub did: Option<String>,
    /// Author handle (e.g. `"alice.bsky.social"`).
    pub handle: Option<String>,
    /// User-defined display name.
    #[serde(alias = "display_name")]
    pub display_name: Option<String>,
    /// Profile avatar image URL.
    #[serde(default)]
    pub avatar: Option<String>,
    /// Profile description / bio text.
    pub description: Option<String>,
    /// Count of accounts following this author.
    #[serde(alias = "followers_count")]
    pub followers_count: Option<u64>,
    /// Count of accounts followed by this author.
    #[serde(alias = "follows_count")]
    pub follows_count: Option<u64>,
    /// Account registration timestamp in ISO 8601 format.
    #[serde(alias = "created_at")]
    pub created_at: Option<String>,
}

/// Actor suggestion returned by `app.bsky.actor.searchActorsTypeahead`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct ActorSuggestion {
    /// Decentralized Identifier of the actor (`did:plc:...` or `did:web:...`).
    pub did: String,
    /// Handle of the actor (e.g. `"alice.bsky.social"`).
    pub handle: String,
    /// Optional user-defined display name.
    #[serde(default, rename = "displayName")]
    pub display_name: Option<String>,
    /// Optional profile avatar URL.
    #[serde(default)]
    pub avatar: Option<String>,
}

/// A resolved post view returned by `app.bsky.feed.getPosts`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub struct PostView {
    /// DID of the post author.
    pub author_did: String,
    /// Post text content, if present.
    pub text: String,
    /// Content identifier (CID) of the post record.
    pub cid: Option<String>,
}

/// Read-only AppView XRPC client.
#[derive(Debug, Clone)]
pub struct AppViewClient {
    appview_url: String,
    cdn_url: String,
    http_client: reqwest::Client,
}

impl Default for AppViewClient {
    fn default() -> Self {
        Self::new()
    }
}

impl AppViewClient {
    /// Creates a client targeting the default public AppView and CDN.
    #[must_use]
    pub fn new() -> Self {
        Self::with_endpoints(DEFAULT_APPVIEW_ENDPOINT, DEFAULT_CDN_ENDPOINT)
    }

    /// Creates a client with a custom AppView endpoint and the default CDN.
    #[must_use]
    pub fn with_endpoint(endpoint: impl Into<String>) -> Self {
        Self::with_endpoints(endpoint, DEFAULT_CDN_ENDPOINT)
    }

    /// Creates a client with custom AppView and CDN endpoints.
    #[must_use]
    pub fn with_endpoints(
        appview_endpoint: impl Into<String>,
        cdn_endpoint: impl Into<String>,
    ) -> Self {
        let client = reqwest::Client::builder()
            .use_rustls_tls()
            .timeout(Duration::from_millis(DEFAULT_APPVIEW_TIMEOUT_MS))
            .build()
            .unwrap_or_else(|_| {
                reqwest::Client::builder()
                    .timeout(Duration::from_millis(DEFAULT_APPVIEW_TIMEOUT_MS))
                    .build()
                    .unwrap_or_default()
            });

        Self {
            appview_url: appview_endpoint.into().trim_end_matches('/').to_string(),
            cdn_url: cdn_endpoint.into().trim_end_matches('/').to_string(),
            http_client: client,
        }
    }

    /// Returns the configured AppView base URL.
    #[must_use]
    pub fn appview_url(&self) -> &str {
        &self.appview_url
    }

    /// Returns the configured CDN base URL.
    #[must_use]
    pub fn cdn_url(&self) -> &str {
        &self.cdn_url
    }

    /// Returns a reference to the underlying HTTP client.
    #[must_use]
    pub fn http_client(&self) -> &reqwest::Client {
        &self.http_client
    }

    /// Performs a GET against an AppView XRPC endpoint and decodes the JSON response.
    ///
    /// # Errors
    /// Returns [`SkybaseError::Network`] on transport failure or
    /// [`SkybaseError::Serialization`] on a non-success status or decode failure.
    pub async fn get<T: DeserializeOwned>(
        &self,
        endpoint: &str,
        query: &[(&str, String)],
    ) -> Result<T, SkybaseError> {
        let url = format!("{}/xrpc/{endpoint}", self.appview_url);
        let resp = self.http_client.get(&url).query(query).send().await?;
        if !resp.status().is_success() {
            return Err(SkybaseError::Internal(format!(
                "AppView {endpoint} returned HTTP {}",
                resp.status()
            )));
        }
        let body = resp.json::<T>().await?;
        Ok(body)
    }

    /// Paginates an AppView XRPC endpoint, following cursors for at most
    /// [`DEFAULT_MAX_PAGES`] pages.
    ///
    /// `extract` projects each decoded response into a page of items plus the next
    /// cursor. Stops on a transport/decode error, an empty page, or a missing cursor.
    pub async fn paginate<T, I, F>(
        &self,
        endpoint: &str,
        base_query: &[(&str, String)],
        page_limit: u8,
        extract: F,
    ) -> Vec<I>
    where
        T: DeserializeOwned,
        F: Fn(T) -> (Vec<I>, Option<String>),
    {
        let page_limit = page_limit.clamp(1, 100).to_string();
        let mut items = Vec::new();
        let mut cursor: Option<String> = None;

        for _ in 0..DEFAULT_MAX_PAGES {
            let mut query: Vec<(&str, String)> = base_query.to_vec();
            query.push(("limit", page_limit.clone()));
            if let Some(ref c) = cursor {
                query.push(("cursor", c.clone()));
            }

            let body: T = match self.get(endpoint, &query).await {
                Ok(body) => body,
                Err(_) => break,
            };

            let (page, next_cursor) = extract(body);
            let count = page.len();
            items.extend(page);
            if count == 0
                || next_cursor.as_deref().is_none_or(str::is_empty)
                || next_cursor == cursor
            {
                break;
            }
            cursor = next_cursor;
        }

        items
    }

    /// Resolves an ATProto handle to a DID via `com.atproto.identity.resolveHandle`.
    ///
    /// Single-label handles without a domain (e.g. `"alice"` or `"@alice"`) automatically
    /// default to `.bsky.social` via [`skyauth::identity::normalize_user_handle`].
    /// Returns `None` on any failure. A DID input is returned unchanged.
    pub async fn resolve_handle(&self, handle: &str) -> Option<String> {
        let clean = handle.trim().trim_start_matches('@');
        if clean.starts_with("did:") {
            return Some(clean.to_string());
        }

        let normalized =
            skyauth::identity::normalize_user_handle(clean).unwrap_or_else(|_| clean.to_string());

        #[derive(Deserialize)]
        struct ResolveHandleResponse {
            did: String,
        }

        self.get::<ResolveHandleResponse>(
            "com.atproto.identity.resolveHandle",
            &[("handle", normalized)],
        )
        .await
        .ok()
        .map(|r| r.did)
    }

    /// Searches actor profiles by handle/name prefix via `app.bsky.actor.searchActorsTypeahead`.
    ///
    /// Returns an empty vector if `query` is empty or on any transport/decode failure.
    pub async fn search_actors_typeahead(&self, query: &str, limit: u8) -> Vec<ActorSuggestion> {
        let clean = query.trim().trim_start_matches('@').trim();
        if clean.is_empty() {
            return Vec::new();
        }
        let clamped_limit = limit.clamp(1, 25).to_string();

        #[derive(Deserialize)]
        struct TypeaheadResponse {
            #[serde(default)]
            actors: Vec<ActorSuggestion>,
        }

        self.get::<TypeaheadResponse>(
            "app.bsky.actor.searchActorsTypeahead",
            &[("q", clean.to_string()), ("limit", clamped_limit)],
        )
        .await
        .map(|r| r.actors)
        .unwrap_or_default()
    }

    /// Fetches an actor profile via `app.bsky.actor.getProfile`.
    ///
    /// Returns `None` on any failure.
    pub async fn fetch_profile(&self, did: &str) -> Option<ActorProfile> {
        #[derive(Deserialize)]
        struct RawProfile {
            did: Option<String>,
            handle: Option<String>,
            #[serde(rename = "displayName")]
            display_name: Option<String>,
            avatar: Option<String>,
            description: Option<String>,
            #[serde(rename = "followersCount")]
            followers_count: Option<u64>,
            #[serde(rename = "followsCount")]
            follows_count: Option<u64>,
            #[serde(rename = "createdAt")]
            created_at: Option<String>,
        }

        let raw: RawProfile = self
            .get("app.bsky.actor.getProfile", &[("actor", did.to_string())])
            .await
            .ok()?;
        Some(ActorProfile {
            did: raw.did,
            handle: raw.handle,
            display_name: raw.display_name,
            avatar: raw.avatar,
            description: raw.description,
            followers_count: raw.followers_count,
            follows_count: raw.follows_count,
            created_at: raw.created_at,
        })
    }

    /// Fetches a single post view via `app.bsky.feed.getPosts`.
    ///
    /// Returns `None` on any failure or an empty response.
    pub async fn fetch_post(&self, uri: &str) -> Option<PostView> {
        #[derive(Deserialize)]
        struct RawRecord {
            text: Option<String>,
        }
        #[derive(Deserialize)]
        struct RawAuthor {
            did: String,
        }
        #[derive(Deserialize)]
        struct RawPostView {
            author: RawAuthor,
            record: serde_json::Value,
            cid: Option<String>,
        }
        #[derive(Deserialize)]
        struct RawPostsResponse {
            posts: Vec<RawPostView>,
        }

        let raw: RawPostsResponse = self
            .get("app.bsky.feed.getPosts", &[("uris", uri.to_string())])
            .await
            .ok()?;
        let first = raw.posts.into_iter().next()?;
        let text = serde_json::from_value::<RawRecord>(first.record)
            .ok()
            .and_then(|r| r.text)
            .unwrap_or_default();
        Some(PostView {
            author_did: first.author.did,
            text,
            cid: first.cid,
        })
    }

    /// Fetches followed DIDs for an actor via `app.bsky.graph.getFollows`.
    pub async fn fetch_follows(&self, actor: &str, limit: u8) -> Vec<String> {
        #[derive(Deserialize)]
        struct FollowProfile {
            did: String,
        }
        #[derive(Deserialize)]
        struct GetFollowsResponse {
            follows: Vec<FollowProfile>,
            cursor: Option<String>,
        }

        self.paginate::<GetFollowsResponse, _, _>(
            "app.bsky.graph.getFollows",
            &[("actor", actor.to_string())],
            limit,
            |body| {
                (
                    body.follows.into_iter().map(|f| f.did).collect(),
                    body.cursor,
                )
            },
        )
        .await
    }

    /// Fetches incoming follower DIDs for an actor via `app.bsky.graph.getFollowers`.
    pub async fn fetch_followers(&self, actor: &str, limit: u8) -> Vec<String> {
        #[derive(Deserialize)]
        struct FollowerProfile {
            did: String,
        }
        #[derive(Deserialize)]
        struct GetFollowersResponse {
            followers: Vec<FollowerProfile>,
            cursor: Option<String>,
        }

        self.paginate::<GetFollowersResponse, _, _>(
            "app.bsky.graph.getFollowers",
            &[("actor", actor.to_string())],
            limit,
            |body| {
                (
                    body.followers.into_iter().map(|f| f.did).collect(),
                    body.cursor,
                )
            },
        )
        .await
    }

    /// Fetches follow records `(rkey, followed_did)` for an actor via
    /// `com.atproto.repo.listRecords` on `app.bsky.graph.follow`.
    pub async fn fetch_follow_records(&self, actor: &str, limit: u8) -> Vec<(String, String)> {
        #[derive(Deserialize)]
        struct FollowValue {
            subject: Option<String>,
        }
        #[derive(Deserialize)]
        struct RecordItem {
            uri: String,
            value: FollowValue,
        }
        #[derive(Deserialize)]
        struct ListRecordsResp {
            records: Vec<RecordItem>,
            cursor: Option<String>,
        }

        self.paginate::<ListRecordsResp, _, _>(
            "com.atproto.repo.listRecords",
            &[
                ("repo", actor.to_string()),
                ("collection", "app.bsky.graph.follow".to_string()),
            ],
            limit,
            |body| {
                let mut items = Vec::new();
                for rec in body.records {
                    if let Some(subject) = rec.value.subject {
                        let rkey = rec.uri.rsplit('/').next().unwrap_or_default().to_string();
                        if !rkey.is_empty() && !subject.is_empty() {
                            items.push((rkey, subject));
                        }
                    }
                }
                (items, body.cursor)
            },
        )
        .await
    }

    /// Builds a CDN thumbnail URL for an author DID and image CID.
    #[must_use]
    pub fn thumbnail_url(&self, author_did: &str, cid: &str) -> String {
        format!(
            "{}/img/feed_thumbnail/plain/{author_did}/{cid}@jpeg",
            self.cdn_url
        )
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_appview_client_methods_and_wiremock_queries() {
        let default_client = AppViewClient::default();
        assert_eq!(default_client.appview_url(), DEFAULT_APPVIEW_ENDPOINT);
        assert_eq!(default_client.cdn_url(), DEFAULT_CDN_ENDPOINT);
        let _ = default_client.http_client();
        assert_eq!(
            default_client.thumbnail_url("did:plc:alice", "bafy123"),
            "https://cdn.bsky.app/img/feed_thumbnail/plain/did:plc:alice/bafy123@jpeg"
        );

        let server = MockServer::start().await;
        let client = AppViewClient::with_endpoint(server.uri());

        // DID passthrough in resolve_handle
        assert_eq!(
            client.resolve_handle("@did:plc:alice123").await.as_deref(),
            Some("did:plc:alice123")
        );

        Mock::given(method("GET"))
            .and(path("/xrpc/com.atproto.identity.resolveHandle"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"did": "did:plc:alice123"})),
            )
            .mount(&server)
            .await;
        assert_eq!(
            client.resolve_handle("@alice").await.as_deref(),
            Some("did:plc:alice123")
        );

        // search_actors_typeahead
        assert!(client.search_actors_typeahead("  @  ", 10).await.is_empty());
        Mock::given(method("GET"))
            .and(path("/xrpc/app.bsky.actor.searchActorsTypeahead"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "actors": [{"did": "did:plc:alice123", "handle": "alice.bsky.social", "displayName": "Alice"}]
            })))
            .mount(&server)
            .await;
        let suggestions = client.search_actors_typeahead("alice", 5).await;
        assert_eq!(suggestions.len(), 1);
        assert_eq!(suggestions[0].did, "did:plc:alice123");

        // fetch_profile, fetch_post, fetch_follows, fetch_followers, fetch_follow_records
        Mock::given(method("GET"))
            .and(path("/xrpc/app.bsky.actor.getProfile"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "did": "did:plc:alice123",
                "handle": "alice.bsky.social",
                "displayName": "Alice",
                "followersCount": 100,
                "followsCount": 50
            })))
            .mount(&server)
            .await;
        let prof = client.fetch_profile("did:plc:alice123").await.unwrap();
        assert_eq!(prof.handle.as_deref(), Some("alice.bsky.social"));
        assert_eq!(prof.display_name.as_deref(), Some("Alice"));
        assert_eq!(prof.followers_count, Some(100));
        assert_eq!(prof.follows_count, Some(50));

        Mock::given(method("GET"))
            .and(path("/xrpc/app.bsky.feed.getPosts"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "posts": [{
                    "author": {"did": "did:plc:alice123"},
                    "record": {"text": "post body"},
                    "cid": "bafypost"
                }]
            })))
            .mount(&server)
            .await;
        let post = client
            .fetch_post("at://did:plc:alice123/app.bsky.feed.post/1")
            .await
            .unwrap();
        assert_eq!(post.text, "post body");

        Mock::given(method("GET"))
            .and(path("/xrpc/app.bsky.graph.getFollows"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "follows": [{"did": "did:plc:f1"}]
            })))
            .mount(&server)
            .await;
        assert_eq!(
            client.fetch_follows("did:plc:alice123", 10).await,
            vec!["did:plc:f1"]
        );

        Mock::given(method("GET"))
            .and(path("/xrpc/app.bsky.graph.getFollowers"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "followers": [{"did": "did:plc:fl1"}]
            })))
            .mount(&server)
            .await;
        assert_eq!(
            client.fetch_followers("did:plc:alice123", 10).await,
            vec!["did:plc:fl1"]
        );

        Mock::given(method("GET"))
            .and(path("/xrpc/com.atproto.repo.listRecords"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "records": [{
                    "uri": "at://did:plc:alice123/app.bsky.graph.follow/rkey1",
                    "value": {"subject": "did:plc:f1"}
                }]
            })))
            .mount(&server)
            .await;
        assert_eq!(
            client.fetch_follow_records("did:plc:alice123", 10).await,
            vec![("rkey1".to_string(), "did:plc:f1".to_string())]
        );
    }
}