openfga-client 0.6.0

Type-safe client SDK for OpenFGA with optional Authorization Model management and Authentication (Bearer or Client Credentials).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

use async_stream::stream;
use futures::{StreamExt, pin_mut};
use tonic::codegen::{Body, Bytes, StdError};

use crate::{
    client::{
        BatchCheckItem, BatchCheckRequest, CheckRequest, CheckRequestTupleKey,
        ConsistencyPreference, ContextualTupleKeys, ExpandRequest, ExpandRequestTupleKey,
        ListObjectsRequest, ListObjectsResponse, OpenFgaServiceClient, ReadRequest,
        ReadRequestTupleKey, ReadResponse, Tuple, TupleKey, TupleKeyWithoutCondition, UsersetTree,
        WriteRequest, WriteRequestDeletes, WriteRequestWrites,
        batch_check_single_result::CheckResult,
    },
    error::{Error, Result},
};

const DEFAULT_MAX_TUPLES_PER_WRITE: i32 = 100;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// Behavior when encountering conflicts during write operations.
///
/// See [OpenFGA documentation](https://openfga.dev/docs/getting-started/update-tuples#05-ignoring-duplicate-or-missing-tuples)
/// for more details.
pub enum ConflictBehavior {
    /// Fail the operation on conflict (default behavior).
    #[default]
    Fail,
    /// Ignore conflicts and continue processing.
    Ignore,
}

