Skip to main content

ReducerContext

Struct ReducerContext 

Source
#[non_exhaustive]
pub struct ReducerContext { pub timestamp: Timestamp, pub db: Local, /* private fields */ }
Expand description

The context that any reducer is provided with.

This must be the first argument of the reducer. Clients of the module will only see arguments after the ReducerContext.

Includes information about the client calling the reducer and the time of invocation, as well as a view into the module’s database.

If the crate was compiled with the rand feature, also includes faculties for random number generation.

Implements the DbContext trait for accessing views into a database.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§timestamp: Timestamp

The time at which the reducer was started.

§db: Local

Allows accessing the local database attached to a module.

This slightly strange type appears to have no methods, but that is misleading. The #[table] macro uses the trait system to add table accessors to this type. These are generated methods that allow you to access specific tables.

For a table named table, use ctx.db.{table}() to get a handle. For example:

use spacetimedb::{table, reducer, ReducerContext};

#[table(accessor = book)]
#[derive(Debug)]
struct Book {
    #[primary_key]
    id: u64,
    isbn: String,
    name: String,
    #[index(btree)]
    author: String
}

#[reducer]
fn find_books_by(ctx: &ReducerContext, author: String) {
    let book: &book__TableHandle = ctx.db.book();

    log::debug!("looking up books by {author}...");
    for book in book.author().filter(&author) {
        log::debug!("- {book:?}");
    }
}

See the #[table] macro for more information.

Implementations§

Source§

impl ReducerContext

Source

pub fn random<T>(&self) -> T

Generates a random value.

Similar to rand::random(), but using StdbRng instead.

See also ReducerContext::rng().

Source

pub fn rng(&self) -> &StdbRng

Retrieve the random number generator for this reducer transaction, seeded by the timestamp of the reducer call.

If you only need a single random value, you can use ReducerContext::random().

§Examples
use spacetimedb::{reducer, ReducerContext};
use rand::Rng;

#[spacetimedb::reducer]
fn rng_demo(ctx: &spacetimedb::ReducerContext) {
    // Can be used in method chaining style:
    let digit = ctx.rng().gen_range(0..=9);

    // Or, cache locally for reuse:
    let mut rng = ctx.rng();
    let floats: Vec<f32> = rng.sample_iter(rand::distributions::Standard).collect();
}

For more information, see StdbRng and rand::Rng.

Source§

impl ReducerContext

Source

pub fn sender(&self) -> Identity

The Identity of the client that invoked the reducer.

Source

pub fn connection_id(&self) -> Option<ConnectionId>

The ConnectionId of the client that invoked the reducer.

Will be None for certain reducers invoked automatically by the host, including init and scheduled reducers.

Source

pub fn sender_auth(&self) -> &AuthCtx

Returns the authorization information for the caller of this reducer.

Source

pub fn identity(&self) -> Identity

Read the current module’s Identity.

Source

pub fn as_anonymous_read_only(&self) -> AnonymousViewContext

Create an anonymous (no sender) read-only view context

Source

pub fn as_read_only(&self) -> ViewContext

Create a sender-bound read-only view context using this reducer’s caller.

Source

pub fn new_uuid_v4(&self) -> Result<Uuid>

Create a new random Uuid v4 using the built-in RNG.

§Example
use spacetimedb::{reducer, ReducerContext, Uuid};

#[reducer]
fn generate_uuid_v4(ctx: &ReducerContext) -> Uuid {
    let uuid = ctx.new_uuid_v4();
    log::info!(uuid);
}
Source

pub fn new_uuid_v7(&self) -> Result<Uuid>

Create a new sortable Uuid v7 using the built-in RNG, counter and timestamp.

§Example
use spacetimedb::{reducer, ReducerContext, Uuid};

#[reducer]
fn generate_uuid_v7(ctx: &ReducerContext) -> Result<Uuid, Box<dyn std::error::Error>> {
    let uuid = ctx.new_uuid_v7()?;
    log::info!(uuid);
}

Trait Implementations§

Source§

impl DbContext for ReducerContext

Source§

type DbView = Local

A view into the tables of a database. Read more
Source§

fn db(&self) -> &Self::DbView

Get a view into the tables. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V