DSN
RustIn Appwrite#
Appwrite runs the Rust crate: the PHP extension serves the library and none of its PHP is left.
Rust 696 lines (267 code)split
| Part | Code | Comments | Blank | Total | Files |
|---|---|---|---|---|---|
| Rust source | 267 | 396 | 33 | 696 | 1 |
Comments include doc comments. Each side counts its src/.
Served from Rust (1)
Utopia\DSN\DSNInstall#
cargo add utopia-dsnGetting started#
Common tasks with DSN, each a complete program you can copy and run.
A DSN (data source name) puts everything needed to reach a service in one string: scheme://user:password@host:port/path?query. Applications read them from configuration so a database, cache or provider can change without code changes. This guide covers the common tasks.
Read a connection string
Parse the string once, then read each part. A missing part is None (or empty for the path).
use utopia_dsn::Dsn;
let dsn = Dsn::parse("postgresql://appwrite:secret@db.internal:5432/appwrite")?;
assert_eq!(dsn.scheme(), "postgresql");
assert_eq!(dsn.host(), "db.internal");
assert_eq!(dsn.port(), Some(5432));
assert_eq!(dsn.path(), b"appwrite");
assert_eq!(dsn.user(), Some(&b"appwrite"[..]));use Utopia\DSN\DSN;
$dsn = new DSN('postgresql://appwrite:secret@db.internal:5432/appwrite');
echo $dsn->getScheme(), "\n"; // postgresql
echo $dsn->getHost(), "\n"; // db.internal
echo $dsn->getPort(), "\n"; // 5432
echo $dsn->getPath(), "\n"; // appwrite
echo $dsn->getUser(), "\n"; // appwriteUse credentials with special characters
Passwords often contain @, / or :, which have a meaning in a DSN. Percent-encode them in the string; the parser decodes them. Credentials are bytes in Rust, because a decoded password can be any bytes.
use utopia_dsn::Dsn;
let dsn = Dsn::parse("redis://default:p%40ss%2Fw%3Ard@cache:6379")?;
assert_eq!(dsn.password(), Some(&b"p@ss/w:rd"[..]));
let password = String::from_utf8_lossy(dsn.password().unwrap_or_default());
assert_eq!(password, "p@ss/w:rd");use Utopia\DSN\DSN;
$dsn = new DSN('redis://default:p%40ss%2Fw%3Ard@cache:6379');
echo $dsn->getPassword(), "\n"; // p@ss/w:rdKeep secrets out of logs
Printing a DSN for debugging never shows its password, and errors never quote the string they refused.
use utopia_dsn::Dsn;
let dsn = Dsn::parse("mariadb://root:hunter2@db:3306/appwrite")?;
let logged = format!("{dsn:?}");
assert!(logged.contains("db"));
assert!(!logged.contains("hunter2"));use Utopia\DSN\DSN;
// PHP marks the constructor argument #[\SensitiveParameter], so stack traces hide it.
$dsn = new DSN('mariadb://root:hunter2@db:3306/appwrite');
echo $dsn->getHost(), "\n"; // dbRead options from the query string
Settings that are not part of the address go in the query. Read one with param, or with param_or to fall back to a default.
use utopia_dsn::Dsn;
let dsn = Dsn::parse("s3://key:secret@s3.amazonaws.com/uploads?region=eu-central-1&acl=private")?;
assert_eq!(dsn.param("region")?, Some(&b"eu-central-1"[..]));
assert_eq!(dsn.param_or("acl", b"public-read")?, b"private");
assert_eq!(dsn.param_or("endpoint", b"https://s3.amazonaws.com")?, b"https://s3.amazonaws.com");use Utopia\DSN\DSN;
$dsn = new DSN('s3://key:secret@s3.amazonaws.com/uploads?region=eu-central-1&acl=private');
echo $dsn->getParam('region'), "\n"; // eu-central-1
echo $dsn->getParam('acl', 'public-read'), "\n"; // private
echo $dsn->getParam('endpoint', 'https://s3.amazonaws.com'), "\n"; // https://s3.amazonaws.comConfigure a service from the environment
Read the DSN from an environment variable, with a default for local development, and pick an adapter by its scheme.
use utopia_dsn::Dsn;
let value = std::env::var("APP_CACHE").unwrap_or_else(|_| "redis://localhost:6379".to_owned());
let dsn = Dsn::parse(&value)?;
let adapter = match dsn.scheme() {
"redis" => format!("Redis at {}:{}", dsn.host(), dsn.port().unwrap_or(6379)),
"memcached" => format!("Memcached at {}", dsn.host()),
other => format!("unsupported cache: {other}"),
};
assert_eq!(adapter, "Redis at localhost:6379");use Utopia\DSN\DSN;
$dsn = new DSN(getenv('APP_CACHE') ?: 'redis://localhost:6379');
$adapter = match ($dsn->getScheme()) {
'redis' => 'Redis at ' . $dsn->getHost() . ':' . ($dsn->getPort() ?? 6379),
'memcached' => 'Memcached at ' . $dsn->getHost(),
default => 'unsupported cache: ' . $dsn->getScheme(),
};
echo $adapter, "\n"; // Redis at localhost:6379Reject invalid configuration
A DSN needs a scheme and a host. Anything else fails with an error you can report without exposing the value.
use utopia_dsn::{Dsn, Error};
for value in ["localhost:6379", "redis://", "not a dsn"] {
match Dsn::parse(value) {
Err(Error::InvalidArgument(reason)) => println!("invalid cache configuration: {reason}"),
other => panic!("expected an error, got {other:?}"),
}
}use Utopia\DSN\DSN;
foreach (['localhost:6379', 'redis://', 'not a dsn'] as $value) {
try {
new DSN($value);
} catch (\InvalidArgumentException $e) {
echo 'invalid cache configuration: ', $e->getMessage(), "\n";
}
}Reference#
Parse data source names (scheme://user:password@host:port/path?query):
the connection strings that configure databases, caches, queues and other
services.
Dsn::parse splits a DSN into its scheme, credentials, host, port, path
and query, and Dsn::param reads one query parameter. Error messages
never quote the DSN, and the Debug output of a Dsn hides the
password, so credentials do not leak into logs.
PHP: ports utopia-php/dsn.
| PHP | Rust |
|---|---|
new DSN($dsn) | Dsn::parse |
getScheme(), getHost() | Dsn::scheme, Dsn::host |
getUser(), getPassword() | Dsn::user, Dsn::password (bytes: they are URL-decoded) |
getPort() (?string) | Dsn::port (Option<u16>; PHP's string is its decimal form) |
DSN::from(...) | Dsn::from |
getPath(), getQuery() | Dsn::path (bytes: it is URL-decoded), Dsn::query |
__toString() | Dsn's Display |
getParam($key, $default) | Dsn::param (Ok(None) where PHP returns $default), Dsn::param_or |
\InvalidArgumentException, \TypeError | Error::InvalidArgument, Error::Type |
PHP: the DSN is split by PHP's parse_url and the query by PHP's
parse_str (php_std), so every input reads exactly as it does in PHP.
PHP marks the argument #[\SensitiveParameter].
use utopia_dsn::Dsn;
let dsn = Dsn::parse("mariadb://user:secret@localhost:3306/appwrite?charset=utf8mb4")?;
assert_eq!(dsn.scheme(), "mariadb");
assert_eq!(dsn.host(), "localhost");
assert_eq!(dsn.port(), Some(3306));
assert_eq!(dsn.path(), b"appwrite");
assert_eq!(dsn.param("charset")?, Some(&b"utf8mb4"[..]));use Utopia\DSN\DSN;
$dsn = new DSN('mariadb://user:secret@localhost:3306/appwrite?charset=utf8mb4');
echo $dsn->getScheme(), "\n"; // mariadb
echo $dsn->getHost(), "\n"; // localhost
echo $dsn->getPort(), "\n"; // 3306
echo $dsn->getPath(), "\n"; // appwrite
echo $dsn->getParam('charset'), "\n"; // utf8mb4API#
What utopia_dsn exports at its root.