impl ConflictBehavior {
    fn as_str(&self) -> &str {
        match self {
            ConflictBehavior::Fail => "",
            ConflictBehavior::Ignore => "ignore",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Options for write operations.
///
/// This allows you to control how OpenFGA handles duplicate writes and missing deletes.
/// See [OpenFGA documentation](https://openfga.dev/docs/getting-started/update-tuples#05-ignoring-duplicate-or-missing-tuples)
/// for more details.
pub struct WriteOptions {
    /// Behavior when writing a tuple that already exists.
    pub on_duplicate: ConflictBehavior,
    /// Behavior when deleting a tuple that doesn't exist.
    pub on_missing: ConflictBehavior,
}

impl WriteOptions {
    #[must_use]
    pub fn new_idempotent() -> Self {
        Self {
            on_duplicate: ConflictBehavior::Ignore,
            on_missing: ConflictBehavior::Ignore,
        }
    }
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self {
            on_duplicate: ConflictBehavior::Fail,
            on_missing: ConflictBehavior::Fail,
        }
    }
}

#[derive(Clone, Debug)]
/// 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
///
/// ```no_run
/// 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(())
/// }
/// ```
pub struct OpenFgaClient<T> {
    client: OpenFgaServiceClient<T>,
    inner: Arc<ModelClientInner>,
}

#[derive(Debug, Clone)]
struct ModelClientInner {
    store_id: String,
    authorization_model_id: String,
    max_tuples_per_write: i32,
    consistency: ConsistencyPreference,
}

#[cfg(feature = "auth-middle")]
/// Specialization of the [`OpenFgaClient`] that includes optional
/// authentication with pre-shared keys (Bearer tokens) or client credentials.
/// For more fine-granular control, construct [`OpenFgaClient`] directly
/// with a custom [`OpenFgaServiceClient`].
pub type BasicOpenFgaClient = OpenFgaClient<crate::client::BasicAuthLayer>;

impl<T> OpenFgaClient<T>
where
    T: tonic::client::GrpcService<tonic::body::Body>,
    T::Error: Into<StdError>,
    T::ResponseBody: Body<Data = Bytes> + Send + 'static,
    <T::ResponseBody as Body>::Error: Into<StdError> + Send,
    T: Clone,
{
    /// Create a new `OpenFgaModelClient` with the given `store_id` and `authorization_model_id`.
    #[must_use]
    pub fn new(
        client: OpenFgaServiceClient<T>,
        store_id: &str,
        authorization_model_id: &str,
    ) -> Self {
        OpenFgaClient {
            client,
            inner: Arc::new(ModelClientInner {
                store_id: store_id.to_string(),
                authorization_model_id: authorization_model_id.to_string(),
                max_tuples_per_write: DEFAULT_MAX_TUPLES_PER_WRITE,
                consistency: ConsistencyPreference::MinimizeLatency,
            }),
        }
    }

    /// Set the `max_tuples_per_write` for the client.
    #[must_use]
    pub fn set_max_tuples_per_write(mut self, max_tuples_per_write: i32) -> Self {
        let inner = Arc::unwrap_or_clone(self.inner);
        self.inner = Arc::new(ModelClientInner {
            store_id: inner.store_id,
            authorization_model_id: inner.authorization_model_id,
            max_tuples_per_write,
            consistency: inner.consistency,
        });
        self
    }

    /// Set the `consistency` for the client.
    #[must_use]
    pub fn set_consistency(mut self, consistency: impl Into<ConsistencyPreference>) -> Self {
        let inner = Arc::unwrap_or_clone(self.inner);
        self.inner = Arc::new(ModelClientInner {
            store_id: inner.store_id,
            authorization_model_id: inner.authorization_model_id,
            max_tuples_per_write: inner.max_tuples_per_write,
            consistency: consistency.into(),
        });
        self
    }

    /// Get the `store_id` of the client.
    pub fn store_id(&self) -> &str {
        &self.inner.store_id
    }

    /// Get the `authorization_model_id` of the client.
    pub fn authorization_model_id(&self) -> &str {
        &self.inner.authorization_model_id
    }

    /// Get the `max_tuples_per_write` of the client.
    pub fn max_tuples_per_write(&self) -> i32 {
        self.inner.max_tuples_per_write
    }

    /// Get the underlying `OpenFgaServiceClient`.
    pub fn client(&self) -> OpenFgaServiceClient<T> {
        self.client.clone()
    }

    /// Get the `consistency` of the client.
    pub fn consistency(&self) -> ConsistencyPreference {
        self.inner.consistency
    }

    /// 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
    /// * [`Error::TooManyWrites`] if the number of writes and deletes exceeds `max_tuples_per_write`
    /// * [`Error::RequestFailed`] if the write request fails
    ///
    pub async fn write(
        &self,
        writes: impl Into<Option<Vec<TupleKey>>>,
        deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>,
    ) -> Result<()> {
        self.write_with_options(writes, deletes, WriteOptions::default())
            .await
    }

    /// 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
    ///
    /// ```no_run
    /// 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::TooManyWrites`] if the number of writes and deletes exceeds `max_tuples_per_write`
    /// * [`Error::RequestFailed`] if the write request fails
    ///
    pub async fn write_with_options(
        &self,
        writes: impl Into<Option<Vec<TupleKey>>>,
        deletes: impl Into<Option<Vec<TupleKeyWithoutCondition>>>,
        options: WriteOptions,
    ) -> Result<()> {
        let writes = writes.into().and_then(|w| (!w.is_empty()).then_some(w));
        let deletes = deletes.into().and_then(|d| (!d.is_empty()).then_some(d));

        if writes.is_none() && deletes.is_none() {
            return Ok(());
        }

        let num_writes_and_deletes = i32::try_from(
            #[allow(clippy::manual_saturating_arithmetic)]
            writes
                .as_ref()
                .map_or(0, Vec::len)
                .checked_add(deletes.as_ref().map_or(0, Vec::len))
                .unwrap_or(usize::MAX),
        )
        .unwrap_or(i32::MAX);

        if num_writes_and_deletes > self.max_tuples_per_write() {
            tracing::error!(
                "Too many writes and deletes in single OpenFGA transaction (actual) {} > {} (max)",
                num_writes_and_deletes,
                self.max_tuples_per_write()
            );
            return Err(Error::TooManyWrites {
                actual: num_writes_and_deletes,
                max: self.max_tuples_per_write(),
            });
        }

        let write_request = WriteRequest {
            store_id: self.store_id().to_string(),
            writes: writes.map(|writes| WriteRequestWrites {
                tuple_keys: writes,
                on_duplicate: options.on_duplicate.as_str().to_string(),
            }),
            deletes: deletes.map(|deletes| WriteRequestDeletes {
                on_missing: options.on_missing.as_str().to_string(),
                tuple_keys: deletes,
            }),
            authorization_model_id: self.authorization_model_id().to_string(),
        };

        self.client
            .clone()
            .write(write_request.clone())
            .await
            .map_err(|e| {
                let write_request_debug = format!("{write_request:?}");
                tracing::error!(
                    "Write request failed with status {e}. Request: {write_request_debug}"
                );
                Error::RequestFailed(Box::new(e))
            })
            .map(|_| ())
    }

    /// Read tuples from OpenFGA, single page.
    ///
    /// `tuple_key` may be:
    ///
    /// * A specific [`ReadRequestTupleKey`] — returns tuples matching that
    ///   filter. The OpenFGA server requires the filter to specify either a
    ///   non-empty `user` or a non-empty object id (a bare `"type:"` prefix is
    ///   *not* enough on its own).
    /// * `None` — returns **every tuple in the store**, no filter applied.
    ///   This is the same primitive used by the OpenFGA CLI's
    ///   `fga store export` and is the only way to enumerate tuples without
    ///   already knowing every user/object id.
    ///
    /// Note that OpenFGA's `Read` RPC caps `page_size` at 100 (proto-level
    /// validation, not configurable). Larger requested values are rejected.
    ///
    /// This is a wrapper around [`OpenFgaServiceClient::read`] that:
    ///
    /// * Traces any errors that occur
    /// * Enriches the error with the `read_request` that caused the error
    ///
    /// # Example
    ///
    /// ```no_run
    /// use openfga_client::client::{OpenFgaClient, OpenFgaServiceClient, ReadRequestTupleKey};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let service_client = OpenFgaServiceClient::connect("http://localhost:8080").await?;
    /// let client = OpenFgaClient::new(service_client, "store_id", "model_id");
    ///
    /// // Filtered read — bare ReadRequestTupleKey is auto-wrapped via Into<Option<_>>.
    /// let _filtered = client
    ///     .read(
    ///         100,
    ///         ReadRequestTupleKey {
    ///             user: "user:alice".to_string(),
    ///             relation: "member".to_string(),
    ///             object: "team:".to_string(),
    ///         },
    ///         None::<String>,
    ///     )
    ///     .await?;
    ///
    /// // Unfiltered — pass `None` to enumerate everything in the store.
    /// let _all = client.read(100, None, None::<String>).await?;
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] if the read request fails
    pub async fn read(
        &self,
        page_size: i32,
        tuple_key: impl Into<Option<ReadRequestTupleKey>>,
        continuation_token: impl Into<Option<String>>,
    ) -> Result<tonic::Response<ReadResponse>> {
        let read_request = ReadRequest {
            store_id: self.store_id().to_string(),
            page_size: Some(page_size),
            continuation_token: continuation_token.into().unwrap_or_default(),
            tuple_key: tuple_key.into(),
            consistency: self.consistency().into(),
        };
        self.client
            .clone()
            .read(read_request.clone())
            .await
            .map_err(|e| {
                let read_request_debug = format!("{read_request:?}");
                tracing::error!(
                    "Read request failed with status {e}. Request: {read_request_debug}"
                );
                Error::RequestFailed(Box::new(e))
            })
    }

    /// Read all tuples, with pagination.
    ///
    /// `tuple` may be:
    ///
    /// * `Some(filter)` — returns tuples matching the filter (paginated). Same
    ///   server-side filter requirements as [`Self::read`].
    /// * `None` — **enumerates every tuple in the store**, paginating to
    ///   completion. This is the supported way to back up or audit a store and
    ///   is what the OpenFGA CLI's `fga store export` uses internally.
    ///
    /// For details on the other parameters, see
    /// [`OpenFgaServiceClient::read_all_pages`].
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] If a request to OpenFGA fails.
    /// * [`Error::TooManyPages`] If the number of pages read exceeds `max_pages`.
    ///
    pub async fn read_all_pages(
        &self,
        tuple: Option<impl Into<ReadRequestTupleKey>>,
        page_size: i32,
        max_pages: u32,
    ) -> Result<Vec<Tuple>> {
        let store_id = self.store_id().to_string();
        self.client
            .clone()
            .read_all_pages(&store_id, tuple, self.consistency(), page_size, max_pages)
            .await
    }

