Skip to main content

skybase/
lib.rs

1//! # `skybase`
2//!
3//! **The Turn-Key Micro-AppView Engine & Developer Platform for the AT Protocol.**
4//!
5//! `skybase` brings Firebase-like developer ergonomics to the decentralized AT Protocol ecosystem.
6//! Rather than forcing developers to hand-roll custom firehose consumers, backfill pipelines, and
7//! database schemas, `skybase` provides a turn-key, single-binary Micro-AppView engine that ingests
8//! Bluesky Jetstream commits, indexes them into embedded SQLite WAL with JSON1 virtual columns and
9//! FTS5 full-text search, and serves real-time REST and WebSocket live queries down to clients.
10//!
11//! Powered by [`skyauth`], `skybase` supports three distinct operating topologies:
12//! - **Topology A (Client-Sovereign / Zero Custody)**: Client applications write directly to user PDSs;
13//!   `skybase` acts as a zero-custody read and indexing engine holding zero private credentials.
14//! - **Topology B (Daemon-Managed / Bots)**: Server-side daemons hold DPoP sessions with AES-256-GCM encryption at rest.
15//! - **Topology C (Token-Mediated Session Proxy)**: Mediates confidential OAuth sessions for static frontends
16//!   (GitHub Pages, Wisp, Tangled) to prevent 2-week session dropouts.
17
18#![forbid(unsafe_code)]
19#![deny(
20    clippy::all,
21    clippy::unwrap_used,
22    clippy::expect_used,
23    clippy::panic,
24    clippy::todo,
25    clippy::unimplemented,
26    missing_docs,
27    rust_2018_idioms
28)]
29
30pub mod appview;
31pub mod chat;
32pub mod error;
33#[cfg(feature = "storage")]
34pub mod index;
35pub mod ingest;
36pub mod lexicon;
37pub mod repo;
38pub use appview::{
39    ActorProfile, ActorSuggestion, AppViewClient, PostView, DEFAULT_APPVIEW_ENDPOINT,
40    DEFAULT_APPVIEW_TIMEOUT_MS, DEFAULT_CDN_ENDPOINT,
41};
42pub use chat::{
43    ChatClient, ChatMessageView, ConvoMember, ConvoView, DeletedMessageView, MessageSender,
44    MessageView, SendMessagePayload, DEFAULT_CHAT_ENDPOINT,
45};
46pub use error::{Result, SkybaseError};
47#[cfg(feature = "storage")]
48pub use index::{
49    parse_at_uri, BatchStats, BroadcastBus, ChangeNotification, QueryBuilder, QueryOp, RecordInput,
50    RecordRow, RecordStore, RecordStoreConfig, SortDirection, StoreOperation,
51    DEFAULT_BROADCAST_CAPACITY,
52};
53pub use ingest::{
54    build_subscription_url, build_subscription_url_full, normalize_indexed_at,
55    parse_frame_timestamp, parse_jetstream_commit, parse_jetstream_frame, resolve_resume_cursor,
56    run_jetstream_streamer, BackoffManager, CommitOperation, CursorTracker, JetstreamCommit,
57    JetstreamEvent, MockJetstreamServer, MockServerCommand, RawJetstreamCommit,
58    RawJetstreamMessage, StreamConfig, CURSOR_REWIND_OVERLAP_US, DEFAULT_JETSTREAM_ENDPOINT,
59    DEFAULT_PING_INTERVAL, DEFAULT_READ_TIMEOUT, INITIAL_BACKOFF, MAX_BACKOFF,
60    MAX_JETSTREAM_REPLAY_WINDOW_US,
61};
62#[cfg(feature = "storage")]
63pub use ingest::{
64    sync_commit_to_store, ConsumerStats, IngesterConfig, JetstreamConsumer, JetstreamConsumerHandle,
65};
66pub use lexicon::{
67    extract_link_facets, format_system_time_iso8601, format_unix_secs_iso8601, has_nsfw_self_label,
68    now_iso8601, ByteSlice, Embed, Facet, FacetFeature, FacetIndex, FollowRecord, ListBlockRecord,
69    ListItemRecord, ListRecordsResponse, ModListRecord, PostRecord, RecordEmbed,
70    RecordWithMediaEmbed, ReplyRef, RepoRecordItem, SelfLabel, SelfLabels, StrongRef,
71    NSFW_SELF_LABEL_VALUES,
72};
73pub use repo::{
74    decode_tid_timestamp_secs, decode_tid_timestamp_us, extract_did_for_collection,
75    extract_did_from_at_uri, format_at_uri, generate_tid, parse_at_post_uri, split_at_uri,
76    validate_rkey, CreateRecordRequest, CreateRecordResult, DeleteRecordRequest, PdsRepoClient,
77    PutRecordRequest, PutRecordResult, RecordView, TidGenerator, XrpcErrorResponse,
78    MAX_PLAUSIBLE_TID_EPOCH_SECS, MIN_PLAUSIBLE_TID_EPOCH_SECS,
79};
80pub use skyauth;
81pub use tokio_util::sync::CancellationToken;
82
83#[cfg(feature = "storage")]
84use std::path::Path;
85use std::path::PathBuf;
86use std::sync::Arc;
87
88/// Configuration options for initializing a [`Skybase`] engine instance.
89#[derive(Debug, Clone)]
90pub struct SkybaseConfig {
91    /// OAuth Client ID URI (e.g., `<https://app.example.com/oauth/client-metadata.json>`).
92    pub client_id: String,
93    /// OAuth callback redirect URI (e.g., `<https://app.example.com/oauth/callback>`).
94    pub redirect_uri: String,
95    /// Application display name presented during consent dialogs.
96    pub app_name: String,
97    /// Optional Jetstream WebSocket endpoint for real-time firehose subscription.
98    pub jetstream_endpoint: Option<String>,
99    /// Optional filesystem path to SQLite database. If set, opens a persistent WAL store.
100    pub storage_path: Option<PathBuf>,
101    /// Whether to open an isolated in-memory SQLite database upon initialization.
102    pub in_memory_store: bool,
103    /// Optional explicit configuration for the embedded record store.
104    #[cfg(feature = "storage")]
105    pub store_config: Option<RecordStoreConfig>,
106    /// Target collection NSIDs to filter for at the edge during Jetstream ingestion.
107    pub wanted_collections: Vec<String>,
108    /// Target repository DIDs to filter for at the edge during Jetstream ingestion.
109    pub wanted_dids: Vec<String>,
110}
111
112impl SkybaseConfig {
113    /// Creates a new [`SkybaseConfig`] with required OAuth parameters.
114    pub fn new(
115        client_id: impl Into<String>,
116        redirect_uri: impl Into<String>,
117        app_name: impl Into<String>,
118    ) -> Self {
119        Self {
120            client_id: client_id.into(),
121            redirect_uri: redirect_uri.into(),
122            app_name: app_name.into(),
123            jetstream_endpoint: None,
124            storage_path: None,
125            in_memory_store: false,
126            #[cfg(feature = "storage")]
127            store_config: None,
128            wanted_collections: Vec::new(),
129            wanted_dids: Vec::new(),
130        }
131    }
132
133    /// Sets a custom Jetstream WebSocket endpoint for event subscription.
134    pub fn with_jetstream_endpoint(mut self, endpoint: impl Into<String>) -> Self {
135        self.jetstream_endpoint = Some(endpoint.into());
136        self
137    }
138
139    /// Configures a persistent SQLite database file path.
140    pub fn with_storage_path(mut self, path: impl Into<PathBuf>) -> Self {
141        self.storage_path = Some(path.into());
142        self
143    }
144
145    /// Configures an isolated in-memory SQLite database.
146    pub fn with_in_memory_store(mut self) -> Self {
147        self.in_memory_store = true;
148        self
149    }
150
151    /// Sets an explicit [`RecordStoreConfig`].
152    #[cfg(feature = "storage")]
153    pub fn with_store_config(mut self, config: RecordStoreConfig) -> Self {
154        self.store_config = Some(config);
155        self
156    }
157
158    /// Appends a target collection NSID to filter for at the edge.
159    pub fn with_wanted_collection(mut self, collection: impl Into<String>) -> Self {
160        self.wanted_collections.push(collection.into());
161        self
162    }
163
164    /// Sets target collection NSIDs to filter for at the edge.
165    pub fn with_wanted_collections<I, S>(mut self, collections: I) -> Self
166    where
167        I: IntoIterator<Item = S>,
168        S: Into<String>,
169    {
170        self.wanted_collections = collections.into_iter().map(Into::into).collect();
171        self
172    }
173
174    /// Appends a target DID to filter for at the edge.
175    pub fn with_wanted_did(mut self, did: impl Into<String>) -> Self {
176        self.wanted_dids.push(did.into());
177        self
178    }
179
180    /// Sets target DIDs to filter for at the edge.
181    pub fn with_wanted_dids<I, S>(mut self, dids: I) -> Self
182    where
183        I: IntoIterator<Item = S>,
184        S: Into<String>,
185    {
186        self.wanted_dids = dids.into_iter().map(Into::into).collect();
187        self
188    }
189}
190
191/// Combined OAuth provider discovery and public profile preview for a user handle or DID.
192#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
193pub struct LoginIdentityPreview {
194    /// Resolved OAuth identity and provider endpoints (`did`, `handle`, `pds_host`, `auth_server_host`, etc.).
195    pub oauth: skyauth::client::OAuthLoginPreview,
196    /// Optional public profile metadata fetched from the AppView (`display_name`, `avatar`, etc.).
197    pub profile: Option<ActorProfile>,
198}
199
200/// The unified Skybase backend engine and client facade.
201#[derive(Clone)]
202pub struct Skybase {
203    config: Arc<SkybaseConfig>,
204    auth_client: Arc<skyauth::client::AtprotoOAuthClient>,
205    #[cfg(feature = "storage")]
206    store: Option<RecordStore>,
207}
208
209impl Skybase {
210    /// Initializes a new [`Skybase`] engine instance with the given configuration.
211    ///
212    /// If `storage_path`, `in_memory_store`, or `store_config` is configured, initializes
213    /// the embedded SQLite [`RecordStore`] with canonical WAL schemas and indexes.
214    ///
215    /// # Errors
216    /// Returns [`SkybaseError::Config`] if metadata is invalid, [`SkybaseError::Auth`] on OAuth
217    /// client failure, or [`SkybaseError::Storage`] if SQLite initialization fails.
218    pub fn new(config: SkybaseConfig) -> Result<Self> {
219        if config.client_id.trim().is_empty() {
220            return Err(SkybaseError::Config("client_id cannot be empty".into()));
221        }
222        if config.redirect_uri.trim().is_empty() {
223            return Err(SkybaseError::Config("redirect_uri cannot be empty".into()));
224        }
225
226        let metadata =
227            skyauth::client::OAuthClientMetadata::new(&config.client_id, &config.redirect_uri)
228                .with_client_name(&config.app_name);
229
230        let auth_client = skyauth::client::AtprotoOAuthClient::builder()
231            .client_metadata(metadata)
232            .build()
233            .map_err(SkybaseError::Auth)?;
234
235        #[cfg(feature = "storage")]
236        let store = if let Some(ref store_cfg) = config.store_config {
237            Some(RecordStore::with_config(store_cfg.clone())?)
238        } else if let Some(ref path) = config.storage_path {
239            Some(RecordStore::open(path)?)
240        } else if config.in_memory_store {
241            Some(RecordStore::open_in_memory()?)
242        } else {
243            None
244        };
245
246        Ok(Self {
247            config: Arc::new(config),
248            auth_client: Arc::new(auth_client),
249            #[cfg(feature = "storage")]
250            store,
251        })
252    }
253
254    /// Convenience constructor initializing [`Skybase`] with an in-memory SQLite store.
255    ///
256    /// # Errors
257    /// Returns [`SkybaseError::Config`] or [`SkybaseError::Auth`] if client metadata is invalid,
258    /// or [`SkybaseError::Storage`] if in-memory database initialization fails.
259    #[cfg(feature = "storage")]
260    pub fn in_memory(config: SkybaseConfig) -> Result<Self> {
261        Self::new(config.with_in_memory_store())
262    }
263
264    /// Attaches an existing [`RecordStore`] to this [`Skybase`] instance.
265    #[cfg(feature = "storage")]
266    #[must_use]
267    pub fn with_store(mut self, store: RecordStore) -> Self {
268        self.store = Some(store);
269        self
270    }
271
272    /// Opens or replaces the active persistent [`RecordStore`] at the specified path.
273    ///
274    /// # Errors
275    /// Returns [`SkybaseError::Storage`] if opening the database fails.
276    #[cfg(feature = "storage")]
277    pub fn open_store(&mut self, path: impl AsRef<Path>) -> Result<RecordStore> {
278        let store = RecordStore::open(path)?;
279        self.store = Some(store.clone());
280        Ok(store)
281    }
282
283    /// Opens or replaces the active [`RecordStore`] with an isolated in-memory database.
284    ///
285    /// # Errors
286    /// Returns [`SkybaseError::Storage`] if opening the in-memory database fails.
287    #[cfg(feature = "storage")]
288    pub fn open_in_memory_store(&mut self) -> Result<RecordStore> {
289        let store = RecordStore::open_in_memory()?;
290        self.store = Some(store.clone());
291        Ok(store)
292    }
293
294    /// Returns a reference to the active [`SkybaseConfig`].
295    #[must_use]
296    pub fn config(&self) -> &SkybaseConfig {
297        &self.config
298    }
299
300    /// Accesses the underlying [`skyauth::client::AtprotoOAuthClient`] identity and authentication engine.
301    #[must_use]
302    pub fn auth(&self) -> &skyauth::client::AtprotoOAuthClient {
303        &self.auth_client
304    }
305
306    /// Resolves a user handle or DID into a [`LoginIdentityPreview`] combining OAuth provider
307    /// discovery (`did`, `handle`, `pds_host`, `auth_server_host`) with public AppView profile
308    /// enrichment (`display_name`, `avatar`).
309    ///
310    /// # Errors
311    /// Returns [`SkybaseError::Auth`] if OAuth identity or endpoint discovery fails.
312    pub async fn preview_login(
313        &self,
314        appview: &AppViewClient,
315        handle_or_did: &str,
316    ) -> Result<LoginIdentityPreview> {
317        let oauth = self
318            .auth_client
319            .preview_login(handle_or_did)
320            .await
321            .map_err(SkybaseError::Auth)?;
322        let profile = appview.fetch_profile(&oauth.did).await;
323        Ok(LoginIdentityPreview { oauth, profile })
324    }
325
326    /// Returns a reference to the active [`RecordStore`], if initialized.
327    #[cfg(feature = "storage")]
328    #[must_use]
329    pub fn store(&self) -> Option<&RecordStore> {
330        self.store.as_ref()
331    }
332
333    /// Returns a reference to the active [`RecordStore`] or returns [`SkybaseError::Config`].
334    ///
335    /// # Errors
336    /// Returns [`SkybaseError::Config`] if no record store is attached.
337    #[cfg(feature = "storage")]
338    pub fn require_store(&self) -> Result<&RecordStore> {
339        self.store.as_ref().ok_or_else(|| {
340            SkybaseError::Config("RecordStore is not initialized on this Skybase instance".into())
341        })
342    }
343
344    /// Initiates a structured [`QueryBuilder`] scoped to the given collection NSID.
345    ///
346    /// # Errors
347    /// Returns [`SkybaseError::Config`] if no record store is attached.
348    #[cfg(feature = "storage")]
349    pub fn query(&self, collection: impl Into<String>) -> Result<QueryBuilder<'_>> {
350        Ok(self.require_store()?.query(collection))
351    }
352
353    /// Initiates a structured [`QueryBuilder`] scoped to the given collection NSID (alias for [`query`](Self::query)).
354    ///
355    /// # Errors
356    /// Returns [`SkybaseError::Config`] if no record store is attached.
357    #[cfg(feature = "storage")]
358    pub fn collection(&self, collection: impl Into<String>) -> Result<QueryBuilder<'_>> {
359        self.query(collection)
360    }
361
362    /// Subscribes to the live [`ChangeNotification`] broadcast stream.
363    ///
364    /// # Errors
365    /// Returns [`SkybaseError::Config`] if no record store is attached.
366    #[cfg(feature = "storage")]
367    pub fn subscribe(&self) -> Result<tokio::sync::broadcast::Receiver<ChangeNotification>> {
368        Ok(self.require_store()?.subscribe())
369    }
370
371    /// Builds a [`JetstreamConsumer`] using the configured `jetstream_endpoint` and `wanted_collections`.
372    ///
373    /// # Errors
374    /// Returns [`SkybaseError::Config`] if `jetstream_endpoint` or `RecordStore` is not configured.
375    #[cfg(feature = "storage")]
376    pub fn consumer(&self) -> Result<JetstreamConsumer> {
377        let endpoint = self.config.jetstream_endpoint.as_ref().ok_or_else(|| {
378            SkybaseError::Config(
379                "Cannot build JetstreamConsumer: 'jetstream_endpoint' is not configured".into(),
380            )
381        })?;
382
383        let mut config = IngesterConfig::new(endpoint);
384        if !self.config.wanted_collections.is_empty() {
385            config = config.with_collections(self.config.wanted_collections.clone());
386        }
387        if !self.config.wanted_dids.is_empty() {
388            config = config.with_dids(self.config.wanted_dids.clone());
389        }
390
391        self.consumer_with_config(config)
392    }
393
394    /// Builds a [`JetstreamConsumer`] with custom [`IngesterConfig`] bound to the internal [`RecordStore`].
395    ///
396    /// # Errors
397    /// Returns [`SkybaseError::Config`] if no record store is attached.
398    #[cfg(feature = "storage")]
399    pub fn consumer_with_config(&self, config: IngesterConfig) -> Result<JetstreamConsumer> {
400        let store = self.require_store()?.clone();
401        Ok(JetstreamConsumer::new(config, store))
402    }
403
404    /// Spawns the default [`JetstreamConsumer`] as a managed background task.
405    ///
406    /// # Errors
407    /// Returns [`SkybaseError::Config`] if `jetstream_endpoint` or `RecordStore` is not configured.
408    #[cfg(feature = "storage")]
409    pub fn start_consumer(
410        &self,
411        cancel: tokio_util::sync::CancellationToken,
412    ) -> Result<JetstreamConsumerHandle> {
413        let consumer = self.consumer()?;
414        Ok(consumer.start(cancel))
415    }
416
417    /// Spawns a [`JetstreamConsumer`] with custom configuration as a managed background task.
418    ///
419    /// # Errors
420    /// Returns [`SkybaseError::Config`] if no record store is attached.
421    #[cfg(feature = "storage")]
422    pub fn start_consumer_with_config(
423        &self,
424        config: IngesterConfig,
425        cancel: tokio_util::sync::CancellationToken,
426    ) -> Result<JetstreamConsumerHandle> {
427        let consumer = self.consumer_with_config(config)?;
428        Ok(consumer.start(cancel))
429    }
430
431    /// Creates a sovereign PDS repository client bound to the provided OAuth session.
432    ///
433    /// # Errors
434    /// Returns [`SkybaseError::Network`] if HTTP client initialization fails.
435    pub fn repo_client(
436        &self,
437        session: Arc<skyauth::session::OAuthSession>,
438    ) -> Result<PdsRepoClient> {
439        PdsRepoClient::new(session, Arc::clone(&self.auth_client))
440    }
441
442    /// Creates a sovereign PDS repository client from explicit credentials or mock endpoint tokens.
443    ///
444    /// Leverages the facade's internal OAuth client for DPoP proof generation and nonce caching.
445    ///
446    /// # Errors
447    /// Returns [`SkybaseError::Auth`] if session creation fails, or [`SkybaseError::Network`]
448    /// if HTTP client creation fails.
449    pub fn repo_client_from_credentials(
450        &self,
451        pds_endpoint: impl Into<String>,
452        repo_did: impl Into<String>,
453        access_token: impl Into<String>,
454    ) -> Result<PdsRepoClient> {
455        let endpoint = pds_endpoint.into();
456        let did = repo_did.into();
457        let token = access_token.into();
458
459        let session = skyauth::session::OAuthSession::new(
460            did,
461            token,
462            None,
463            "DPoP",
464            None,
465            None,
466            skyauth::dpop::DPoPKey::generate(),
467            Some(endpoint),
468            None,
469            None,
470        )
471        .map_err(SkybaseError::Auth)?;
472
473        PdsRepoClient::new(Arc::new(session), Arc::clone(&self.auth_client))
474    }
475}
476
477#[cfg(test)]
478#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
479mod tests {
480    use super::*;
481
482    #[test]
483    fn test_skybase_initialization() {
484        let config = SkybaseConfig::new(
485            "https://app.example.com/oauth/client-metadata.json",
486            "https://app.example.com/oauth/callback",
487            "Test App",
488        );
489
490        let skybase = Skybase::new(config).expect("Skybase should initialize successfully");
491        assert_eq!(skybase.config().app_name, "Test App");
492    }
493
494    #[test]
495    fn test_skybase_config_validation() {
496        let invalid_config = SkybaseConfig::new("", "https://app.example.com/callback", "App");
497        let result = Skybase::new(invalid_config);
498        assert!(matches!(result, Err(SkybaseError::Config(_))));
499    }
500
501    #[test]
502    fn test_skybase_repo_client_creation() {
503        let config = SkybaseConfig::new(
504            "https://app.example.com/oauth/client-metadata.json",
505            "https://app.example.com/oauth/callback",
506            "Test App",
507        );
508        let skybase = Skybase::new(config).expect("Skybase init failed");
509
510        let session = skyauth::session::OAuthSession::new(
511            "did:plc:alice",
512            "access_token",
513            None,
514            "DPoP",
515            None,
516            None,
517            skyauth::dpop::DPoPKey::generate(),
518            Some("https://pds.example.com".into()),
519            None,
520            None,
521        )
522        .expect("session creation failed");
523
524        let client = skybase.repo_client(Arc::new(session)).expect("repo_client");
525        assert_eq!(client.did(), "did:plc:alice");
526        assert_eq!(
527            client.pds_endpoint().expect("endpoint"),
528            "https://pds.example.com"
529        );
530    }
531
532    #[cfg(feature = "storage")]
533    #[test]
534    fn test_skybase_config_builders() {
535        let path = std::path::PathBuf::from("/tmp/skybase_test.db");
536        let store_cfg = RecordStoreConfig::in_memory();
537        let config = SkybaseConfig::new(
538            "https://app.example.com/oauth/client-metadata.json",
539            "https://app.example.com/oauth/callback",
540            "Builder Test App",
541        )
542        .with_jetstream_endpoint("wss://jetstream.example.com/subscribe")
543        .with_storage_path(&path)
544        .with_in_memory_store()
545        .with_store_config(store_cfg)
546        .with_wanted_collections(vec!["app.bsky.actor.profile", "app.bsky.feed.like"])
547        .with_wanted_collection("app.bsky.feed.post")
548        .with_wanted_dids(vec!["did:plc:bob", "did:plc:charlie"])
549        .with_wanted_did("did:plc:alice");
550
551        assert_eq!(
552            config.jetstream_endpoint.as_deref(),
553            Some("wss://jetstream.example.com/subscribe")
554        );
555        assert_eq!(config.storage_path.as_deref(), Some(path.as_path()));
556        assert!(config.in_memory_store);
557        assert!(config.store_config.is_some());
558        assert_eq!(config.wanted_collections.len(), 3);
559        assert_eq!(config.wanted_dids.len(), 3);
560    }
561
562    #[cfg(feature = "storage")]
563    #[test]
564    fn test_skybase_in_memory_and_store_delegation() {
565        let config = SkybaseConfig::new(
566            "https://app.example.com/oauth/client-metadata.json",
567            "https://app.example.com/oauth/callback",
568            "In Memory App",
569        );
570
571        let skybase = Skybase::in_memory(config).expect("in_memory init failed");
572        assert!(skybase.store().is_some());
573        assert!(skybase.require_store().is_ok());
574
575        // Test query and collection builder
576        let q1 = skybase.query("app.bsky.feed.post").expect("query failed");
577        let (sql1, _) = q1.build_sql().expect("sql build failed");
578        assert!(sql1.contains("WHERE collection = ?"));
579
580        let q2 = skybase
581            .collection("app.bsky.feed.post")
582            .expect("collection failed");
583        let (sql2, _) = q2.build_sql().expect("sql build failed");
584        assert_eq!(sql1, sql2);
585
586        // Test subscribe
587        let mut rx = skybase.subscribe().expect("subscribe failed");
588        let input = RecordInput::new(
589            "did:plc:alice",
590            "app.bsky.feed.post",
591            "post_facade_1",
592            "cid_1",
593            serde_json::json!({"text": "Hello facade"}),
594            1_000,
595        );
596        skybase
597            .require_store()
598            .unwrap()
599            .upsert_record(&input)
600            .expect("upsert failed");
601
602        let event = rx.try_recv().expect("broadcast event expected");
603        match event {
604            ChangeNotification::Upsert(row) => {
605                assert_eq!(row.uri, input.uri);
606                assert_eq!(row.record_json["text"], "Hello facade");
607            }
608            _ => panic!("Expected Upsert event"),
609        }
610    }
611
612    #[cfg(feature = "storage")]
613    #[test]
614    fn test_skybase_uninitialized_store_errors() {
615        let config = SkybaseConfig::new(
616            "https://app.example.com/oauth/client-metadata.json",
617            "https://app.example.com/oauth/callback",
618            "No Store App",
619        );
620        let skybase = Skybase::new(config).expect("init failed");
621        assert!(skybase.store().is_none());
622        assert!(matches!(
623            skybase.require_store(),
624            Err(SkybaseError::Config(_))
625        ));
626        assert!(matches!(skybase.query("col"), Err(SkybaseError::Config(_))));
627        assert!(matches!(
628            skybase.collection("col"),
629            Err(SkybaseError::Config(_))
630        ));
631        assert!(matches!(skybase.subscribe(), Err(SkybaseError::Config(_))));
632        assert!(matches!(skybase.consumer(), Err(SkybaseError::Config(_))));
633    }
634
635    #[cfg(feature = "storage")]
636    #[test]
637    fn test_skybase_with_store_and_open_store() {
638        let config = SkybaseConfig::new(
639            "https://app.example.com/oauth/client-metadata.json",
640            "https://app.example.com/oauth/callback",
641            "Attach Store App",
642        );
643        let mut skybase = Skybase::new(config).expect("init failed");
644        assert!(skybase.store().is_none());
645
646        let store = RecordStore::open_in_memory().expect("store init failed");
647        skybase = skybase.with_store(store);
648        assert!(skybase.store().is_some());
649
650        // Replace with open_in_memory_store
651        let store2 = skybase
652            .open_in_memory_store()
653            .expect("open_in_memory_store failed");
654        assert!(skybase.store().is_some());
655        let _ = store2;
656
657        // Replace with open_store in a tempdir
658        let temp_dir = tempfile::tempdir().expect("tempdir failed");
659        let db_path = temp_dir.path().join("skybase_facade.db");
660        let store3 = skybase.open_store(&db_path).expect("open_store failed");
661        assert!(skybase.store().is_some());
662        let _ = store3;
663    }
664
665    #[cfg(feature = "storage")]
666    #[tokio::test]
667    async fn test_skybase_consumer_wiring() {
668        let config = SkybaseConfig::new(
669            "https://app.example.com/oauth/client-metadata.json",
670            "https://app.example.com/oauth/callback",
671            "Consumer App",
672        )
673        .with_jetstream_endpoint("wss://jetstream.example.com/subscribe")
674        .with_in_memory_store()
675        .with_wanted_collection("app.bsky.feed.post")
676        .with_wanted_did("did:plc:alice");
677
678        let skybase = Skybase::new(config).expect("init failed");
679        let consumer = skybase.consumer().expect("consumer build failed");
680        assert_eq!(
681            consumer.config().wanted_collections,
682            vec!["app.bsky.feed.post"]
683        );
684        assert_eq!(consumer.config().wanted_dids, vec!["did:plc:alice"]);
685
686        let cancel = CancellationToken::new();
687        let handle = skybase
688            .start_consumer(cancel.clone())
689            .expect("start_consumer failed");
690        handle.stop();
691        let _ = handle.join().await;
692    }
693
694    #[test]
695    fn test_skybase_repo_client_from_credentials() {
696        let config = SkybaseConfig::new(
697            "https://app.example.com/oauth/client-metadata.json",
698            "https://app.example.com/oauth/callback",
699            "Repo App",
700        );
701        let skybase = Skybase::new(config).expect("init failed");
702        let client = skybase
703            .repo_client_from_credentials(
704                "https://pds.example.com",
705                "did:plc:bob",
706                "dpop_access_token_123",
707            )
708            .expect("repo_client_from_credentials failed");
709
710        assert_eq!(client.did(), "did:plc:bob");
711        assert_eq!(
712            client.pds_endpoint().expect("endpoint"),
713            "https://pds.example.com"
714        );
715    }
716}