-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathOpenFgaClient.java
More file actions
1495 lines (1311 loc) · 67.2 KB
/
Copy pathOpenFgaClient.java
File metadata and controls
1495 lines (1311 loc) · 67.2 KB
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
package dev.openfga.sdk.api.client;
import static dev.openfga.sdk.util.StringUtil.isNullOrWhitespace;
import static java.util.UUID.randomUUID;
import dev.openfga.sdk.api.*;
import dev.openfga.sdk.api.client.model.*;
import dev.openfga.sdk.api.configuration.*;
import dev.openfga.sdk.api.model.*;
import dev.openfga.sdk.constants.FgaConstants;
import dev.openfga.sdk.errors.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class OpenFgaClient {
private final ApiClient apiClient;
private ClientConfiguration configuration;
private OpenFgaApi api;
public OpenFgaClient(ClientConfiguration configuration) throws FgaInvalidParameterException {
this(configuration, new ApiClient());
}
public OpenFgaClient(ClientConfiguration configuration, ApiClient apiClient) throws FgaInvalidParameterException {
this.apiClient = apiClient;
this.configuration = configuration;
this.api = new OpenFgaApi(configuration, apiClient);
}
/* ***********
* Utilities *
*************/
/**
* Returns the underlying low-level OpenFgaApi instance.
*/
public OpenFgaApi getApi() {
return api;
}
/**
* Returns an ApiExecutor instance for executing HTTP requests to arbitrary OpenFGA endpoints.
* Requests automatically include authentication, retry logic, error handling, and configured timeouts/headers.
*
* <p>Example:</p>
* <pre>{@code
* ApiExecutorRequestBuilder request = ApiExecutorRequestBuilder.builder("POST", "/stores/{store_id}/endpoint")
* .pathParam("store_id", storeId)
* .body(requestData);
*
* client.apiExecutor().send(request, ResponseType.class)
* .thenAccept(response -> handleResponse(response.getData()));
* }</pre>
*
* @return ApiExecutor instance
*/
public ApiExecutor apiExecutor() {
return new ApiExecutor(this.apiClient, this.configuration);
}
public void setStoreId(String storeId) {
configuration.storeId(storeId);
}
public void setAuthorizationModelId(String authorizationModelId) {
configuration.authorizationModelId(authorizationModelId);
}
public void setConfiguration(ClientConfiguration configuration) throws FgaInvalidParameterException {
this.configuration = configuration;
this.api = new OpenFgaApi(configuration, apiClient);
}
/* ********
* Stores *
**********/
/**
* ListStores - Get a paginated list of stores.
*/
public CompletableFuture<ClientListStoresResponse> listStores() throws FgaInvalidParameterException {
configuration.assertValid();
return call(() -> api.listStores(null, null, null)).thenApply(ClientListStoresResponse::new);
}
/**
* ListStores - Get a paginated list of stores.
*/
public CompletableFuture<ClientListStoresResponse> listStores(ClientListStoresOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.listStores(
options.getPageSize(), options.getContinuationToken(), options.getName(), overrides))
.thenApply(ClientListStoresResponse::new);
}
/**
* CreateStore - Initialize a store
*/
public CompletableFuture<ClientCreateStoreResponse> createStore(CreateStoreRequest request)
throws FgaInvalidParameterException {
return createStore(request, null);
}
/**
* CreateStore - Initialize a store
*/
public CompletableFuture<ClientCreateStoreResponse> createStore(
CreateStoreRequest request, ClientCreateStoreOptions options) throws FgaInvalidParameterException {
configuration.assertValid();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.createStore(request, overrides)).thenApply(ClientCreateStoreResponse::new);
}
/**
* GetStore - Get information about the current store.
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientGetStoreResponse> getStore() throws FgaInvalidParameterException {
return getStore(null);
}
/**
* GetStore - Get information about the current store.
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientGetStoreResponse> getStore(ClientGetStoreOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.getStore(storeId, overrides)).thenApply(ClientGetStoreResponse::new);
}
/**
* DeleteStore - Delete a store
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientDeleteStoreResponse> deleteStore() throws FgaInvalidParameterException {
return deleteStore(null);
}
/**
* DeleteStore - Delete a store
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientDeleteStoreResponse> deleteStore(ClientDeleteStoreOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.deleteStore(storeId, overrides)).thenApply(ClientDeleteStoreResponse::new);
}
/* **********************
* Authorization Models *
************************/
/**
* ReadAuthorizationModels - Read all authorization models
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelsResponse> readAuthorizationModels()
throws FgaInvalidParameterException {
return readAuthorizationModels(null);
}
/**
* ReadAuthorizationModels - Read all authorization models
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelsResponse> readAuthorizationModels(
ClientReadAuthorizationModelsOptions options) throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
Integer pageSize;
String continuationToken;
if (options != null) {
pageSize = options.getPageSize();
continuationToken = options.getContinuationToken();
} else {
// null are valid for these values
continuationToken = null;
pageSize = null;
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.readAuthorizationModels(storeId, pageSize, continuationToken, overrides))
.thenApply(ClientReadAuthorizationModelsResponse::new);
}
/**
* WriteAuthorizationModel - Create a new version of the authorization model
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteAuthorizationModelResponse> writeAuthorizationModel(
WriteAuthorizationModelRequest request) throws FgaInvalidParameterException {
return writeAuthorizationModel(request, null);
}
/**
* WriteAuthorizationModel - Create a new version of the authorization model
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteAuthorizationModelResponse> writeAuthorizationModel(
WriteAuthorizationModelRequest request, ClientWriteAuthorizationModelOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.writeAuthorizationModel(storeId, request, overrides))
.thenApply(ClientWriteAuthorizationModelResponse::new);
}
/**
* ReadAuthorizationModel - Read the current authorization model
*
* @throws FgaInvalidParameterException When either the Store ID or Authorization Model ID are null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelResponse> readAuthorizationModel()
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
String authorizationModelId = configuration.getAuthorizationModelIdChecked();
return call(() -> api.readAuthorizationModel(storeId, authorizationModelId))
.thenApply(ClientReadAuthorizationModelResponse::new);
}
/**
* ReadAuthorizationModel - Read the current authorization model
*
* @throws FgaInvalidParameterException When either the Store ID or Authorization Model ID are null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelResponse> readAuthorizationModel(
ClientReadAuthorizationModelOptions options) throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
// Set authorizationModelId from options if available; otherwise, require a valid configuration value
String authorizationModelId;
if (options != null && !isNullOrWhitespace(options.getAuthorizationModelId())) {
authorizationModelId = options.getAuthorizationModelIdChecked();
} else {
authorizationModelId = configuration.getAuthorizationModelIdChecked();
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.readAuthorizationModel(storeId, authorizationModelId, overrides))
.thenApply(ClientReadAuthorizationModelResponse::new);
}
/**
* ReadLatestAuthorizationModel - Read the latest authorization model for the current store
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelResponse> readLatestAuthorizationModel()
throws FgaInvalidParameterException {
return readLatestAuthorizationModel(null);
}
/**
* ReadLatestAuthorizationModel - Read the latest authorization model for the current store
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadAuthorizationModelResponse> readLatestAuthorizationModel(
ClientReadLatestAuthorizationModelOptions options) throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.readAuthorizationModels(storeId, 1, null, overrides))
.thenApply(ClientReadAuthorizationModelResponse::latestOf);
}
/* *********************
* Relationship Tuples *
***********************/
/**
* Read Changes - Read the list of historical relationship tuple writes and deletes
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadChangesResponse> readChanges(ClientReadChangesRequest request)
throws FgaInvalidParameterException {
return readChanges(request, null);
}
/**
* Read Changes - Read the list of historical relationship tuple writes and deletes
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadChangesResponse> readChanges(
ClientReadChangesRequest request, ClientReadChangesOptions readChangesOptions)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var options = readChangesOptions != null ? readChangesOptions : new ClientReadChangesOptions();
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.readChanges(
storeId,
request.getType(),
options.getPageSize(),
options.getContinuationToken(),
request.getStartTime(),
overrides))
.thenApply(ClientReadChangesResponse::new);
}
/**
* Read - Read tuples previously written to the store (does not evaluate)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadResponse> read(ClientReadRequest request) throws FgaInvalidParameterException {
return read(request, null);
}
/**
* Read - Read tuples previously written to the store (does not evaluate)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientReadResponse> read(ClientReadRequest request, ClientReadOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
ReadRequest body = new ReadRequest();
if (request != null
&& (request.getUser() != null || request.getRelation() != null || request.getObject() != null)) {
body.tupleKey(new ReadRequestTupleKey()
.user(request.getUser())
.relation(request.getRelation())
._object(request.getObject()));
}
if (options != null) {
body.pageSize(options.getPageSize()).continuationToken(options.getContinuationToken());
if (options.getConsistency() != null) {
body.consistency(options.getConsistency());
}
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.read(storeId, body, overrides)).thenApply(ClientReadResponse::new);
}
/**
* Write - Create or delete relationship tuples
*
* <p>This method can operate in two modes depending on the options provided:</p>
*
* <h3>Transactional Mode (default)</h3>
* <p>When {@code options.disableTransactions()} is false or not set:</p>
* <ul>
* <li>All writes and deletes are executed as a single atomic transaction</li>
* <li>If any tuple fails, the entire operation fails and no changes are made</li>
* <li>On success: All tuples in the response have {@code ClientWriteStatus.SUCCESS}</li>
* <li>On failure: The method throws an exception (no partial results)</li>
* </ul>
*
* <h3>Non-Transactional Mode</h3>
* <p>When {@code options.disableTransactions()} is true:</p>
* <ul>
* <li>Tuples are processed in chunks (size controlled by {@code transactionChunkSize})</li>
* <li>Each chunk is processed independently - some may succeed while others fail</li>
* <li>The method always returns a response (never throws for tuple-level failures)</li>
* <li>Individual tuple results are indicated by {@code ClientWriteStatus} in the response</li>
* </ul>
*
* <h4>Non-Transactional Success Scenarios:</h4>
* <ul>
* <li>All tuples succeed: All responses have {@code status = SUCCESS, error = null}</li>
* <li>Mixed results: Some responses have {@code status = SUCCESS}, others have {@code status = FAILURE} with error details</li>
* <li>All tuples fail: All responses have {@code status = FAILURE} with individual error details</li>
* </ul>
*
* <h4>Non-Transactional Exception Scenarios:</h4>
* <ul>
* <li>Authentication errors: Method throws immediately (no partial processing)</li>
* <li>Configuration errors: Method throws before processing any tuples</li>
* <li>Network/infrastructure errors: Method may throw depending on the specific error</li>
* </ul>
*
* <h4>Caller Responsibilities:</h4>
* <ul>
* <li>For transactional mode: Handle exceptions for any failures</li>
* <li>For non-transactional mode: Check {@code status} field of each tuple in the response</li>
* <li>For non-transactional mode: Implement retry logic for failed tuples if needed</li>
* <li>For non-transactional mode: Handle partial success scenarios appropriately</li>
* </ul>
*
* @param request The write request containing tuples to create or delete
* @return A CompletableFuture containing the write response with individual tuple results
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> write(ClientWriteRequest request)
throws FgaInvalidParameterException {
return write(request, null);
}
/**
* Write - Create or delete relationship tuples
*
* <p>This method can operate in two modes depending on the options provided:</p>
*
* <h3>Transactional Mode (default)</h3>
* <p>When {@code options.disableTransactions()} is false or not set:</p>
* <ul>
* <li>All writes and deletes are executed as a single atomic transaction</li>
* <li>If any tuple fails, the entire operation fails and no changes are made</li>
* <li>On success: All tuples in the response have {@code ClientWriteStatus.SUCCESS}</li>
* <li>On failure: The method throws an exception (no partial results)</li>
* </ul>
*
* <h3>Non-Transactional Mode</h3>
* <p>When {@code options.disableTransactions()} is true:</p>
* <ul>
* <li>Tuples are processed in chunks (size controlled by {@code transactionChunkSize})</li>
* <li>Each chunk is processed independently - some may succeed while others fail</li>
* <li>The method always returns a response (never throws for tuple-level failures)</li>
* <li>Individual tuple results are indicated by {@code ClientWriteStatus} in the response</li>
* </ul>
*
* <h4>Non-Transactional Success Scenarios:</h4>
* <ul>
* <li>All tuples succeed: All responses have {@code status = SUCCESS, error = null}</li>
* <li>Mixed results: Some responses have {@code status = SUCCESS}, others have {@code status = FAILURE} with error details</li>
* <li>All tuples fail: All responses have {@code status = FAILURE} with individual error details</li>
* </ul>
*
* <h4>Non-Transactional Exception Scenarios:</h4>
* <ul>
* <li>Authentication errors: Method throws immediately (no partial processing)</li>
* <li>Configuration errors: Method throws before processing any tuples</li>
* <li>Network/infrastructure errors: Method may throw depending on the specific error</li>
* </ul>
*
* <h4>Caller Responsibilities:</h4>
* <ul>
* <li>For transactional mode: Handle exceptions for any failures</li>
* <li>For non-transactional mode: Check {@code status} field of each tuple in the response</li>
* <li>For non-transactional mode: Implement retry logic for failed tuples if needed</li>
* <li>For non-transactional mode: Handle partial success scenarios appropriately</li>
* </ul>
*
* @param request The write request containing tuples to create or delete
* @param options Write options including transaction mode and chunk size settings
* @return A CompletableFuture containing the write response with individual tuple results
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> write(ClientWriteRequest request, ClientWriteOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
if (options != null && options.disableTransactions()) {
return writeNonTransaction(storeId, request, options);
}
return writeTransactions(storeId, request, options);
}
private CompletableFuture<ClientWriteResponse> writeTransactions(
String storeId, ClientWriteRequest request, ClientWriteOptions options) {
WriteRequest body = new WriteRequest();
var writeTuples = request.getWrites();
if (writeTuples != null && !writeTuples.isEmpty()) {
var onDuplicate = options != null ? options.getOnDuplicate() : null;
body.writes(ClientTupleKey.asWriteRequestWrites(writeTuples, onDuplicate));
}
var deleteTuples = request.getDeletes();
if (deleteTuples != null && !deleteTuples.isEmpty()) {
var onMissing = options != null ? options.getOnMissing() : null;
body.deletes(ClientTupleKeyWithoutCondition.asWriteRequestDeletes(deleteTuples, onMissing));
}
if (options != null && !isNullOrWhitespace(options.getAuthorizationModelId())) {
body.authorizationModelId(options.getAuthorizationModelId());
} else {
String authorizationModelId = configuration.getAuthorizationModelId();
body.authorizationModelId(authorizationModelId);
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.write(storeId, body, overrides)).thenApply(apiResponse -> {
// For transaction-based writes, all tuples are successful if the call succeeds
List<ClientWriteSingleResponse> writeResponses = writeTuples != null
? writeTuples.stream()
.map(tuple -> new ClientWriteSingleResponse(tuple.asTupleKey(), ClientWriteStatus.SUCCESS))
.collect(Collectors.toList())
: new ArrayList<>();
List<ClientWriteSingleResponse> deleteResponses = deleteTuples != null
? deleteTuples.stream()
.map(tuple -> new ClientWriteSingleResponse(
new TupleKey()
.user(tuple.getUser())
.relation(tuple.getRelation())
._object(tuple.getObject()),
ClientWriteStatus.SUCCESS))
.collect(Collectors.toList())
: new ArrayList<>();
return new ClientWriteResponse(apiResponse, writeResponses, deleteResponses);
});
}
/**
* Non-transactional write implementation that processes tuples in parallel chunks.
*
* <p>This method implements the error isolation behavior where individual chunk failures
* do not prevent other chunks from being processed. It performs the following steps:</p>
*
* <ol>
* <li>Splits writes and deletes into chunks based on {@code transactionChunkSize}</li>
* <li>Processes each chunk as an independent transaction in parallel</li>
* <li>Collects results from all chunks, marking individual tuples as SUCCESS or FAILURE</li>
* <li>Re-throws authentication errors immediately to stop all processing</li>
* <li>Converts other errors to FAILURE status for affected tuples</li>
* </ol>
*
* <p>The method guarantees that:</p>
* <ul>
* <li>Authentication errors are never swallowed (they stop all processing)</li>
* <li>Other errors are isolated to their respective chunks</li>
* <li>The response always contains a result for every input tuple</li>
* <li>The order of results matches the order of input tuples</li>
* </ul>
*
* @param storeId The store ID to write to
* @param request The write request containing tuples to process
* @param writeOptions Options including chunk size and headers
* @return CompletableFuture with results for all tuples, marking each as SUCCESS or FAILURE
*/
private CompletableFuture<ClientWriteResponse> writeNonTransaction(
String storeId, ClientWriteRequest request, ClientWriteOptions writeOptions) {
var options = writeOptions != null
? writeOptions
: new ClientWriteOptions().transactionChunkSize(FgaConstants.CLIENT_MAX_METHOD_PARALLEL_REQUESTS);
HashMap<String, String> headers = options.getAdditionalHeaders() != null
? new HashMap<>(options.getAdditionalHeaders())
: new HashMap<>();
headers.putIfAbsent(FgaConstants.CLIENT_METHOD_HEADER, "Write");
headers.putIfAbsent(
FgaConstants.CLIENT_BULK_REQUEST_ID_HEADER, randomUUID().toString());
options.additionalHeaders(headers);
int chunkSize = options.getTransactionChunkSize();
List<CompletableFuture<List<ClientWriteSingleResponse>>> writeFutures = new ArrayList<>();
List<CompletableFuture<List<ClientWriteSingleResponse>>> deleteFutures = new ArrayList<>();
// Handle writes
if (request.getWrites() != null && !request.getWrites().isEmpty()) {
var writeChunks = chunksOf(chunkSize, request.getWrites()).collect(Collectors.toList());
for (List<ClientTupleKey> chunk : writeChunks) {
CompletableFuture<List<ClientWriteSingleResponse>> chunkFuture = this.writeTransactions(
storeId, ClientWriteRequest.ofWrites(chunk), options)
.thenApply(response -> {
// On success, mark all tuples in this chunk as successful
return chunk.stream()
.map(tuple -> new ClientWriteSingleResponse(
tuple.asTupleKey(), ClientWriteStatus.SUCCESS))
.collect(Collectors.toList());
})
.exceptionally(exception -> {
// Re-throw authentication errors to stop all processing
Throwable cause =
exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof FgaApiAuthenticationError) {
throw new CompletionException(cause);
}
// On failure, mark all tuples in this chunk as failed, but continue processing other chunks
return chunk.stream()
.map(tuple -> new ClientWriteSingleResponse(
tuple.asTupleKey(),
ClientWriteStatus.FAILURE,
cause instanceof Exception ? (Exception) cause : new Exception(cause)))
.collect(Collectors.toList());
});
writeFutures.add(chunkFuture);
}
}
// Handle deletes
if (request.getDeletes() != null && !request.getDeletes().isEmpty()) {
var deleteChunks = chunksOf(chunkSize, request.getDeletes()).collect(Collectors.toList());
for (List<ClientTupleKeyWithoutCondition> chunk : deleteChunks) {
CompletableFuture<List<ClientWriteSingleResponse>> chunkFuture = this.writeTransactions(
storeId, ClientWriteRequest.ofDeletes(chunk), options)
.thenApply(response -> {
// On success, mark all tuples in this chunk as successful
return chunk.stream()
.map(tuple -> new ClientWriteSingleResponse(
new TupleKey()
.user(tuple.getUser())
.relation(tuple.getRelation())
._object(tuple.getObject()),
ClientWriteStatus.SUCCESS))
.collect(Collectors.toList());
})
.exceptionally(exception -> {
// Re-throw authentication errors to stop all processing
Throwable cause =
exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof FgaApiAuthenticationError) {
throw new CompletionException(cause);
}
// On failure, mark all tuples in this chunk as failed, but continue processing other chunks
return chunk.stream()
.map(tuple -> new ClientWriteSingleResponse(
new TupleKey()
.user(tuple.getUser())
.relation(tuple.getRelation())
._object(tuple.getObject()),
ClientWriteStatus.FAILURE,
cause instanceof Exception ? (Exception) cause : new Exception(cause)))
.collect(Collectors.toList());
});
deleteFutures.add(chunkFuture);
}
}
// Combine all futures
CompletableFuture<List<ClientWriteSingleResponse>> allWritesFuture = writeFutures.isEmpty()
? CompletableFuture.completedFuture(new ArrayList<>())
: CompletableFuture.allOf(writeFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> writeFutures.stream()
.map(CompletableFuture::join)
.flatMap(List::stream)
.collect(Collectors.toList()));
CompletableFuture<List<ClientWriteSingleResponse>> allDeletesFuture = deleteFutures.isEmpty()
? CompletableFuture.completedFuture(new ArrayList<>())
: CompletableFuture.allOf(deleteFutures.toArray(new CompletableFuture[0]))
.thenApply(v -> deleteFutures.stream()
.map(CompletableFuture::join)
.flatMap(List::stream)
.collect(Collectors.toList()));
return CompletableFuture.allOf(allWritesFuture, allDeletesFuture)
.thenApply(v -> new ClientWriteResponse(allWritesFuture.join(), allDeletesFuture.join()));
}
private <T> Stream<List<T>> chunksOf(int chunkSize, List<T> list) {
if (list == null || list.isEmpty()) {
return Stream.empty();
}
int nChunks = (int) Math.ceil(list.size() / (double) chunkSize);
int finalEndExclusive = list.size();
Stream.Builder<List<T>> chunks = Stream.builder();
for (int i = 0; i < nChunks; i++) {
List<T> chunk = list.subList(i * chunkSize, Math.min((i + 1) * chunkSize, finalEndExclusive));
chunks.add(chunk);
}
return chunks.build();
}
/**
* WriteTuples - Utility method to write tuples, wraps Write
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> writeTuples(List<ClientTupleKey> tupleKeys)
throws FgaInvalidParameterException {
return writeTuples(tupleKeys, null);
}
/**
* WriteTuples - Utility method to write tuples, wraps Write
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> writeTuples(
List<ClientTupleKey> tupleKeys, ClientWriteTuplesOptions options) throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var body = new WriteRequest();
var onDuplicate = options != null ? options.getOnDuplicate() : null;
body.writes(ClientTupleKey.asWriteRequestWrites(tupleKeys, onDuplicate));
String authorizationModelId = configuration.getAuthorizationModelId();
if (!isNullOrWhitespace(authorizationModelId)) {
body.authorizationModelId(authorizationModelId);
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.write(storeId, body, overrides)).thenApply(apiResponse -> {
List<ClientWriteSingleResponse> writeResponses = tupleKeys.stream()
.map(tuple -> new ClientWriteSingleResponse(tuple.asTupleKey(), ClientWriteStatus.SUCCESS))
.collect(Collectors.toList());
return new ClientWriteResponse(apiResponse, writeResponses, new ArrayList<>());
});
}
/**
* DeleteTuples - Utility method to delete tuples, wraps Write
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> deleteTuples(List<ClientTupleKeyWithoutCondition> tupleKeys)
throws FgaInvalidParameterException {
return deleteTuples(tupleKeys, null);
}
/**
* DeleteTuples - Utility method to delete tuples, wraps Write
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientWriteResponse> deleteTuples(
List<ClientTupleKeyWithoutCondition> tupleKeys, ClientDeleteTuplesOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
var body = new WriteRequest();
var onMissing = options != null ? options.getOnMissing() : null;
body.deletes(ClientTupleKeyWithoutCondition.asWriteRequestDeletes(tupleKeys, onMissing));
String authorizationModelId = configuration.getAuthorizationModelId();
if (!isNullOrWhitespace(authorizationModelId)) {
body.authorizationModelId(authorizationModelId);
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.write(storeId, body, overrides)).thenApply(apiResponse -> {
List<ClientWriteSingleResponse> deleteResponses = tupleKeys.stream()
.map(tuple -> new ClientWriteSingleResponse(
new TupleKey()
.user(tuple.getUser())
.relation(tuple.getRelation())
._object(tuple.getObject()),
ClientWriteStatus.SUCCESS))
.collect(Collectors.toList());
return new ClientWriteResponse(apiResponse, new ArrayList<>(), deleteResponses);
});
}
/* **********************
* Relationship Queries *
***********************/
/**
* Check - Check if a user has a particular relation with an object (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientCheckResponse> check(ClientCheckRequest request)
throws FgaInvalidParameterException {
return check(request, null);
}
/**
* Check - Check if a user has a particular relation with an object (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientCheckResponse> check(ClientCheckRequest request, ClientCheckOptions options)
throws FgaInvalidParameterException {
configuration.assertValid();
String storeId = configuration.getStoreIdChecked();
CheckRequest body = request.asCheckRequest();
if (options != null) {
if (options.getConsistency() != null) {
body.consistency(options.getConsistency());
}
// Set authorizationModelId from options if available; otherwise, use the default from configuration
String authorizationModelId = !isNullOrWhitespace(options.getAuthorizationModelId())
? options.getAuthorizationModelId()
: configuration.getAuthorizationModelId();
body.authorizationModelId(authorizationModelId);
} else {
body.setAuthorizationModelId(configuration.getAuthorizationModelId());
}
var overrides = new ConfigurationOverride().addHeaders(options);
return call(() -> api.check(storeId, body, overrides)).thenApply(ClientCheckResponse::new);
}
/**
* BatchCheck - Run a set of checks (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<List<ClientBatchCheckClientResponse>> clientBatchCheck(List<ClientCheckRequest> requests)
throws FgaInvalidParameterException {
return clientBatchCheck(requests, null);
}
/**
* BatchCheck - Run a set of checks (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<List<ClientBatchCheckClientResponse>> clientBatchCheck(
List<ClientCheckRequest> requests, ClientBatchCheckClientOptions batchCheckOptions)
throws FgaInvalidParameterException {
configuration.assertValid();
configuration.assertValidStoreId();
var options = batchCheckOptions != null
? batchCheckOptions
: new ClientBatchCheckClientOptions()
.maxParallelRequests(FgaConstants.CLIENT_MAX_METHOD_PARALLEL_REQUESTS);
HashMap<String, String> headers = options.getAdditionalHeaders() != null
? new HashMap<>(options.getAdditionalHeaders())
: new HashMap<>();
headers.putIfAbsent(FgaConstants.CLIENT_METHOD_HEADER, "ClientBatchCheck");
headers.putIfAbsent(
FgaConstants.CLIENT_BULK_REQUEST_ID_HEADER, randomUUID().toString());
options.additionalHeaders(headers);
int maxParallelRequests = options.getMaxParallelRequests() != null
? options.getMaxParallelRequests()
: FgaConstants.CLIENT_MAX_METHOD_PARALLEL_REQUESTS;
var executor = Executors.newScheduledThreadPool(maxParallelRequests);
var latch = new CountDownLatch(requests.size());
var responses = new ConcurrentLinkedQueue<ClientBatchCheckClientResponse>();
final var clientCheckOptions = options.asClientCheckOptions();
Consumer<ClientCheckRequest> singleClientCheckRequest =
request -> call(() -> this.check(request, clientCheckOptions))
.handleAsync(ClientBatchCheckClientResponse.asyncHandler(request))
.thenAccept(responses::add)
.thenRun(latch::countDown);
try {
requests.forEach(request -> executor.execute(() -> singleClientCheckRequest.accept(request)));
latch.await();
return CompletableFuture.completedFuture(new ArrayList<>(responses));
} catch (Exception e) {
return CompletableFuture.failedFuture(e);
} finally {
executor.shutdown();
}
}
/**
* BatchCheck - Run a set of checks (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientBatchCheckResponse> batchCheck(ClientBatchCheckRequest request)
throws FgaInvalidParameterException, FgaValidationError {
return batchCheck(request, null);
}
/**
* BatchCheck - Run a set of checks (evaluates)
*
* @throws FgaInvalidParameterException When the Store ID is null, empty, or whitespace
*/
public CompletableFuture<ClientBatchCheckResponse> batchCheck(
ClientBatchCheckRequest requests, ClientBatchCheckOptions batchCheckOptions)
throws FgaInvalidParameterException, FgaValidationError {
configuration.assertValid();
configuration.assertValidStoreId();
var options = batchCheckOptions != null
? batchCheckOptions
: new ClientBatchCheckOptions()
.maxParallelRequests(FgaConstants.CLIENT_MAX_METHOD_PARALLEL_REQUESTS)
.maxBatchSize(FgaConstants.CLIENT_MAX_BATCH_SIZE);
HashMap<String, String> headers = options.getAdditionalHeaders() != null
? new HashMap<>(options.getAdditionalHeaders())
: new HashMap<>();
headers.putIfAbsent(FgaConstants.CLIENT_METHOD_HEADER, "BatchCheck");
headers.putIfAbsent(
FgaConstants.CLIENT_BULK_REQUEST_ID_HEADER, randomUUID().toString());
options.additionalHeaders(headers);
Map<String, ClientBatchCheckItem> correlationIdToCheck = new HashMap<>();
List<BatchCheckItem> collect = new ArrayList<>();
for (ClientBatchCheckItem check : requests.getChecks()) {
String correlationId = check.getCorrelationId();
correlationId = correlationId == null || correlationId.isBlank()
? randomUUID().toString()
: correlationId;
BatchCheckItem batchCheckItem = new BatchCheckItem()
.tupleKey(new CheckRequestTupleKey()
.user(check.getUser())
.relation(check.getRelation())
._object(check.getObject()))
.context(check.getContext())
.correlationId(correlationId);
List<ClientTupleKey> contextualTuples = check.getContextualTuples();
if (contextualTuples != null && !contextualTuples.isEmpty()) {
batchCheckItem.contextualTuples(ClientTupleKey.asContextualTupleKeys(contextualTuples));
}
collect.add(batchCheckItem);
if (correlationIdToCheck.containsKey(correlationId)) {
throw new FgaValidationError(
"correlationId", "When calling batchCheck, correlation IDs must be unique");
}
correlationIdToCheck.put(correlationId, check);
}
int maxBatchSize =
options.getMaxBatchSize() != null ? options.getMaxBatchSize() : FgaConstants.CLIENT_MAX_BATCH_SIZE;
List<List<BatchCheckItem>> batchedChecks = IntStream.range(
0, (collect.size() + maxBatchSize - 1) / maxBatchSize)
.mapToObj(i -> collect.subList(i * maxBatchSize, Math.min((i + 1) * maxBatchSize, collect.size())))
.collect(Collectors.toList());
int maxParallelRequests = options.getMaxParallelRequests() != null
? options.getMaxParallelRequests()
: FgaConstants.CLIENT_MAX_METHOD_PARALLEL_REQUESTS;
var executor = Executors.newScheduledThreadPool(maxParallelRequests);
var latch = new CountDownLatch(batchedChecks.size());
var responses = new ConcurrentLinkedQueue<ClientBatchCheckSingleResponse>();
var failure = new AtomicReference<Throwable>();
var override = new ConfigurationOverride().addHeaders(options);
Consumer<List<BatchCheckItem>> singleBatchCheckRequest = request -> call(() -> {
BatchCheckRequest body = new BatchCheckRequest().checks(request);
if (options.getConsistency() != null) {
body.consistency(options.getConsistency());
}
// Set authorizationModelId from options if available; otherwise, use the default from configuration
String authorizationModelId = !isNullOrWhitespace(options.getAuthorizationModelId())
? options.getAuthorizationModelId()
: configuration.getAuthorizationModelId();
if (!isNullOrWhitespace(authorizationModelId)) {
body.authorizationModelId(authorizationModelId);
}
return api.batchCheck(configuration.getStoreId(), body, override);
})
.whenComplete((batchCheckResponseApiResponse, throwable) -> {
try {
if (throwable != null) {
failure.compareAndSet(null, throwable);
return;
}
Map<String, BatchCheckSingleResult> response =
batchCheckResponseApiResponse.getData().getResult();
List<ClientBatchCheckSingleResponse> batchResults = new ArrayList<>();