A MongoDB ODM over the injected client
Models with oximod that read and write through the mongodb::Client the MongoDB module already built, with no second connection.
ulo-db-mongodb binds mongodb::Client and oximod is an ODM over the same driver. Both can share one client: the module connects, pings and closes it, and the models use it through the _from methods, which take a &Client. This recipe wires them and serves two routes. It is compiled and run against MongoDB 5.0.6 in a container.
Versions compiled with: oximod 1.0.1, mongodb 3.10.1 (through ulo-db-mongodb), ulo 0.1.0-alpha.3.
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-db-mongodb = "=0.1.0-alpha.3"
oximod = "1.0.1"
# The model derive and the `ObjectId` come from the driver; the version unifies with the store's.
mongodb = "3.10"
serde = { version = "1", features = ["derive"] }The code
use mongodb::Client;
use mongodb::bson::oid::ObjectId;
use oximod::{Model, OxiModError};
use serde::{Deserialize, Serialize};
use ulo::{App, AppBuilder, Dep, Module, ModuleDef, ModuleIdentity, Secret, controller, handlers, injectable};
use ulo_db_mongodb::{MongoModule, MongoOptions};
use ulo_http::{CallError, Created, ErrorKind, Json, Path};
#[derive(Debug, Serialize, Deserialize, Model)]
#[db("shop")]
#[collection("customers")]
pub struct Customer {
#[serde(skip_serializing_if = "Option::is_none")]
_id: Option<ObjectId>,
#[validate(min_length = 2)]
name: String,
#[validate(email)]
email: String,
}
#[derive(Deserialize)]
pub struct NewCustomer {
pub name: String,
pub email: String,
}
#[derive(Serialize)]
pub struct CustomerView {
pub id: String,
pub name: String,
pub email: String,
}
/// Validation failures are the caller's; everything else is the store's.
fn refused(error: OxiModError) -> CallError {
match error {
OxiModError::Validation(errors) => CallError::new(ErrorKind::Unprocessable, errors.to_string()),
other => CallError::new(ErrorKind::Unavailable, other.to_string()),
}
}
#[injectable]
pub struct Customers {
client: Dep<Client>,
}
impl Customers {
pub async fn add(&self, new: NewCustomer) -> Result<ObjectId, OxiModError> {
Customer::new().name(new.name).email(new.email).save_from(&self.client).await
}
pub async fn find(&self, id: ObjectId) -> Result<Option<Customer>, OxiModError> {
Customer::find_by_id_from(id, &self.client).await
}
pub async fn count_named(&self, name: &str) -> Result<u64, OxiModError> {
Customer::count_from(mongodb::bson::doc! { "name": name }, &self.client).await
}
/// `Customer::query()` reads OxiMod's global client, which this application never initialises, so
/// a query that is not one of the `_from` methods goes through the typed collection.
pub async fn with_email_domain(&self, domain: &str) -> Result<Vec<Customer>, OxiModError> {
let collection = Customer::get_collection_from(&self.client)?;
let pattern = format!("@{}$", domain.replace('.', "\\."));
let mut cursor = collection
.find(mongodb::bson::doc! { "email": { "$regex": pattern } })
.await
.map_err(|e| OxiModError::database("find by domain", e))?;
let mut found = Vec::new();
while cursor.advance().await.map_err(|e| OxiModError::database("advance", e))? {
found.push(cursor.deserialize_current().map_err(|e| OxiModError::database("decode", e))?);
}
Ok(found)
}
}
#[controller]
pub struct CustomersController {
customers: Dep<Customers>,
}
#[handlers]
impl CustomersController {
#[ulo_http::post("/customers")]
async fn create(&self, Json(new): Json<NewCustomer>) -> Result<Created<Json<serde_json::Value>>, CallError> {
let id = self.customers.add(new).await.map_err(refused)?;
Ok(Created::at(format!("/customers/{}", id.to_hex()), Json(serde_json::json!({ "id": id.to_hex() }))))
}
#[ulo_http::get("/customers/{id}")]
async fn show(&self, Path(id): Path<String>) -> Result<Json<CustomerView>, CallError> {
let id = ObjectId::parse_str(&id).map_err(|_| CallError::new(ErrorKind::BadRequest, "not an object id"))?;
let found = self.customers.find(id).await.map_err(refused)?;
let customer = found.ok_or_else(|| CallError::new(ErrorKind::NotFound, "no such customer"))?;
Ok(Json(CustomerView { id: id.to_hex(), name: customer.name, email: customer.email }))
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ShopModule {
pub uri: String,
}
impl Module for ShopModule {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_value(self)
}
fn register(&self, m: &mut ModuleDef<'_>) {
let options = MongoOptions { uri: Secret::new(self.uri.clone()), max_pool_size: Some(10), min_pool_size: None, app_name: None };
m.import(MongoModule::from_options(options));
m.provide::<Customers>();
m.controller::<CustomersController>();
}
}
pub fn builder(uri: &str) -> AppBuilder {
App::builder(ShopModule { uri: uri.to_owned() })
}What each seam does
MongoModule::from_options(..) is the store module from MongoDB. It builds the client, pings it under the retry policy of Connecting and closes it on shutdown. A Customers provider takes Dep<Client> and nothing else from the driver.
Every OxiMod call in Customers ends in _from and receives &self.client: save_from, find_by_id_from, count_from and get_collection_from. Dep<Client> derefs to Client, so &self.client is the &Client those methods take. The model's #[db("shop")] and #[collection("customers")] name the database and collection, so the client's URI needs no database.
The #[validate(..)] attributes run inside save_from. A failure is OxiModError::Validation, which refused maps to a 422 problem document. Any other OxiModError maps to 503.
with_email_domain shows what to do when OxiMod has no _from form: get_collection_from(&client) returns the driver's typed Collection<Customer>, and the driver's own API runs from there.
What ran
Against a real MongoDB 5.0.6, with the app bound on port 0:
| Call | Answer |
|---|---|
POST /customers with a valid body | 201, a location header of /customers/<id>, body {"id":"..."} |
POST /customers with name B and email bo | 422, detail name: must have a length of at least 2; email: must be a valid email address |
GET /customers/<id> of a saved customer | 200, {"id":"...","name":"Ada","email":"ada@example.com"} |
GET /customers/000000000000000000000000 | 404, detail no such customer |
count_named("Ada") returned 1 and with_email_domain("example.com") returned the saved customer.
Failure modes
The global-client methods fail. Customer::save(), find_by_id() and Model::query() use OxiMod's process-wide client, set by OxiClient::init_global. This application never calls it, and save() answers GlobalClientMissing { msg: "Global MongoDB client has not been initialized" }. That answer was observed. Initialising the global client as well opens a second connection pool in addition to the store's, outside the module's retry, health check and shutdown. The oximod documentation (read, not run) says a sessionless Model::query() currently uses the global client, so typed queries are not available on an injected client; the _from methods and get_collection_from are.
Importing doc. use mongodb::bson::doc; next to #[derive(..)] and #[ulo_http::get(..)] makes doc ambiguous with Rust's built-in doc attribute, and the build fails with E0659 on every derive and route attribute in the file. The code above writes mongodb::bson::doc! in full.
A mongodb+srv:// URI cannot start lazily. See MongoDB.
Reference
- MongoDB: the module, its options and the scheme rule.
- Connecting: the connect bound, retries and permanent failures.
- Providers:
#[injectable]andDep<T>. - Error handling:
CallErrorandErrorKind.
A client as a provider
The lifecycle a module writes for a client no store module covers, what the store modules add on top, and a hand-built SOAP client as the worked example.
Explicit transactions with SQLx
A unit of work that begins a transaction, passes it as &mut Transaction to repositories, and commits once or rolls back on drop.