encore-dev 2.0.0-beta.5

Rust SDK for Encore applications
Documentation
//! What a handle's access does to the statements it runs, through a real
//! runtime and server: a read handle's writes are refused, in a statement or
//! a transaction, and a write handle still writes after a read handle used
//! its connection. A read handle's connection string connects read-only too.
//!
//! `#[ignore]`d so a plain `cargo test` stays hermetic. Run them with a server
//! reachable at `ENCORE_TEST_PG` (defaulting to a local trust-auth cluster):
//!
//! ```sh
//! cargo test -p encore-dev --test postgres_access -- --ignored
//! ```

use encore::storage::postgres::{Database, DatabaseRef};
use encore_runtimecfg::pb;

static DB: Database = Database::named("access");

/// Points the runtime at the test's server before anything starts it: one
/// database, with a read-write pool of a single connection, so every handle
/// shares it.
fn setup() {
    let uri = std::env::var("ENCORE_TEST_PG")
        .unwrap_or_else(|_| "postgresql://postgres@127.0.0.1:5432/postgres".to_string());
    let config: tokio_postgres::Config = uri.parse().expect("ENCORE_TEST_PG is not a valid URI");
    let host = match &config.get_hosts()[0] {
        tokio_postgres::config::Host::Tcp(host) => host.clone(),
        #[cfg(unix)]
        tokio_postgres::config::Host::Unix(path) => path.display().to_string(),
    };
    let port = config.get_ports().first().copied().unwrap_or(5432);
    let cfg = pb::RuntimeConfig {
        environment: Some(pb::Environment {
            app_id: "app".into(),
            env_name: "local".into(),
            ..Default::default()
        }),
        deployment: Some(pb::Deployment {
            hosted_services: vec![pb::HostedService {
                name: "svc".into(),
                ..Default::default()
            }],
            ..Default::default()
        }),
        infra: Some(pb::Infrastructure {
            resources: Some(pb::infrastructure::Resources {
                sql_clusters: vec![pb::SqlCluster {
                    rid: "cluster".into(),
                    servers: vec![pb::SqlServer {
                        rid: "server".into(),
                        host: format!("{host}:{port}"),
                        kind: pb::ServerKind::Primary as i32,
                        tls_config: None,
                    }],
                    databases: vec![pb::SqlDatabase {
                        rid: "db".into(),
                        encore_name: "access".into(),
                        cloud_name: config.get_dbname().unwrap_or("postgres").into(),
                        conn_pools: vec![pb::SqlConnectionPool {
                            role_rid: "role".into(),
                            max_connections: 1,
                            ..Default::default()
                        }],
                    }],
                }],
                ..Default::default()
            }),
            credentials: Some(pb::infrastructure::Credentials {
                sql_roles: vec![pb::SqlRole {
                    rid: "role".into(),
                    username: config.get_user().unwrap_or("postgres").into(),
                    password: config.get_password().map(|password| pb::SecretData {
                        source: Some(pb::secret_data::Source::Embedded(password.to_vec())),
                        ..Default::default()
                    }),
                    client_cert_rid: None,
                }],
                ..Default::default()
            }),
        }),
        ..Default::default()
    };
    // Before the runtime reads the environment; the only test here.
    std::env::set_var(
        "ENCORE_RUNTIME_CONFIG",
        encore_runtimecfg::encoding::encode_env_value(&cfg),
    );
}

const WRITE: &str = "CREATE TEMP TABLE IF NOT EXISTS encore_access (id int)";

fn refused(result: Result<(), encore::Error>) -> bool {
    result.is_err_and(|err| err.to_string().contains("read-only transaction"))
}

#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs a PostgreSQL server at ENCORE_TEST_PG"]
async fn read_handles_refuse_writes_and_write_handles_still_write() {
    setup();
    let readers: [DatabaseRef; 2] = [DB.read(), DB.read_primary()];
    for reader in readers {
        let row = reader.query_one("SELECT 1", &[]).await.expect("a read");
        assert_eq!(row.get::<_, i32>(0), 1);
        assert!(
            refused(reader.batch_execute(WRITE).await),
            "a read handle wrote"
        );

        let tx = reader.transaction().await.expect("begin");
        assert!(
            refused(tx.batch_execute(WRITE).await),
            "its transaction wrote"
        );
        tx.rollback().await.unwrap();

        let tx = reader
            .build_transaction()
            .read_only(false)
            .start()
            .await
            .expect("begin");
        assert!(
            refused(tx.batch_execute(WRITE).await),
            "its transaction asking to write wrote"
        );
        tx.rollback().await.unwrap();

        let conn = reader.acquire().await.expect("acquire");
        assert!(
            refused(conn.batch_execute(WRITE).await),
            "its connection wrote"
        );
        conn.close().await;

        // The same connection, the pool having one.
        DB.write()
            .batch_execute(WRITE)
            .await
            .expect("a write handle wrote after a read handle");
        DB.batch_execute(WRITE).await.expect("the database wrote");
        let tx = DB.admin().transaction().await.expect("begin");
        tx.batch_execute(WRITE)
            .await
            .expect("an admin transaction wrote");
        tx.rollback().await.unwrap();
    }

    // Another client, through the runtime's proxy.
    let conn_strings = [
        (DB.connection_string(), false),
        (DB.write().connection_string(), false),
        (DB.read().connection_string(), true),
        (DB.read_primary().connection_string(), true),
    ];
    for (conn_string, read_only) in conn_strings {
        let conn_string = conn_string.expect("a connection string");
        let (client, conn) = tokio_postgres::connect(&conn_string, tokio_postgres::NoTls)
            .await
            .expect("connect through the proxy");
        tokio::spawn(conn);
        let row = client
            .query_one("SHOW default_transaction_read_only", &[])
            .await
            .unwrap();
        let expected = if read_only { "on" } else { "off" };
        assert_eq!(row.get::<_, String>(0), expected, "{conn_string}");
        match client.batch_execute(WRITE).await {
            Ok(()) => assert!(!read_only, "{conn_string} wrote"),
            Err(err) => {
                assert!(read_only, "{conn_string}: {err}");
                assert_eq!(
                    err.code(),
                    Some(&tokio_postgres::error::SqlState::READ_ONLY_SQL_TRANSACTION),
                    "{conn_string}: {err}"
                );
            }
        }
    }
}