pubky-testnet 0.7.3

A local test network for Pubky Core development.
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
use crate::Testnet;
use http_relay::HttpRelay;
use pubky::{Keypair, Pubky};
use pubky_homeserver::{ConfigToml, ConnectionString, HomeserverApp, MockDataDir};

#[cfg(feature = "embedded-postgres")]
use crate::embedded_postgres::EmbeddedPostgres;

/// A simple testnet with random ports assigned for all components.
///
/// Components included:
/// - A local DHT with bootstrapping nodes.
/// - A homeserver (default pubkey: `8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo`).
/// - An HTTP relay (optional, use `.with_http_relay()` to enable).
///
/// # Recommended Usage
/// Use [`EphemeralTestnet::builder()`] to create a testnet with explicit configuration:
///
/// ```ignore
/// // Minimal testnet (admin/metrics disabled) - fastest for most tests
/// let testnet = EphemeralTestnet::builder().build().await?;
///
/// // Full-featured testnet (admin enabled) - for tests requiring admin API
/// let testnet = EphemeralTestnet::builder()
///     .config(ConfigToml::default_test_config())
///     .build()
///     .await?;
/// ```
///
/// # Configuration Defaults
/// - [`EphemeralTestnet::builder().build()`] uses [`ConfigToml::minimal_test_config()`] (admin/metrics **disabled**)
/// - Deprecated [`EphemeralTestnet::start()`] uses [`ConfigToml::default_test_config()`] (admin **enabled**)
pub struct EphemeralTestnet {
    /// Inner flexible testnet.
    pub testnet: Testnet,
    /// Embedded PostgreSQL instance (if using embedded postgres).
    /// Kept alive as long as the testnet is running.
    #[cfg(feature = "embedded-postgres")]
    #[allow(dead_code)]
    embedded_postgres: Option<EmbeddedPostgres>,
}

/// Builder for configuring and creating an [`EphemeralTestnet`].
///
/// Provides a fluent API for customizing testnet configuration before creation.
///
/// # Defaults
/// - **Config**: [`ConfigToml::minimal_test_config()`] (admin/metrics disabled)
/// - **Keypair**: Deterministic keypair from `[0; 32]` secret key
/// - **Postgres**: Uses `TEST_PUBKY_CONNECTION_STRING` env var if set, otherwise in-memory
/// - **HTTP Relay**: Disabled by default (use `.with_http_relay()` to enable)
///
/// # Example
/// ```ignore
/// // Use defaults (minimal config, no HTTP relay)
/// let testnet = EphemeralTestnet::builder().build().await?;
///
/// // Enable admin server
/// let testnet = EphemeralTestnet::builder()
///     .config(ConfigToml::default_test_config())
///     .build()
///     .await?;
///
/// // Custom keypair
/// let testnet = EphemeralTestnet::builder()
///     .keypair(Keypair::random())
///     .build()
///     .await?;
///
/// // With HTTP relay (for tests that need it)
/// let testnet = EphemeralTestnet::builder()
///     .with_http_relay()
///     .build()
///     .await?;
/// ```
pub struct EphemeralTestnetBuilder {
    postgres_connection_string: Option<ConnectionString>,
    homeserver_config: Option<ConfigToml>,
    homeserver_keypair: Option<Keypair>,
    http_relay: bool,
    #[cfg(feature = "embedded-postgres")]
    use_embedded_postgres: bool,
}

impl EphemeralTestnetBuilder {
    /// Create a new builder with default configuration.
    pub fn new() -> Self {
        Self {
            postgres_connection_string: None,
            homeserver_config: None,
            homeserver_keypair: None,
            http_relay: false,
            #[cfg(feature = "embedded-postgres")]
            use_embedded_postgres: false,
        }
    }

    /// Set a custom homeserver configuration.
    pub fn config(mut self, config: ConfigToml) -> Self {
        self.homeserver_config = Some(config);
        self
    }

    /// Set a specific keypair for the homeserver.
    pub fn keypair(mut self, keypair: Keypair) -> Self {
        self.homeserver_keypair = Some(keypair);
        self
    }

    /// Set a custom postgres connection string.
    pub fn postgres(mut self, connection_string: ConnectionString) -> Self {
        self.postgres_connection_string = Some(connection_string);
        self
    }

    /// Enable the HTTP relay (disabled by default).
    pub fn with_http_relay(mut self) -> Self {
        self.http_relay = true;
        self
    }

    /// Use embedded PostgreSQL instead of an external database.
    ///
    /// This starts an embedded PostgreSQL instance that is automatically
    /// downloaded and managed. The first run will download the PostgreSQL
    /// binaries (~50-100MB), which are cached for subsequent runs.
    ///
    /// This is useful for running tests without requiring a separate
    /// PostgreSQL installation.
    ///
    /// **Note**: Cannot be combined with `.postgres()`. If both are set, `build()` will
    /// return an error.
    #[cfg(feature = "embedded-postgres")]
    pub fn with_embedded_postgres(mut self) -> Self {
        self.use_embedded_postgres = true;
        self
    }

