OpenFgaClient

Struct OpenFgaClient 

Source
pub struct OpenFgaClient<T> { /* private fields */ }
Expand description

Wrapper around the generated OpenFgaServiceClient.

Why you should use this wrapper:

  • Handles the store_id and authorization_model_id for you - you don’t need to pass them in every request
  • Applies the same configured consistency to all requests
  • Ensures the number of writes and deletes does not exceed OpenFGA’s limit
  • Uses tracing to log errors
  • Never sends empty writes or deletes, which fails on OpenFGA
  • Uses impl Into<ReadRequestTupleKey> arguments instead of very specific types like ReadRequestTupleKey
  • Most methods don’t require mutable access to the client. Cloning tonic clients is cheap.
  • If a method is missing, the OpenFgaClient::client() provides access to the underlying client with full control

§Example

use openfga_client::client::{OpenFgaServiceClient, OpenFgaClient};
use tonic::transport::Channel;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let endpoint = "http://localhost:8080";
    let service_client = OpenFgaServiceClient::connect(endpoint).await?;
    let client = OpenFgaClient::new(service_client, "<store_id>", "<authorization_model_id>");

    // Use the client to interact with OpenFGA
    Ok(())
}

Implementations§

Source§

impl<T> OpenFgaClient<T>
where T: GrpcService<Body> + Clone, T::Error: Into<StdError>, T::ResponseBody: Body<Data = Bytes> + Send + 'static, <T::ResponseBody as Body>::Error: Into<StdError> + Send,

Source

pub fn new( client: OpenFgaServiceClient<T>, store_id: &str, authorization_model_id: &str, ) -> Self

Create a new OpenFgaModelClient with the given store_id and authorization_model_id.

Source

pub fn set_max_tuples_per_write(self, max_tuples_per_write: i32) -> Self

Set the max_tuples_per_write for the client.

Source

pub fn set_consistency( self, consistency: impl Into<ConsistencyPreference>, ) -> Self

Set the consistency for the client.

Source

pub fn store_id(&self) -> &str

Get the store_id of the client.

Source

pub fn authorization_model_id(&self) -> &str

Get the authorization_model_id of the client.

Source

pub fn max_tuples_per_write(&self) -> i32

Get the max_tuples_per_write of the client.

Source

pub fn client(&self) -> OpenFgaServiceClient<T>

Get the underlying OpenFgaServiceClient.

Source

pub fn consistency(&self) -> ConsistencyPreference

Get the consistency of the client.

Source

pub async fn write( &self, writes: impl Into<Option<Vec<TupleKey>>>, deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>, ) -> Result<()>

Write or delete tuples from FGA. This is a wrapper around OpenFgaServiceClient::write that ensures that:

  • Ensures the number of writes and deletes does not exceed OpenFGA’s limit
  • Does not send empty writes or deletes
  • Traces any errors that occur
  • Enriches the error with the write_request that caused the error

All writes happen in a single transaction.

OpenFGA currently has a default limit of 100 tuples per write (sum of writes and deletes).

This write method will fail if the number of writes and deletes exceeds max_tuples_per_write which defaults to 100. To change this limit, use Self::set_max_tuples_per_write.

§Errors
Source

pub async fn write_with_options( &self, writes: impl Into<Option<Vec<TupleKey>>>, deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>, options: WriteOptions, ) -> Result<()>

Write or delete tuples from FGA with custom conflict handling options. This is a wrapper around OpenFgaServiceClient::write that ensures that:

  • Ensures the number of writes and deletes does not exceed OpenFGA’s limit
  • Does not send empty writes or deletes
  • Traces any errors that occur
  • Enriches the error with the write_request that caused the error
  • Allows configuring behavior for duplicate writes and missing deletes

All writes happen in a single transaction.

OpenFGA currently has a default limit of 100 tuples per write (sum of writes and deletes).

This write_with_options method will fail if the number of writes and deletes exceeds max_tuples_per_write which defaults to 100. To change this limit, use Self::set_max_tuples_per_write.

