Exposing methods over RPC
The JSON-2 core (erp-rpc) runs in-process; the native HTTP route is
/erp/json/2/<model>/<method>. ADR 0073 establishes the product namespace;
ADR 0038 and docs/design/m3-rpc.md describe dispatch. Existing /json/2/ callers
remain accepted as input aliases without redirecting or replaying POSTs.
Use X-ERP-Database when selecting a database; a single legacy selector remains
accepted, but sending both header names is refused. Domain errors emit
erp.exceptions.*; session errors emit erp.http.session.*. Integrations matching
exception names must use these canonical names. Status/body semantics are unchanged.
In Odoo every public method (a name that does not start with _) is callable over RPC unless it is
decorated @api.private. ERPForAll turns this around: a method is callable only when you mark it with
#[rpc], and the mark must say what the method changes, its effect. Helpers you never meant to
publish stay private, and the server knows which calls only read.
Every Rust example here is compiled and run as a doctest of erp-test-models, like the rest of the
guide.
Effects
Section titled “Effects”| Effect | Use it when the method | A read_only API key | Transaction |
|---|---|---|---|
read | changes nothing anywhere | may call it | READ ONLY (may go to a replica later) |
write | changes this database, reversibly | is refused | read/write |
destructive | deletes data or is hard to undo (unlink, posting) | is refused | read/write |
external | acts outside the database (mail, payment, HTTP) | is refused | read/write |
Pick the widest effect of anything the method may do: a method that reads and sends an e-mail is
external. The effect labels the whole call, including what the methods it calls do.
Marking a method
Section titled “Marking a method”Put #[rpc(effect = …)] next to #[method]. Add model for a model method (Odoo’s @api.model): the
call’s ids must then be empty.
# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;
#[model(name = "library.book", description = "Book")]pub struct Book { #[field(char, required)] pub name: Option<Arc<str>>, #[field(integer)] pub copies: i32,}
#[methods(Book)]impl Book { /// How many copies the selected books have in total. #[method] #[rpc(effect = read)] async fn total_copies(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { let copies: Vec<i32> = this.mapped(tx, Book::COPIES).await?; Ok(copies.into_iter().map(i64::from).sum()) }
/// Add `count` copies to each selected book (10 when the call does not say). #[method] #[rpc(effect = write)] async fn add_copies( this: &RecordSet<Book>, tx: &mut Transaction, #[arg(default = 10)] count: i64, ) -> Result<bool> { for book in this.iter() { let copies = i64::from(book.get(tx, Book::COPIES).await?); let total = i32::try_from(copies + count) .map_err(|_| Error::validation("too many copies"))?; book.set(tx, Book::COPIES, total).await?; } Ok(true) }
/// Create a book by name: a model method. #[method] #[rpc(effect = write, model)] async fn quick_create(this: &RecordSet<Book>, tx: &mut Transaction, name: String) -> Result<RecordSet<Book>> { this.create(tx, vec![this.vals().set(Book::NAME, name.as_str())]).await }
/// Not marked: callable from Rust, refused over RPC with Odoo's 403. #[method] async fn recount(_this: &RecordSet<Book>, _tx: &mut Transaction) -> Result<bool> { Ok(true) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }A client then calls POST /erp/json/2/library.book/add_copies with {"ids": [7], "count": 2}, or
{"ids": 7} (a single id), or without count to get the default.
Arguments and results
Section titled “Arguments and results”- Keyword names are your Rust parameter names. A missing required argument, an unknown one or
idson a model method answer 422 with Odoo’s texts (missing a required argument: 'count',got an unexpected keyword argument 'cnt',cannot call library.book.quick_create with ids). Option<T>makes an argument optional (absent ornullisNone);#[arg(default = expr)]gives a default. Conversions are lossless: ani64takes JSON integers only, so1.5or"2"is a 422 naming the argument and the expected type.- Accepted types implement
erp_sdk::rpc::FromRpc:bool,i64,u64,f64,String,Value,ValueMap,Vec<T>,Option<T>,Domain,web::Specandrpc::Binary(standard padded base64, decoded strictly). Results implementerp_sdk::rpc::IntoRpc; a recordset is returned as its ids, as Odoo does. Implement the traits for your own types when you need more;FromRpcthen needs aconst SHAPE: ArgShape(erp_sdk::rpc::ArgShape) describing the JSON your binder accepts, orArgShape::Open("why")when no closed shape describes it (see Offering a method to the assistant). - The parameter names
idsandcontextare reserved (they are keys of the call body); using them is a compile error.
Mistakes the compiler catches
Section titled “Mistakes the compiler catches”#[rpc] without an effect:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[rpc] async fn total(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { Ok(0) }}# fn main() {}An unknown effect, or a reserved parameter name:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[rpc(effect = readonly)] async fn total(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { Ok(0) }}# fn main() {}# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[rpc(effect = read)] async fn total(this: &RecordSet<Book>, tx: &mut Transaction, ids: Vec<i64>) -> Result<i64> { Ok(0) }}# fn main() {}An effect given twice (even the same one):
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {}#[methods(Book)]impl Book { #[method] #[rpc(effect = read, effect = write)] async fn total(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<i64> { Ok(0) }}# fn main() {}Overrides: hide, widen, never narrow
Section titled “Overrides: hide, widen, never narrow”An override in another addon may expose a method, widen its effect, or hide it with #[rpc(hide)]
(Odoo’s @api.private in a subclass). An override without #[rpc] keeps what is below it. It may not
narrow the effect: the server refuses to start, naming both declarations.
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# }#[methods(Book)]impl Book { #[method] #[rpc(effect = write, model)] async fn import_catalogue(_this: &RecordSet<Book>, _tx: &mut Transaction) -> Result<bool> { Ok(true) }}
pub mod library_mail { use erp_sdk::prelude::*;
use super::Book;
erp_sdk::addon!(name = "library_mail", depends = ["library"]);
#[extend(Book, addon = "library_mail")] pub struct BookMail {}
#[methods(Book, addon = "library_mail")] impl BookMail { /// Now also e-mails the librarian: `external`. #[method(override)] #[rpc(effect = external, model)] async fn import_catalogue(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<bool> { sup.call(tx, this.as_records(), ()).await } }}
pub mod library_lite { use erp_sdk::prelude::*;
use super::Book;
erp_sdk::addon!(name = "library_lite", depends = ["library"]);
#[extend(Book, addon = "library_lite")] pub struct BookLite {}
#[methods(Book, addon = "library_lite")] impl BookLite { /// Wrong: `read` below `write`. #[method(override)] #[rpc(effect = read, model)] async fn import_catalogue(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<bool> { sup.call(tx, this.as_records(), ()).await } }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {erp_testkit::Harness::builder([&ADDON, &library_mail::ADDON]).check()?;let err = erp_testkit::Harness::builder([&ADDON, &library_lite::ADDON]) .check() .unwrap_err() .to_string();assert!(err.contains( "library.book.import_catalogue: addon 'library_lite' declares effect = read below effect = \ write declared by 'library'"));# Ok(())# }A read method that writes is a bug
Section titled “A read method that writes is a bug”A read call runs in a read-only transaction. If the method (or anything it calls) creates, writes,
deletes, locks rows, flushes pending values or sends a statement that changes data, the call fails with
erp.programming naming the method:
'library.book.total_copies' is declared effect = read but tried to write 'library.book'; declare effect = write (or wider). Odoo would quietly replay the call on a read/write cursor; ERPForAll does
not, because read is what lets a read-only API key call the method.
Offering a method to the assistant
Section titled “Offering a method to the assistant”Business methods are closed to the AI assistant unless you offer them (ADR 0188 D2 (a)). Add
assistant = offer to the method’s #[rpc]:
#[method]#[rpc(effect = write, assistant = offer)]async fn set_priority(this: &RecordSet<Task>, tx: &mut Transaction, priority: String) -> Result<bool>The assistant may then use the method: a read method runs during the turn, a write or destructive
one becomes a proposal the user confirms before it runs (ADR 0188 D5). The rules:
offeris the only value. It needseffect = read,writeordestructive: witheffect = external, or next to#[rpc(hide)], it is a compile error.- Every parameter needs a closed shape:
bool,i64,u64,f64,String,Domain, andVec<T>orOption<T>of those.Value,ValueMap,web::Spec,rpc::Binaryand your own types withArgShape::Openhave no closed schema; offering such a method fails the ORM build with an error naming the model, the method and the parameter. - The offer belongs to your implementation. When another addon overrides the method, the method stays
offered only if that override says
assistant = offertoo: an override without it withdraws the offer (it may add behaviour you never reviewed). A WebAssembly implementation in the chain also withdraws it. If an override widens the method toeffect = external, or hides it, while your offer stands, the ORM build fails. - Review rule. Never offer a method that posts, notifies, or reaches an outbound delivery (mail, messages, webhooks, payments, anything queued for after commit). Those are external in effect even when the code path looks like a database write. Reviewers refuse an offer on such a method.
The assistant reads the offered methods and their argument schemas from the exposure table
(ExposureTable::assistant_offers, ExposureTable::assistant_offered); the schemas come from
erp_registry::tool_schema.
The call context
Section titled “The call context”The body’s context replaces the context (nothing carries over from earlier calls). lang must be an
active language, tz a known time zone and allowed_company_ids companies of the user, checked before
the method runs. Keys only the server may set (the data loader’s install_mode, module,
install_filename, noupdate) are refused with 422. Every key beginning with __ is also
reserved and refused with 422, including addon-defined keys: do not use that prefix for public
context parameters. This is broader than the named server-only keys in ADR 0038 option (c).
Other keys reach your method unchanged. If your
addon adds a context key that relaxes a check, an audit or a constraint, it must be server-only (talk
to the core team); the identity never comes from the context.
Idempotency keys (for integrators)
Section titled “Idempotency keys (for integrators)”A client that may retry a write, destructive or external call sends the header
Idempotency-Key: <uuid> (RFC 9562, v7 recommended). The server runs the call at most once per key and
user:
- the same request again replays the stored answer byte for byte (header
Idempotent-Replayed: true); - the same key with a different request is 422
erp.idempotency_mismatch; - while the first request still runs, 409
erp.idempotency_in_progresswithRetry-After; - after the user’s access changed (companies, key scope, groups, the access policy), 409
erp.idempotency_access_changed: the first call did commit, but its answer is not sent again; - after
rpc.idempotency_replay_secs(1 hour by default), 409erp.idempotency_result_expired; the key still prevents a second execution forrpc.idempotency_ttl_secs(24 hours); - a call that failed stored nothing, so retrying with the key runs it again.
If the server answers 500 erp.commit_unknown, the connection was lost while committing: retry with
the same key to learn the outcome. Keys are refused on read calls and from public and link callers.
Errors
Section titled “Errors”Error bodies keep Odoo’s shape: name, message, arguments, timestamp, context, debug, in that
order, with Odoo’s statuses and texts for Odoo’s exceptions and erp.* names for the server’s own
(the table is in docs/design/m3-rpc.md §11). debug is empty unless the operator turns on
rpc.error_debug and the user holds the capability rpc.debug_errors; even then it shows the error
chain, the SQLSTATE and the statement template, never values. A database error’s message names only
its SQLSTATE.
Import and export methods
Section titled “Import and export methods”Link erp-data to contribute load, export_data, and get_import_templates through the existing
erp_orm::rpc::RPC_IMPLS registration slice (ADR 0038). These are framework methods inherited by
every model. The registration’s base addon label is framework ownership: ERPForAll has no separate
base_import addon yet. Odoo adds get_import_templates by extending base from that addon
(odoo/addons/base_import/models/base_import.py:84-94). Its default result, and ours, is [].
All three methods have effect write, so a read-only API key cannot call them. load and
get_import_templates are model methods (empty ids); export_data takes record ids. This follows
Odoo’s model decorators and absence of @api.readonly on these methods
(odoo/odoo/orm/models.py:924-964, odoo/addons/base_import/models/base_import.py:84-94). Export can
create external identifiers, so callers must treat it as a write.
JSON-2 bodies use keyword arguments:
{"fields":["name"],"data":[["Example"]]}Send that body to /erp/json/2/<model>/load. Its result contains ids, messages, and nextrow;
row-level import failures are reported in messages. The RPC contract deliberately requires string
cells: a non-string cell fails binding before any row is read, with its zero-based row and column.
The resource contract caps a call at 1,000 columns and 1,000,000 rows. The configured whole-request
limits.rpc_body_bytes check runs before parsing and bounds both individual cells and aggregate
string bytes (default 2 MiB, configurable from 64 KiB through 128 MiB); there are no additional fixed
cell/matrix byte caps. Column and row limit refusals are validation errors; an oversized whole request
is refused as HTTP 413.
For /erp/json/2/<model>/export_data, send:
{"ids":[7],"fields_to_export":["id","name"]}The result is {"datas": [...]}. At most 1,000 export fields are accepted. Export requires superuser
mode, the export group base.group_allow_export, or the admin group base.group_erp_manager, as well
as the model’s read access. Group lookup errors propagate; user ids are not an authorization policy.
These rights follow Odoo’s export check and admin definition
(odoo/odoo/orm/models.py:937-940, odoo/odoo/orm/environments.py:182-185,
odoo/odoo/addons/base/models/res_users.py:1292-1294).
For /erp/json/2/<model>/get_import_templates, send {}. The framework default returns an empty list;
addons may override it through the existing RPC override mechanism.
Native browser credential adapter
Section titled “Native browser credential adapter”The trusted native HTTP root attaches RpcCredential with RpcCall::credential. Each RPC attempt
opens a fresh session transaction on the primary with the supplied CredentialOptions, exact context
and read entry. Returning an elevated principal, another registry, a nonprimary transaction or a
changed intent/context is a Programming error. Current resolved groups/companies govern gates,
record access and idempotent replay; an earlier transport principal is only an identity precheck.
Credential calls conceal error-debug details. Addon RPC methods continue using their supplied
transaction and normal ORM access; they do not construct credentials or open nested transactions.
Action and view metadata bundle
Section titled “Action and view metadata bundle”ir.actions.act_window.erp_load_web_action_views is a Read method (ADR 0100).
Pass ids: [action_id], wire_major: 1, and options: {mobile: false} with
normal caller context. It returns {action, views}: the same WindowAction and
ViewDescription as the separate action and model get_views calls. The server
derives the view requests from the authorized action and performs both reads in
the caller’s transaction. Action/model access, company and field restrictions,
view admission and metadata bounds still apply. Any failure rejects the whole
call; no successful action prefix is returned. Record data is requested separately.
Existing erp_load_web_action and get_views calls remain available, including
action-only related-record discovery. erp_load_web_action_ref (a model method, no
ids) takes xml_id: "module.name" and returns the same window action after the same
checks; an unknown XML id, a non-window-action XML id and an unreadable action get one
identical refusal (Dashboard cards). The human client shares bundle loads for
navigation and prefetch, seeds the page-local action/view cache and discards late
seeding after metadata invalidation. Failed bundle loads are retried only by a
subsequent explicit read/navigation.
The Rust schema root is erp_views::wire::WindowActionViews. The existing
crates/erp-views/examples/human_ui_schema.rs generator owns its TypeScript
representation in addons/web/static/src/generated/human-ui.ts. Regenerate on an
approved build host with:
cargo run --locked -p erp-views --features schema-gen --example human_ui_schema -- addons/web/static/src/generated/human-ui.tsSearch-panel data reads
Section titled “Search-panel data reads”The ordinary model Read methods search_panel_select_range and
search_panel_select_multi_range accept field_name and optional search/category/filter/comodel
domains. They are model calls: omit ids. Native clients use the ordinary authenticated JSON-2
route, for example POST /erp/json/2/<model>/search_panel_select_range with
{"field_name":"state","expand":true,"enable_counters":true}.
Range responses carry parent_field and values; multi-range responses carry values. With
counters enabled, entries include __count. Categories can carry the comodel’s parent link;
relational filters can request a group_by field. Every source field, comodel field, category
record and counted source record remains subject to the request’s access and company policy.
Native user API keys call these methods under their resolved subject authority. Native user keys
currently inherit the subject scope; restricted/read-only native keys remain unavailable until
scoped principals exist. A synthetic read-only RPC principal is a separate dispatcher-level contract.
A missing, null, false or zero display limit means no display truncation. Reaching a positive
limit returns {"error_msg":"Too many items to display."}. This is a display result, not a
permission to disable request/work safety bounds. Counter queries apply the complete admitted
domain; a display limit does not limit their input rows.
For many2many grouping, group_domain keys encode JSON scalar group identities. Malformed maps,
compound/null identities and equivalent duplicate keys are rejected; at most 64 map entries are
admitted. Many2one grouping uses a domain instead. Unknown parameters, wrong types, inaccessible
fields and malformed restrictions fail explicitly. Backend data availability does not imply that
the current human client renders every panel section: its existing static selection subset and
unsupported-feature notices remain documented separately.
HTML validation and reports
Section titled “HTML validation and reports”ADR 0152 adds a top-level html_validation transport control. Omit it to preserve the
ordinary success shape and use Strict HTML admission: policy removals refuse the write.
Send "html_validation":"clean" to accept policy cleaning with diagnostics, or "strict"
to request strict validation with the report envelope. This never changes a field’s policy
or access rights. Do not put the control in context or a model method signature.
Explicit controls return {"result": <ordinary result>, "html_reports": [...]} on success.
Consume the reports even when the operation succeeded. Each report identifies model,
field, nullable language, total_count and entries; entries carry kind, name,
reason, count, and sample node ordinals in sample_locations. No rejected body, URL or
attribute value is included. Strict DisallowedContent errors use the normal error response
with an additive html_reports member, not a successful result envelope.
The envelope counts toward limits.rpc_result_bytes. Exceeding it rolls back the call.
Reports include stored computations flushed before commit and are published only after a
successful commit. Idempotent replay returns the original report bytes; changing the control
with the same key is a request mismatch. Requests without the control retain their historical
digest representation for recovery. Managed password operations refuse the control explicitly.
This protocol is an integration candidate until its release notes record deployment. The HTML field guide describes the host API and remaining preset, property, import and mail integration boundaries.
Exact bigint values
Section titled “Exact bigint values”The bigint field type (ADR 0210) uses canonical signed decimal JSON strings on input and output: "0", "9007199254740993" or "-9223372036854775808". Use the string directly, or an exact bigint facility in the integration; converting it to JavaScript Number can lose information. Read/create/write/search_read and nested typed results preserve the string representation.
Safe JSON integers in ±(2^53−1) are also accepted as field input. Larger numeric tokens, floats, noncanonical decimal text and values outside signed i64 receive a validation error naming the field. Existing integer and record-id contracts are unchanged. Domain operands for large bigint values are decimal strings and compare numerically. Metadata reports type = "bigint", sortable true and groupable false; grouping and aggregation are unavailable in this scalar delivery. Frozen WASM ABI1 refuses bigint operations rather than erasing the native type.