Integrating the networked PliantDb Server

To access PliantDb over the network, you're going to be writing two pieces of code: the server code and the client code.

Your PliantDb Server

The first step is to create a Server, which uses local Storage under the hood. This means that if you're already using PliantDb in local mode, you can swap your usage of Storage with Server in your server code without running your database through any tools. Here's the setup code from pliantdb/examples/server.rs

    let server = Server::open(
        Path::new("server-data.pliantdb"),
        Configuration::default(),
    )
    .await?;
    if server.certificate().await.is_err() {
        server
            .install_self_signed_certificate("example-server", true)
            .await?;
    }
    let certificate = server.certificate().await?;
    server.register_schema::<Shape>().await?;
    match server.create_database::<Shape>("my-database").await {
        Ok(()) => {}
        Err(Error::DatabaseNameAlreadyTaken(_)) => {}
        Err(err) => panic!(
            "Unexpected error from server during create_database: {:?}",
            err
        ),
    }

Once you have a server initialized, calling listen_on will begin listening for connections on the port specified. This uses the preferred native protocol which uses UDP. If you find that UDP is not working for your setup or want to put PliantDb behind a load balancer that doesn't support UDP, you can enable WebSocket support and call listen_for_websockets_on.

You can call both, but since these functions don't return until the server is shut down, you should spawn them instead:

let task_server = server.clone();
tokio::spawn(async move {
    task_server.listen_on(5645).await
});
let server = server.clone();
tokio::spawn(async move {
    task_server.listen_for_websockets_on("localhost:8080").await
});

If you're not running any of your own code on the server, and you're only using one listening method, you can just await the listen method of your choice in your server's main.

From the Client

The Client can support both the native protocol and WebSockets. It determines which protocol to use based on the scheme in the URL:

  • pliantdb://host:port will connect using the native PliantDb protocol.
  • ws://host:port will connect using WebSockets.

Here's how to connect, from pliantdb/examples/server.rs:

Client::new(
    Url::parse("pliantdb://localhost:5645")?,
    Some(certificate),
)
.await?

This is using a pinned certificate to connect. Other methods are supported, but better certificate management is coming soon.

Common Traits