pub struct OpenFgaClient<T> { /* private fields */ }Expand description
Wrapper around the generated OpenFgaServiceClient.
Why you should use this wrapper:
- Handles the
store_idandauthorization_model_idfor you - you don’t need to pass them in every request - Applies the same configured
consistencyto 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 likeReadRequestTupleKey - 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,
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,
Sourcepub fn new(
client: OpenFgaServiceClient<T>,
store_id: &str,
authorization_model_id: &str,
) -> Self
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.
Sourcepub fn set_max_tuples_per_write(self, max_tuples_per_write: i32) -> Self
pub fn set_max_tuples_per_write(self, max_tuples_per_write: i32) -> Self
Set the max_tuples_per_write for the client.
Sourcepub fn set_consistency(
self,
consistency: impl Into<ConsistencyPreference>,
) -> Self
pub fn set_consistency( self, consistency: impl Into<ConsistencyPreference>, ) -> Self
Set the consistency for the client.
Get the authorization_model_id of the client.
Sourcepub fn max_tuples_per_write(&self) -> i32
pub fn max_tuples_per_write(&self) -> i32
Get the max_tuples_per_write of the client.
Sourcepub fn client(&self) -> OpenFgaServiceClient<T>
pub fn client(&self) -> OpenFgaServiceClient<T>
Get the underlying OpenFgaServiceClient.
Sourcepub fn consistency(&self) -> ConsistencyPreference
pub fn consistency(&self) -> ConsistencyPreference
Get the consistency of the client.
Sourcepub async fn write(
&self,
writes: impl Into<Option<Vec<TupleKey>>>,
deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>,
) -> Result<()>
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_requestthat 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
Error::TooManyWritesif the number of writes and deletes exceedsmax_tuples_per_writeError::RequestFailedif the write request fails
Sourcepub async fn write_with_options(
&self,
writes: impl Into<Option<Vec<TupleKey>>>,
deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>,
options: WriteOptions,
) -> Result<()>
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_requestthat 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
Error::TooManyWritesif the number of writes and deletes exceedsmax_tuples_per_writeError::RequestFailedif the write request fails
Sourcepub async fn read(
&self,
page_size: i32,
tuple_key: impl Into<ReadRequestTupleKey>,
continuation_token: impl Into<Option<String>>,
) -> Result<Response<ReadResponse>>
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_requestthat caused the error
§Errors
Error::RequestFailedif the read request fails
Sourcepub async fn read_all_pages(
&self,
tuple: Option<impl Into<ReadRequestTupleKey>>,
page_size: i32,
max_pages: u32,
) -> Result<Vec<Tuple>>
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
Error::RequestFailedIf a request to OpenFGA fails.Error::TooManyPagesIf the number of pages read exceedsmax_pages.
Sourcepub 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>
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
Error::RequestFailedif the check request fails
Sourcepub async fn batch_check<I>(
&self,
checks: impl IntoIterator<Item = I>,
) -> Result<HashMap<String, CheckResult>>where
I: Into<BatchCheckItem>,
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
Error::RequestFailedif the check request failsError::ExpectedOneofif the server unexpectedly returnsNonefor one of the tuples to check.
Sourcepub async fn expand(
&self,
tuple_key: impl Into<ExpandRequestTupleKey>,
contextual_tuples: impl Into<Option<Vec<TupleKey>>>,
) -> Result<Option<UsersetTree>>
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
Error::RequestFailedif the expand request fails
Sourcepub async fn check_simple(
&self,
tuple_key: impl Into<CheckRequestTupleKey>,
) -> Result<bool>
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.
Sourcepub 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>>
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
Error::RequestFailedif the list-objects request fails
Sourcepub async fn delete_relations_to_object(&self, object: &str) -> Result<()>
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
Error::RequestFailedif a read or delete request fails
Sourcepub async fn exists_relation_to(&self, object: &str) -> Result<bool>
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
Error::RequestFailedif the read request fails
Trait Implementations§
Source§impl<T: Clone> Clone for OpenFgaClient<T>
impl<T: Clone> Clone for OpenFgaClient<T>
Source§fn clone(&self) -> OpenFgaClient<T>
fn clone(&self) -> OpenFgaClient<T>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreAuto 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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request