Rust
The Rust runtime is the crate comatype (packages/rust). It depends on serde / serde_json (JSON), regex (format and pattern validation) and ureq (the HTTP client, synchronous).
What is generated#
<out>/ default is src/comatype_gen
├─ mod.rs Declares each module
├─ types.rs Named types (structs and enums, with serde derives)
├─ init.rs Wrappers, ctx and wrapper statuses
└─ user_put_id.rs One per endpoint (the module name is a snake_case joined name)Write mod comatype_gen; in main.rs and you can use it. Generated .rs files are formatted if rustfmt is available.
Client#
user_put_id.rs
// Call PUT /user/:id. Use the generated ENDPOINT and Request / Response
use crate::comatype_gen::types::UserData;
use crate::comatype_gen::user_put_id::{self, Request, Response};
use comatype::c;
pub fn put_user(id: &str, user: UserData) -> comatype::Result<()> {
// Request has params / headers / body, typed from the params block of put__id.comat
let res = c::put(
&user_put_id::ENDPOINT,
Request { params: user_put_id::Params { id: id.into() }, body: user, ..Default::default() },
)?;
match res {
Response::S200(data, _headers) => drop(data), // UserData, headers are S200Headers
Response::S404(error, _) => drop(error), // ApiError
_ => {}
}
Ok(())
}- The argument is
Requestif there areparams/search/ headers (it implementsDefault, so..Default::default()works), the body itself if there is only abody, andcomatype::NoArgif there is neither. - The return value is
Result<Response, comatype::Error>.Responseis an enum whose variants, likeS200(body, headers), carry only the body and headers that exist. - A status that is not in the
.comatisError::UnexpectedStatus, and a validation error isError::Validation(pathandreason). - The client is synchronous (ureq).
init.rs
// Client init: pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or Config.base_url
use crate::comatype_gen::init::Wrappers;
use comatype::c::{self, Config};
use comatype::CookieJar;
use std::sync::Arc;
pub fn init_comatype() {
c::init(Config {
// Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
cookie_jar: Some(Arc::new(CookieJar::new())),
// With the generated Wrappers, a missing wrapper declared in init.comat is a compile error
..Config::default().wrappers(Wrappers { auth: crate::auth::auth() })
});
}Server#
user_put_id.rs
// Handler for PUT /user/:id. Register the generated ENDPOINT with the Server
use crate::comatype_gen::types::ApiError;
use crate::comatype_gen::user_put_id::{self, Reply, Response, S200Headers};
use comatype::s::Server;
pub fn register(server: &Server, db: crate::db::Db) {
server.put(&user_put_id::ENDPOINT, move |req| -> Reply {
// req.params.id: Uuidv4, req.body: UserData, req.ctx.auth.user (wrap auth is on)
let Some(user) = db.update(&req.params.id.0, req.body) else {
return Response::S404(ApiError { code: "not_found".into(), message: "user not found".into() }, Default::default()).into();
};
// headerRes (X-Resource-Version) of user/defaults.comat
let headers = S200Headers { x_resource_version: Some("v2".into()), ..Default::default() };
Response::S200(user, headers).into()
});
}- Register handlers on
s::Server. A handler isFn(Request) -> Response. For an endpoint withcookie onit isReply(.into()from aResponse; cookies use.with_cookie(CookieValue::new(v).max_age(3600))/.clear_cookie()). server.handle(method, target, headers, body)is an entry point you can call from any framework.server.serve("127.0.0.1:3000", |addr| ...)is a simple server built on the standard library only (one thread per connection).- A panic in a handler becomes
500(the cause is passed toon_error).
init.rs
// Server init: pass the implemented ComatypeWrap. The cookie settings (name, httpOnly, etc.) are in init.comat
use crate::comatype_gen::init::Wrappers;
use comatype::s::Server;
pub fn init_comatype(server: &Server) {
// With the generated Wrappers, a missing wrapper declared in init.comat, or a wrong type, is a compile error
server.init(Wrappers { auth: crate::auth::auth() });
}auth.rs
// Implement a wrapper as a ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat)
use crate::comatype_gen::init::{s401, AuthCtx};
use crate::comatype_gen::types::ApiError;
use comatype::s::ComatypeWrap;
pub fn auth() -> ComatypeWrap<AuthCtx> {
ComatypeWrap::new(|req, next| {
// On endpoints with `wrap auth` on, a handler can read req.ctx.auth.user, typed
let Some(user) = crate::verify_session(req.cookie("session")) else {
return s401(ApiError { code: "unauthorized".into(), message: "login required".into() });
};
next(req.with_ctx(AuthCtx { user }))
})
}Type mapping#
emailphoneuuiduuidv4uuidv7datetimedatetimedecimalurlare own types that wrap a string (comatype::Emailand so on). Make them with.into()/::new(), and check the format withvalidate.intisi64,int64iscomatype::Int64(a string on the wire),bytesiscomatype::Bytes(base64), andjsonisserde_json::Value.- Optional (
?) andT | nullareOption<T>. Field names are snake_case (serde(rename)restores the original name). - Constraints (
minmaxpattern) are checked by the generatedValidateimplementation.
Notes#
- Union types support
T | nulland unions of only string literals. Recursive types (types that contain themselves) are not supported. - A missing wrapper is found at compile time, because the fields of the
Wrappersstruct are required.