Remote Procedure Calls
Remote procedure calls (RPC) are how clients communicate with actors. RPCs are as simple as writing a method on the actor class and then calling it from the client.
Performance
RPCs are very lightweight. They can be called hundreds of times per second to send realtime data to the actor.
Writing RPCs
RPCs can be written as native JavaScript methods on the actor class.
For example, the multiplyByTwo
method is written as:
Private Methods
Methods starting with _
or #
(e.g. _myMethod
and #myMethod
) are private and cannot be called by clients.
All Rivet-provided methods start with _
(e.g. _broadcast
) so clients cannot call them.
For example:
Streaming Return Data
RPCs have a single return value. In order to stream realtime data in response to an RPC, use events.
Calling RPCs
Calling RPCs is as simple as calling any other JavaScript function.
Note
Calling RPCs from the client are async and require an await
, even if the actor's method is not async.
Type Safety
The Rivet client includes type safety out of the box. The first generic parameter in get<Actor>(...)
defines the actor class. You can safely import the actor's type with import type
in to the client, like this:
Error Handling
Rivet provides robust error handling out of the box for RPCs.
User Errors
UserError
error can be used to return rich error data to the client. You can provide:
- A human-readable message
- A machine-readable code that's useful for matching errors in a try-catch (optional)
- A metadata object for providing richer error context (optional)
For example:
Read the documentation for UserError
here.
Internal Errors
All other errors will return an error with the code internal_error
to the client. This helps keep your application secure, as errors can sometimes expose sensitive information.
Schema Validation
Data schemas are not validated by default. For production applications, use a library like zod to validate input types.
In the previous example, providing a non-number value to count
could corrupt the actor's state (e.g. by passing a string instead of a number). For example, to validate the increment
request schema:
Authentication
By default, clients can call all RPCs on an actor without restriction. Make sure to implement authentication if needed. Documentation on authentication is available here.