    /// Build and start the testnet with the configured settings.
    /// Uses minimal_test_config() by default (admin/metrics disabled).
    ///
    /// # Errors
    /// Returns an error if both `.postgres()` and `.with_embedded_postgres()` are set.
    pub async fn build(self) -> anyhow::Result<EphemeralTestnet> {
        #[cfg(feature = "embedded-postgres")]
        if self.use_embedded_postgres && self.postgres_connection_string.is_some() {
            anyhow::bail!(
                "Cannot use both embedded postgres and a custom connection string. \
                 Use either .with_embedded_postgres() or .postgres(), not both."
            );
        }

        #[cfg(feature = "embedded-postgres")]
        let (embedded_postgres, postgres_connection_string) = if self.use_embedded_postgres {
            let embedded = EmbeddedPostgres::start().await?;
            let conn_string = embedded.connection_string()?;
            (Some(embedded), Some(conn_string))
        } else {
            (None, self.postgres_connection_string)
        };

        #[cfg(not(feature = "embedded-postgres"))]
        let postgres_connection_string = self.postgres_connection_string;

        let mut testnet = if let Some(postgres) = postgres_connection_string {
            Testnet::new_with_custom_postgres(postgres).await?
        } else {
            Testnet::new().await?
        };

        if self.http_relay {
            testnet.create_http_relay().await?;
        }

        let mut config = self
            .homeserver_config
            .unwrap_or_else(ConfigToml::minimal_test_config);

        if let Some(connection_string) = testnet.postgres_connection_string.as_ref() {
            config.general.database_url = connection_string.clone();
        }

        let keypair = self
            .homeserver_keypair
            .unwrap_or_else(|| Keypair::from_secret(&[0; 32]));
        let mock_dir = MockDataDir::new(config, Some(keypair))?;
        testnet.create_homeserver_app_with_mock(mock_dir).await?;

        Ok(EphemeralTestnet {
            testnet,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres,
        })
    }
}

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

impl EphemeralTestnet {
    /// Create a new builder for configuring the testnet.
    ///
    /// This is the recommended way to create a testnet with custom configuration.
    ///
    /// # Example
    /// ```ignore
    /// let testnet = EphemeralTestnet::builder()
    ///     .config(ConfigToml::default_test_config())
    ///     .keypair(Keypair::random())
    ///     .build()
    ///     .await?;
    /// ```
    pub fn builder() -> EphemeralTestnetBuilder {
        EphemeralTestnetBuilder::new()
    }

    /// Run a new simple testnet with full config (admin enabled).
    ///
    /// # Deprecated
    /// Use [`Self::builder()`] for explicit configuration control.
    /// This method uses [`ConfigToml::default_test_config()`] which enables the admin server.
    #[deprecated(
        since = "0.5.0",
        note = "Use EphemeralTestnet::builder().config(ConfigToml::default_test_config()).build() for explicit behavior"
    )]
    pub async fn start() -> anyhow::Result<Self> {
        let mut testnet = Testnet::new().await?;
        testnet.create_http_relay().await?;
        testnet.create_homeserver().await?;
        Ok(Self {
            testnet,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres: None,
        })
    }

    /// Run a new simple testnet with custom postgres and full config (admin enabled).
    ///
    /// # Deprecated
    /// Use [`Self::builder()`] with `.postgres()` for explicit configuration control.
    #[deprecated(
        since = "0.5.0",
        note = "Use EphemeralTestnet::builder().postgres(...).config(ConfigToml::default_test_config()).build() instead"
    )]
    pub async fn start_with_custom_postgres(
        postgres_connection_string: ConnectionString,
    ) -> anyhow::Result<Self> {
        let mut testnet = Testnet::new_with_custom_postgres(postgres_connection_string).await?;
        testnet.create_http_relay().await?;
        testnet.create_homeserver().await?;
        Ok(Self {
            testnet,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres: None,
        })
    }

    /// Run a new simple testnet with custom postgres but no homeserver (minimal setup).
    ///
    /// # Deprecated
    /// Use [`Testnet`] directly for fine-grained control over component creation.
    #[deprecated(
        since = "0.5.0",
        note = "Use Testnet::new_with_custom_postgres() and create_http_relay() for fine-grained control"
    )]
    pub async fn start_minimal_with_custom_postgres(
        postgres_connection_string: ConnectionString,
    ) -> anyhow::Result<Self> {
        let mut me = Self {
            testnet: Testnet::new_with_custom_postgres(postgres_connection_string).await?,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres: None,
        };
        me.testnet.create_http_relay().await?;
        Ok(me)
    }

    /// Run a new simple testnet network with a minimal setup (no homeserver).
    ///
    /// # Deprecated
    /// Use [`Testnet`] directly for fine-grained control over component creation.
    #[deprecated(
        since = "0.5.0",
        note = "Use Testnet::new() and create_http_relay() for fine-grained control"
    )]
    pub async fn start_minimal() -> anyhow::Result<Self> {
        let mut me = Self {
            testnet: Testnet::new().await?,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres: None,
        };
        me.testnet.create_http_relay().await?;
        Ok(me)
    }

    /// Create an additional homeserver with a random keypair.
    pub async fn create_random_homeserver(&mut self) -> anyhow::Result<&HomeserverApp> {
        self.create_random_homeserver_with_config(None).await
    }

    /// Create an additional homeserver with a random keypair and custom config.
    /// Uses minimal_test_config() by default (admin/metrics disabled).
    pub async fn create_random_homeserver_with_config(
        &mut self,
        config: Option<ConfigToml>,
    ) -> anyhow::Result<&HomeserverApp> {
        let mut config = config.unwrap_or_else(ConfigToml::minimal_test_config);

        if let Some(connection_string) = self.testnet.postgres_connection_string.as_ref() {
            config.general.database_url = connection_string.clone();
        }

        let mock_dir = MockDataDir::new(config, Some(Keypair::random()))?;
        self.testnet.create_homeserver_app_with_mock(mock_dir).await
    }

    /// Create a new pubky client builder.
    pub fn client_builder(&self) -> pubky::PubkyHttpClientBuilder {
        self.testnet.client_builder()
    }

    /// Creates a [`pubky::PubkyHttpClient`] pre-configured to use this test network.
    pub fn client(&self) -> Result<pubky::PubkyHttpClient, pubky::BuildError> {
        self.testnet.client()
    }

    /// Creates a [`pubky::Pubky`] SDK facade pre-configured to use this test network.
    ///
    /// This is a convenience method that builds a client from `Self::client_builder`.
    pub fn sdk(&self) -> Result<Pubky, pubky::BuildError> {
        self.testnet.sdk()
    }

    /// Create a new pkarr client builder.
    pub fn pkarr_client_builder(&self) -> pkarr::ClientBuilder {
        self.testnet.pkarr_client_builder()
    }

    /// Get the homeserver in the testnet.
    pub fn homeserver_app(&self) -> &pubky_homeserver::HomeserverApp {
        self.testnet
            .homeservers
            .first()
            .expect("homeservers should be non-empty")
    }

    /// Get the http relay in the testnet.
    pub fn http_relay(&self) -> &HttpRelay {
        self.testnet
            .http_relays
            .first()
            .expect("no http relay configured - use .with_http_relay() when building")
    }
}