§Example
use openfga_client::client::{ConflictBehavior, WriteOptions, OpenFgaClient, OpenFgaServiceClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let endpoint = "http://localhost:8080";
    let service_client = OpenFgaServiceClient::connect(endpoint).await?;
    let client = OpenFgaClient::new(service_client, "store_id", "model_id");
     
    let options = WriteOptions {
        on_duplicate: ConflictBehavior::Ignore,
        on_missing: ConflictBehavior::Ignore,
    };

    let writes = vec![/* TupleKey instances */];
    client.write_with_options(writes, None, options).await?;
    Ok(())
}
§Errors
Source

pub async fn read( &self, page_size: i32, tuple_key: impl Into<ReadRequestTupleKey>, continuation_token: impl Into<Option<String>>, ) -> Result<Response<ReadResponse>>

Read tuples from OpenFGA. This is a wrapper around OpenFgaServiceClient::read that:

  • Traces any errors that occur
  • Enriches the error with the read_request that caused the error
§Errors
Source

pub async fn read_all_pages( &self, tuple: Option<impl Into<ReadRequestTupleKey>>, page_size: i32, max_pages: u32, ) -> Result<Vec<Tuple>>

Read all tuples, with pagination. For details on the parameters, see OpenFgaServiceClient::read_all_pages.

§Errors
Source

pub async fn check( &self, tuple_key: impl Into<CheckRequestTupleKey>, contextual_tuples: impl Into<Option<Vec<TupleKey>>>, context: impl Into<Option<Struct>>, trace: bool, ) -> Result<bool>

Perform a check. Returns true if the check is allowed, false otherwise.

§Errors
Source

pub async fn batch_check<I>( &self, checks: impl IntoIterator<Item = I>, ) -> Result<HashMap<String, CheckResult>>
where I: Into<BatchCheckItem>,

Check multiple tuples at once. Returned HashMap contains one key for each correlation_id in the input.

§Errors
Source

pub async fn expand( &self, tuple_key: impl Into<ExpandRequestTupleKey>, contextual_tuples: impl Into<Option<Vec<TupleKey>>>, ) -> Result<Option<UsersetTree>>

Expand all relationships in userset tree format. Useful to reason about and debug a certain relationship.

§Errors
Source

pub async fn check_simple( &self, tuple_key: impl Into<CheckRequestTupleKey>, ) -> Result<bool>

Simplified version of Self::check without contextual tuples, context, or trace.

§Errors

Check the Self::check method for possible errors.

Source

pub async fn list_objects( &self, type: impl Into<String>, relation: impl Into<String>, user: impl Into<String>, contextual_tuples: impl Into<Option<Vec<TupleKey>>>, context: impl Into<Option<Struct>>, ) -> Result<Response<ListObjectsResponse>>

List all objects of the given type that the user has a relation with.

§Errors
Source

pub async fn delete_relations_to_object(&self, object: &str) -> Result<()>

Delete all relations that other entities have to the given object, that is, all tuples with the “object” field set to the given object.

This method uses streamed pagination internally, so that also large amounts of tuples can be deleted. Please not that this method does not delete tuples where the given object has a relation TO another entity.

Iteration is stopped when no more tuples are returned from OpenFGA.

§Errors
Source

pub async fn exists_relation_to(&self, object: &str) -> Result<bool>

Check if any direct relation to the given object exists. This does not check if the object is used as a user in relations to other objects.

§Errors

Trait Implementations§

Source§

impl<T: Clone> Clone for OpenFgaClient<T>

Source§

fn clone(&self) -> OpenFgaClient<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for OpenFgaClient<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> !Freeze for OpenFgaClient<T>

§

impl<T> RefUnwindSafe for OpenFgaClient<T>
where T: RefUnwindSafe,

§

impl<T> Send for OpenFgaClient<T>
where T: Send,

§

impl<T> Sync for OpenFgaClient<T>
where T: Sync,

§

impl<T> Unpin for OpenFgaClient<T>
where T: Unpin,

§

impl<T> UnwindSafe for OpenFgaClient<T>
where T: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more