    /// Perform a check.
    /// Returns `true` if the check is allowed, `false` otherwise.
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] if the check request fails
    ///
    pub async fn check(
        &self,
        tuple_key: impl Into<CheckRequestTupleKey>,
        contextual_tuples: impl Into<Option<Vec<TupleKey>>>,
        context: impl Into<Option<prost_wkt_types::Struct>>,
        trace: bool,
    ) -> Result<bool> {
        let contextual_tuples = contextual_tuples
            .into()
            .and_then(|c| (!c.is_empty()).then_some(c))
            .map(|tuple_keys| ContextualTupleKeys { tuple_keys });

        let check_request = CheckRequest {
            store_id: self.store_id().to_string(),
            tuple_key: Some(tuple_key.into()),
            consistency: self.consistency().into(),
            contextual_tuples,
            authorization_model_id: self.authorization_model_id().to_string(),
            context: context.into(),
            trace,
        };
        let response = self
            .client
            .clone()
            .check(check_request.clone())
            .await
            .map_err(|e| {
                let check_request_debug = format!("{check_request:?}");
                tracing::error!(
                    "Check request failed with status {e}. Request: {check_request_debug}"
                );
                Error::RequestFailed(Box::new(e))
            })?;
        Ok(response.get_ref().allowed)
    }

    /// Check multiple tuples at once.
    /// Returned `HashMap` contains one key for each `correlation_id` in the input.
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] if the check request fails
    /// * [`Error::ExpectedOneof`] if the server unexpectedly returns `None` for one of the tuples
    ///   to check.
    pub async fn batch_check<I>(
        &self,
        checks: impl IntoIterator<Item = I>,
    ) -> Result<HashMap<String, CheckResult>>
    where
        I: Into<BatchCheckItem>,
    {
        let checks: Vec<BatchCheckItem> = checks.into_iter().map(Into::into).collect();
        let request = BatchCheckRequest {
            store_id: self.store_id().to_string(),
            checks,
            authorization_model_id: self.authorization_model_id().to_string(),
            consistency: self.consistency().into(),
        };

        let response = self
            .client
            .clone()
            .batch_check(request.clone())
            .await
            .map_err(|e| {
                let request_debug = format!("{request:?}");
                tracing::error!(
                    "Batch-Check request failed with status {e}. Request: {request_debug}"
                );
                Error::RequestFailed(Box::new(e))
            })?;

        let mut map = HashMap::new();
        for (k, v) in response.into_inner().result {
            match v.check_result {
                // The server should return `Some(_)` for every tuple to check.
                // `None` is not expected to occur, hence returning an error for the *entire*
                // batch request to keep the API simple.
                Some(v) => map.insert(k, v),
                None => return Err(Error::ExpectedOneof),
            };
        }
        Ok(map)
    }

    /// Expand all relationships in userset tree format.
    /// Useful to reason about and debug a certain relationship.
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] if the expand request fails
    ///
    pub async fn expand(
        &self,
        tuple_key: impl Into<ExpandRequestTupleKey>,
        contextual_tuples: impl Into<Option<Vec<TupleKey>>>,
    ) -> Result<Option<UsersetTree>> {
        let expand_request = ExpandRequest {
            store_id: self.store_id().to_string(),
            tuple_key: Some(tuple_key.into()),
            authorization_model_id: self.authorization_model_id().to_string(),
            consistency: self.consistency().into(),
            contextual_tuples: contextual_tuples
                .into()
                .map(|tuple_keys| ContextualTupleKeys { tuple_keys }),
        };
        let response = self
            .client
            .clone()
            .expand(expand_request.clone())
            .await
            .map_err(|e| {
                tracing::error!(
                    "Expand request failed with status {e}. Request: {expand_request:?}"
                );
                Error::RequestFailed(Box::new(e))
            })?;
        Ok(response.into_inner().tree)
    }

    /// Simplified version of [`Self::check`] without contextual tuples, context, or trace.
    ///
    /// # Errors
    /// Check the [`Self::check`] method for possible errors.
    pub async fn check_simple(&self, tuple_key: impl Into<CheckRequestTupleKey>) -> Result<bool> {
        self.check(tuple_key, None, None, false).await
    }

    /// List all objects of the given type that the user has a relation with.
    ///
    /// # Errors
    /// * [`Error::RequestFailed`] if the list-objects request fails
    pub async fn list_objects(
        &self,
        r#type: impl Into<String>,
        relation: impl Into<String>,
        user: impl Into<String>,
        contextual_tuples: impl Into<Option<Vec<TupleKey>>>,
        context: impl Into<Option<prost_wkt_types::Struct>>,
    ) -> Result<tonic::Response<ListObjectsResponse>> {
        let request = ListObjectsRequest {
            r#type: r#type.into(),
            relation: relation.into(),
            user: user.into(),
            authorization_model_id: self.authorization_model_id().to_string(),
            store_id: self.store_id().to_string(),
            consistency: self.consistency().into(),
            contextual_tuples: contextual_tuples
                .into()
                .map(|tuple_keys| ContextualTupleKeys { tuple_keys }),
            context: context.into(),
        };

        self.client
            .clone()
            .list_objects(request.clone())
            .await
            .map_err(|e| {
                tracing::error!(
                    "List-Objects request failed with status {e}. Request: {request:?}"
                );
                Error::RequestFailed(Box::new(e))
            })
    }

    /// 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::RequestFailed`] if a read or delete request fails
    ///
    pub async fn delete_relations_to_object(&self, object: &str) -> Result<()> {
        loop {
            self.delete_relations_to_object_inner(object)
                .await
                .inspect_err(|e| {
                    tracing::error!("Failed to delete relations to object {object}: {e}");
                })?;

            if self.exists_relation_to(object).await? {
                tracing::debug!(
                    "Some tuples for object {object} are still present after first sweep. Performing another deletion."
                );
            } else {
                tracing::debug!("Successfully deleted all relations to object {object}");
                break Ok(());
            }
        }
    }

    /// 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::RequestFailed`] if the read request fails
    pub async fn exists_relation_to(&self, object: &str) -> Result<bool> {
        let tuples = self.read_relations_to_object(object, None, 1).await?;
        Ok(!tuples.tuples.is_empty())
    }

    async fn read_relations_to_object(
        &self,
        object: &str,
        continuation_token: impl Into<Option<String>>,
        page_size: i32,
    ) -> Result<ReadResponse> {
        self.read(
            page_size,
            TupleKeyWithoutCondition {
                user: String::new(),
                relation: String::new(),
                object: object.to_string(),
            },
            continuation_token,
        )
        .await
        .map(tonic::Response::into_inner)
    }

    /// # Errors
    /// * [`Error::RequestFailed`] if a read or delete request fails
    ///
    async fn delete_relations_to_object_inner(&self, object: &str) -> Result<()> {
        let read_stream = stream! {
            let mut continuation_token = None;
            // We need to keep track of seen keys, as OpenFGA might return
            // duplicates even of `HigherConsistency`.
            let mut seen= HashSet::new();
            while continuation_token != Some(String::new()) {
                let response = self.read_relations_to_object(object, continuation_token, self.max_tuples_per_write()).await?;
                let keys = response.tuples.into_iter().filter_map(|t| t.key).filter(|k| !seen.contains(&(k.user.clone(), k.relation.clone()))).collect::<Vec<_>>();
                tracing::debug!("Read {} keys for object {object} that are up for deletion. Continuation token: {}", keys.len(), response.continuation_token);
                continuation_token = Some(response.continuation_token);
                seen.extend(keys.iter().map(|k| (k.user.clone(), k.relation.clone())));
                yield Result::Ok(keys);
            }
        };
        pin_mut!(read_stream);
        let mut read_tuples: Option<Vec<TupleKey>> = None;

        let delete_tuples = |t: Option<Vec<TupleKey>>| async {
            match t {
                Some(tuples) => {
                    tracing::debug!(
                        "Deleting {} tuples for object {object} that we haven't seen before.",
                        tuples.len()
                    );
                    self.write(
                        None,
                        Some(
                            tuples
                                .into_iter()
                                .map(|t| TupleKeyWithoutCondition {
                                    user: t.user,
                                    relation: t.relation,
                                    object: t.object,
                                })
                                .collect(),
                        ),
                    )
                    .await
                }
                None => Ok(()),
            }
        };

        loop {
            let next_future = read_stream.next();
            let deletion_future = delete_tuples(read_tuples.clone());

            let (tuples, delete) = futures::join!(next_future, deletion_future);
            delete?;

            if let Some(tuples) = tuples.transpose()? {
                read_tuples = (!tuples.is_empty()).then_some(tuples);
            } else {
                break Ok(());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use needs_env_var::needs_env_var;

    #[needs_env_var(TEST_OPENFGA_CLIENT_GRPC_URL)]
    mod openfga {
        use tracing_test::traced_test;

        use super::super::*;
        use crate::{
            client::{AuthorizationModel, Store},
            migration::test::openfga::service_client_with_store,
        };

        async fn write_custom_roles_model(
            client: &OpenFgaServiceClient<tonic::transport::Channel>,
            store: &Store,
        ) -> String {
            let model: AuthorizationModel = serde_json::from_str(include_str!(
                "../tests/sample-store/custom-roles/schema.json"
            ))
            .unwrap();
            client
                .clone()
                .write_authorization_model(model.into_write_request(store.id.clone()))
                .await
                .unwrap()
                .into_inner()
                .authorization_model_id
        }

        async fn get_client_with_custom_roles_model() -> OpenFgaClient<tonic::transport::Channel> {
            let (service_client, store) = service_client_with_store().await;
            let auth_model_id = write_custom_roles_model(&service_client, &store).await;

            OpenFgaClient::new(service_client, &store.id, auth_model_id.as_str())
        }

        /// Verifies that the single-page [`OpenFgaClient::read`] honours
        /// `tuple_key=None` as "no filter" and returns store-wide tuples,
        /// providing a continuation token when more pages are available.
        #[tokio::test]
        #[traced_test]
        async fn test_read_single_page_unfiltered() {
            let client = get_client_with_custom_roles_model().await;

            // Write 75 tuples — small enough to fit in one page of 100 but
            // larger than a page of 50 so we also exercise the continuation token.
            let total = 75;
            for i in 0..total {
                client
                    .write(
                        vec![TupleKey {
                            user: format!("user:user{i}"),
                            relation: "member".to_string(),
                            object: "team:team1".to_string(),
                            condition: None,
                        }],
                        None,
                    )
                    .await
                    .unwrap();
            }

            // page_size=100: one page, no continuation, all 75 returned.
            let resp = client
                .read(100, None, None::<String>)
                .await
                .expect("read with None tuple_key must succeed");
            let inner = resp.into_inner();
            assert_eq!(inner.tuples.len(), total);
            assert!(
                inner.continuation_token.is_empty(),
                "continuation token must be empty when all results fit in one page"
            );

            // page_size=50: first page returns 50, with a non-empty continuation.
            let resp = client
                .read(50, None, None::<String>)
                .await
                .expect("read with None tuple_key must succeed");
            let inner = resp.into_inner();
            assert_eq!(inner.tuples.len(), 50);
            assert!(
                !inner.continuation_token.is_empty(),
                "continuation token must be set when more pages are available"
            );

            // Follow the continuation; remaining 25 tuples come back, no further pages.
            let resp = client
                .read(50, None, Some(inner.continuation_token))
                .await
                .expect("read with continuation token must succeed");
            let inner = resp.into_inner();
            assert_eq!(inner.tuples.len(), total - 50);
            assert!(inner.continuation_token.is_empty());
        }

        /// Verifies that the bare-`ReadRequestTupleKey` call pattern (used
        /// throughout this codebase before the signature was widened to accept
        /// `Option<...>`) still compiles and works. Relies on the
        /// `T: Into<Option<T>>` blanket impl.
        #[tokio::test]
        #[traced_test]
        async fn test_read_single_page_filtered_backward_compat() {
            let client = get_client_with_custom_roles_model().await;

            client
                .write(
                    vec![
                        TupleKey {
                            user: "user:alice".to_string(),
                            relation: "member".to_string(),
                            object: "team:team1".to_string(),
                            condition: None,
                        },
                        TupleKey {
                            user: "user:bob".to_string(),
                            relation: "member".to_string(),
                            object: "team:team2".to_string(),
                            condition: None,
                        },
                    ],
                    None,
                )
                .await
                .unwrap();

            // Pass `ReadRequestTupleKey` directly — no `Some(...)` wrap.
            let resp = client
                .read(
                    100,
                    ReadRequestTupleKey {
                        user: String::new(),
                        relation: "member".to_string(),
                        object: "team:team1".to_string(),
                    },
                    None::<String>,
                )
                .await
                .unwrap();
            let inner = resp.into_inner();
            assert_eq!(inner.tuples.len(), 1);
            assert_eq!(inner.tuples[0].key.as_ref().unwrap().user, "user:alice");
        }

        /// Verifies that all pages are read when *not* passing a `ReadRequestTupleKey`.
        #[tokio::test]
        #[traced_test]
        async fn test_read_all_pages_empty_tuple() {
            let client = get_client_with_custom_roles_model().await;

            let loop_count = 100;
            let tuples_per_loop = 3;
            for i in 0..loop_count {
                // Write to different relations with different users and objects to test that an
                // empty ReadRequestTupleKey does not filter for anything.
                client
                    .write(
                        vec![
                            TupleKey {
                                user: format!("user:user{i}"),
                                relation: "member".to_string(),
                                object: "team:team1".to_string(),
                                condition: None,
                            },
                            TupleKey {
                                user: format!("role:role{i}#assignee"),
                                relation: "role_assigner".to_string(),
                                object: "org:org1".to_string(),
                                condition: None,
                            },
                            TupleKey {
                                user: format!("org:org{i}"),
                                relation: "org".to_string(),
                                object: "asset-category:ac{i}".to_string(),
                                condition: None,
                            },
                        ],
                        None,
                    )
                    .await
                    .unwrap();
            }

            let tuples = client
                .read_all_pages(None::<ReadRequestTupleKey>, 50, u32::MAX)
                .await
                .unwrap();
            assert_eq!(tuples.len(), loop_count * tuples_per_loop);
        }

        #[tokio::test]
        #[traced_test]
        async fn test_delete_relations_to_object() {
            let client = get_client_with_custom_roles_model().await;
            let object = "team:team1";

            assert!(!client.exists_relation_to(object).await.unwrap());

            client
                .write(
                    vec![TupleKey {
                        user: "user:user1".to_string(),
                        relation: "member".to_string(),
                        object: object.to_string(),
                        condition: None,
                    }],
                    None,
                )
                .await
                .unwrap();
            assert!(client.exists_relation_to(object).await.unwrap());
            client.delete_relations_to_object(object).await.unwrap();
            assert!(!client.exists_relation_to(object).await.unwrap());
        }

        #[tokio::test]
        #[traced_test]
        async fn test_delete_relations_to_object_usersets() {
            let client = get_client_with_custom_roles_model().await;
            let object: &str = "role:admin";

            assert!(!client.exists_relation_to(object).await.unwrap());

            client
                .write(
                    vec![TupleKey {
                        user: "team:team1#member".to_string(),
                        relation: "assignee".to_string(),
                        object: object.to_string(),
                        condition: None,
                    }],
                    None,
                )
                .await
                .unwrap();
            assert!(client.exists_relation_to(object).await.unwrap());
            client.delete_relations_to_object(object).await.unwrap();
            assert!(!client.exists_relation_to(object).await.unwrap());
        }

        #[tokio::test]
        #[traced_test]
        async fn test_delete_relations_to_object_empty() {
            let client = get_client_with_custom_roles_model().await;
            let object = "team:team1";

            assert!(!client.exists_relation_to(object).await.unwrap());
            client.delete_relations_to_object(object).await.unwrap();
            assert!(!client.exists_relation_to(object).await.unwrap());
        }

        #[tokio::test]
        #[traced_test]
        async fn test_delete_relations_to_object_many() {
            let client = get_client_with_custom_roles_model().await;
            let object = "org:org1";

            assert!(!client.exists_relation_to(object).await.unwrap());

            for i in 0..502 {
                client
                    .write(
                        vec![
                            TupleKey {
                                user: format!("user:user{i}"),
                                relation: "member".to_string(),
                                object: object.to_string(),
                                condition: None,
                            },
                            TupleKey {
                                user: format!("role:role{i}#assignee"),
                                relation: "role_assigner".to_string(),
                                object: object.to_string(),
                                condition: None,
                            },
                        ],
                        None,
                    )
                    .await
                    .unwrap();
            }

            // Also write a tuple for another org to make sure we don't delete those
            let object_2 = "org:org2";
            client
                .write(
                    vec![TupleKey {
                        user: "user:user1".to_string(),
                        relation: "owner".to_string(),
                        object: object_2.to_string(),
                        condition: None,
                    }],
                    None,
                )
                .await
                .unwrap();

            assert!(client.exists_relation_to(object).await.unwrap());
            assert!(client.exists_relation_to(object_2).await.unwrap());

            client.delete_relations_to_object(object).await.unwrap();

            assert!(!client.exists_relation_to(object).await.unwrap());
            assert!(client.exists_relation_to(object_2).await.unwrap());
            assert!(
                client
                    .check_simple(TupleKeyWithoutCondition {
                        user: "user:user1".to_string(),
                        relation: "role_assigner".to_string(),
                        object: object_2.to_string(),
                    })
                    .await
                    .unwrap()
            );
        }

        #[tokio::test]
        #[traced_test]
        async fn test_write_with_options_ignore_duplicate() {
            let client = get_client_with_custom_roles_model().await;
            let tuple = TupleKey {
                user: "user:user1".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
                condition: None,
            };

            // First write should succeed
            client
                .write_with_options(vec![tuple.clone()], None, WriteOptions::default())
                .await
                .unwrap();

            // Second write with default options should fail
            let result = client
                .write_with_options(vec![tuple.clone()], None, WriteOptions::default())
                .await;
            assert!(result.is_err());

            // Write with ignore duplicate should succeed
            let options = WriteOptions {
                on_duplicate: ConflictBehavior::Ignore,
                on_missing: ConflictBehavior::Fail,
            };
            client
                .write_with_options(vec![tuple], None, options)
                .await
                .unwrap();
        }

        #[tokio::test]
        #[traced_test]
        async fn test_write_with_options_ignore_missing() {
            let client = get_client_with_custom_roles_model().await;
            let tuple_key = TupleKeyWithoutCondition {
                user: "user:user1".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
            };

            // Delete non-existent tuple with default options should fail
            let result = client
                .write_with_options(None, vec![tuple_key.clone()], WriteOptions::default())
                .await;
            assert!(result.is_err());

            // Delete with ignore missing should succeed
            let options = WriteOptions {
                on_duplicate: ConflictBehavior::Fail,
                on_missing: ConflictBehavior::Ignore,
            };
            client
                .write_with_options(None, vec![tuple_key], options)
                .await
                .unwrap();
        }

        #[tokio::test]
        #[traced_test]
        async fn test_write_with_options_idempotent() {
            let client = get_client_with_custom_roles_model().await;
            let tuple = TupleKey {
                user: "user:user1".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
                condition: None,
            };

            let options = WriteOptions::new_idempotent();

            // Write twice with idempotent options should succeed both times
            client
                .write_with_options(vec![tuple.clone()], None, options)
                .await
                .unwrap();
            client
                .write_with_options(vec![tuple], None, options)
                .await
                .unwrap();

            // Delete non-existent tuple with idempotent options should succeed
            let tuple_key = TupleKeyWithoutCondition {
                user: "user:nonexistent".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
            };
            client
                .write_with_options(None, vec![tuple_key], options)
                .await
                .unwrap();
        }

        #[tokio::test]
        #[traced_test]
        #[allow(clippy::similar_names)]
        async fn test_write_with_options_mixed_operations() {
            let client = get_client_with_custom_roles_model().await;

            // First, write a tuple
            let tuple1 = TupleKey {
                user: "user:user1".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
                condition: None,
            };
            client.write(vec![tuple1.clone()], None).await.unwrap();

            // Now write a new tuple and delete the existing one in the same request
            let tuple2 = TupleKey {
                user: "user:user2".to_string(),
                relation: "member".to_string(),
                object: "team:team1".to_string(),
                condition: None,
            };
            let delete_key = TupleKeyWithoutCondition {
                user: tuple1.user,
                relation: tuple1.relation,
                object: tuple1.object,
            };

            client
                .write_with_options(vec![tuple2], vec![delete_key], WriteOptions::default())
                .await
                .unwrap();

            // Verify the old tuple is gone and the new one exists
            let tuples = client
                .read_all_pages(
                    Some(TupleKeyWithoutCondition {
                        user: String::new(),
                        relation: "member".to_string(),
                        object: "team:team1".to_string(),
                    }),
                    10,
                    10,
                )
                .await
                .unwrap();
            assert_eq!(tuples.len(), 1);
            assert_eq!(tuples[0].key.as_ref().unwrap().user, "user:user2");
        }

        #[tokio::test]
        #[traced_test]
        async fn test_write_with_options_empty_operations() {
            let client = get_client_with_custom_roles_model().await;

            // Writing with empty writes and deletes should succeed without making a request
            let result = client
                .write_with_options(
                    None::<Vec<TupleKey>>,
                    None::<Vec<TupleKeyWithoutCondition>>,
                    WriteOptions::default(),
                )
                .await;
            assert!(result.is_ok());
        }
    }
}