Rust

Registry

Named resources created on first use by registered factories, cached per context.
Rust 412 lines (111 code)split
PartCodeCommentsBlankTotalFiles
Rust source111279224121
Rust tests1601171

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-registry = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Registry, each a complete program you can copy and run.

A registry holds the resources an application shares, such as database connections and API clients, and creates each one only when it is first needed. Register a factory per resource at startup; code that needs a resource asks the registry for it by name.

Create a resource on first use

The factory runs on the first read; later reads return the same instance.

Rust
use utopia_registry::Registry;

let mut registry = Registry::new();
registry.set("db", || String::from("postgresql://db.internal"));

assert!(registry.has("db"));
assert_eq!(registry.get::<String>("db")?, "postgresql://db.internal");

Get a new instance every time

A fresh factory runs on every read, for resources that must not be shared. A single read can also ask for a new instance.

Rust
use std::sync::atomic::{AtomicU32, Ordering};
use utopia_registry::Registry;

let mut registry = Registry::new();
let requests = AtomicU32::new(0);
registry.set_fresh("request", move || requests.fetch_add(1, Ordering::Relaxed));

assert_eq!(*registry.get::<u32>("request")?, 0);
assert_eq!(*registry.get::<u32>("request")?, 1);

Keep one set of resources per context

Each context has its own instances. Switch context per worker or tenant to give each its own connections.

Rust
use std::sync::atomic::{AtomicU32, Ordering};
use utopia_registry::Registry;

let mut registry = Registry::new();
let connections = AtomicU32::new(0);
registry.set("redis", move || connections.fetch_add(1, Ordering::Relaxed));

let first = *registry.get::<u32>("redis")?;
registry.context("tenant-b");
let second = *registry.get::<u32>("redis")?;
assert_ne!(first, second);

Reference#

Named resources (database connections, clients, caches) created on first use by registered factories, and cached per context.

Register a factory under a name with Registry::set, then read the resource with [Registry::get]: the first read runs the factory and later reads return the same instance. A factory registered with Registry::set_fresh runs on every read, and Registry::get_fresh forces one new instance. Each context (Registry::context) keeps its own instances, so one process can hold one set of connections per worker, tenant or request.

Rust
use utopia_registry::Registry;

let mut registry = Registry::new();
registry.set("db", || String::from("connection"));

assert!(registry.has("db"));
assert_eq!(registry.get::<String>("db")?, "connection");

API#

What utopia_registry exports at its root.