#[cfg(test)]
mod test {
    use super::*;

    /// Test that two testnets can be run in a row.
    /// This is to prevent the case where the testnet is not cleaned up properly.
    /// For example, if the port is not released after the testnet is stopped.
    #[tokio::test]
    async fn test_two_testnet_in_a_row() {
        {
            let _ = EphemeralTestnet::builder().build().await.unwrap();
        }

        {
            let _ = EphemeralTestnet::builder().build().await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_homeserver_with_random_keypair() {
        // Start with just DHT + http relay, no homeserver
        let mut testnet = Testnet::new().await.unwrap();
        testnet.create_http_relay().await.unwrap();
        let mut network = EphemeralTestnet {
            testnet,
            #[cfg(feature = "embedded-postgres")]
            embedded_postgres: None,
        };
        assert!(network.testnet.homeservers.is_empty());

        let _ = network.create_random_homeserver().await.unwrap();
        let _ = network.create_random_homeserver().await.unwrap();
        assert!(network.testnet.homeservers.len() == 2);

        // The two newly created homeservers must have distinct public keys.
        assert_ne!(
            network.testnet.homeservers[0].public_key(),
            network.testnet.homeservers[1].public_key()
        );
    }

    #[tokio::test]
    async fn test_builder_default() {
        // Verify builder creates homeserver with minimal config (admin disabled)
        let network = EphemeralTestnet::builder().build().await.unwrap();
        let homeserver = network.homeserver_app();

        // The builder should use minimal_test_config() by default (admin disabled)
        assert!(
            homeserver.admin_server().is_none(),
            "Builder should use minimal config with admin disabled by default"
        );
        assert!(
            homeserver.metrics_server().is_none(),
            "Builder should use minimal config with metrics disabled by default"
        );
    }

    #[tokio::test]
    async fn test_builder_with_custom_config() {
        // Verify custom config is used (e.g., metrics enabled)
        let mut config = ConfigToml::minimal_test_config();
        config.metrics.enabled = true;

        let network = EphemeralTestnet::builder()
            .config(config)
            .build()
            .await
            .unwrap();

        let homeserver = network.homeserver_app();
        assert!(
            homeserver.metrics_server().is_some(),
            "Custom config should enable metrics"
        );
        assert!(
            homeserver.admin_server().is_none(),
            "Custom config should keep admin disabled"
        );
    }

    #[tokio::test]
    async fn test_builder_with_custom_keypair() {
        // Verify custom keypair is used
        let keypair = Keypair::random();
        let expected_public_key = keypair.public_key();

        let network = EphemeralTestnet::builder()
            .keypair(keypair)
            .build()
            .await
            .unwrap();

        let homeserver = network.homeserver_app();
        assert_eq!(
            homeserver.public_key(),
            expected_public_key,
            "Custom keypair should be used"
        );
    }
}