From 985623ae5c3ca03dbf8be408e91af36c2621106f Mon Sep 17 00:00:00 2001 From: "J.R. Hill" Date: Thu, 14 Dec 2023 13:33:43 -0800 Subject: [PATCH] refactor(api): refactor low-level API (WIP) --- .../java/dev/openfga/sdk/api/OpenFgaApi.java | 498 +++++------------- .../dev/openfga/sdk/api/client/ApiClient.java | 56 -- src/main/java/dev/openfga/sdk/util/Pair.java | 16 + .../dev/openfga/sdk/api/OpenFgaApiTest.java | 69 +-- .../sdk/api/client/OpenFgaClientTest.java | 5 +- 5 files changed, 168 insertions(+), 476 deletions(-) diff --git a/src/main/java/dev/openfga/sdk/api/OpenFgaApi.java b/src/main/java/dev/openfga/sdk/api/OpenFgaApi.java index 3eaeb30..75a96f9 100644 --- a/src/main/java/dev/openfga/sdk/api/OpenFgaApi.java +++ b/src/main/java/dev/openfga/sdk/api/OpenFgaApi.java @@ -12,6 +12,9 @@ package dev.openfga.sdk.api; +import static dev.openfga.sdk.api.client.ApiClient.urlEncode; +import static dev.openfga.sdk.util.StringUtil.isNullOrWhitespace; + import dev.openfga.sdk.api.auth.*; import dev.openfga.sdk.api.client.*; import dev.openfga.sdk.api.configuration.*; @@ -43,8 +46,11 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.StringJoiner; import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * A low-level API representation of an OpenFGA server. @@ -101,16 +107,18 @@ public CompletableFuture> check(String storeId, Check */ public CompletableFuture> check( String storeId, CheckRequest body, ConfigurationOverride configurationOverride) - throws ApiException, FgaInvalidParameterException { + throws FgaInvalidParameterException { return check(storeId, body, this.configuration.override(configurationOverride)); } private CompletableFuture> check( - String storeId, CheckRequest body, Configuration configuration) - throws ApiException, FgaInvalidParameterException { + String storeId, CheckRequest body, Configuration configuration) throws FgaInvalidParameterException { + validate(storeId, "storeId", "check"); + validate(body, "CheckRequest", "check"); + + String path = "/stores/" + urlEncode(storeId) + "/check"; try { - HttpRequest request = - checkRequestBuilder(storeId, body, configuration).build(); + HttpRequest request = buildHttpRequest("POST", path, body, configuration); return new HttpRequestAttempt<>(request, "check", CheckResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -118,58 +126,6 @@ private CompletableFuture> check( } } - private HttpRequest.Builder checkRequestBuilder(String storeId, CheckRequest body, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'storeId' is set - if (storeId == null) { - throw new ApiException(400, "Missing the required parameter 'storeId' when calling check"); - } - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling check"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/stores/{store_id}/check".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - try { - byte[] localVarPostBody = apiClient.getObjectMapper().writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * Create a store * Create a unique OpenFGA store which will be used to store authorization models and relationship tuples. @@ -198,8 +154,9 @@ public CompletableFuture> createStore( private CompletableFuture> createStore( CreateStoreRequest body, Configuration configuration) throws ApiException, FgaInvalidParameterException { + validate(body, "CreateStoreRequest", "createStore"); try { - HttpRequest request = createStoreRequestBuilder(body, configuration).build(); + HttpRequest request = buildHttpRequest("POST", "/stores", body, configuration); return new HttpRequestAttempt<>(request, "createStore", CreateStoreResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -207,54 +164,6 @@ private CompletableFuture> createStore( } } - private HttpRequest.Builder createStoreRequestBuilder(CreateStoreRequest body, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createStore"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/stores"; - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - try { - byte[] localVarPostBody = apiClient.getObjectMapper().writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * Delete a store * Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models. @@ -282,9 +191,10 @@ public CompletableFuture> deleteStore(String storeId, Configur private CompletableFuture> deleteStore(String storeId, Configuration configuration) throws ApiException, FgaInvalidParameterException { + validate(storeId, "storeId", "deleteStore"); + String path = "/stores/" + urlEncode(storeId); try { - HttpRequest request = - deleteStoreRequestBuilder(storeId, configuration).build(); + HttpRequest request = buildHttpRequest("DELETE", path, configuration); return new HttpRequestAttempt<>(request, "deleteStore", Void.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -292,48 +202,6 @@ private CompletableFuture> deleteStore(String storeId, Configu } } - private HttpRequest.Builder deleteStoreRequestBuilder(String storeId, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'storeId' is set - if (storeId == null) { - throw new ApiException(400, "Missing the required parameter 'storeId' when calling deleteStore"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/stores/{store_id}".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship * The Expand API will return all users and usersets that have certain relationship with an object in a certain store. This is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned. Body parameters `tuple_key.object` and `tuple_key.relation` are all required. The response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes. ## Example To expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body ```json { \"tuple_key\": { \"object\": \"document:2021-budget\", \"relation\": \"reader\" }, \"authorization_model_id\": \"01G50QVV17PECNVAHX1GG4Y5NC\" } ``` OpenFGA's response will be a userset tree of the users and usersets that have read access to the document. ```json { \"tree\":{ \"root\":{ \"type\":\"document:2021-budget#reader\", \"union\":{ \"nodes\":[ { \"type\":\"document:2021-budget#reader\", \"leaf\":{ \"users\":{ \"users\":[ \"user:bob\" ] } } }, { \"type\":\"document:2021-budget#reader\", \"leaf\":{ \"computed\":{ \"userset\":\"document:2021-budget#writer\" } } } ] } } } } ``` The caller can then call expand API for the `writer` relationship for the `document:2021-budget`. @@ -365,9 +233,12 @@ public CompletableFuture> expand( private CompletableFuture> expand( String storeId, ExpandRequest body, Configuration configuration) throws ApiException, FgaInvalidParameterException { + validate(storeId, "storeId", "expand"); + validate(body, "ExpandRequest", "expand"); + + String path = "/stores/" + urlEncode(storeId) + "/expand"; try { - HttpRequest request = - expandRequestBuilder(storeId, body, configuration).build(); + HttpRequest request = buildHttpRequest("POST", path, body, configuration); return new HttpRequestAttempt<>(request, "expand", ExpandResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -375,59 +246,6 @@ private CompletableFuture> expand( } } - private HttpRequest.Builder expandRequestBuilder(String storeId, ExpandRequest body, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'storeId' is set - if (storeId == null) { - throw new ApiException(400, "Missing the required parameter 'storeId' when calling expand"); - } - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling expand"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = - "/stores/{store_id}/expand".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - try { - byte[] localVarPostBody = apiClient.getObjectMapper().writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * Get a store * Returns an OpenFGA store by its identifier @@ -456,8 +274,11 @@ public CompletableFuture> getStore( private CompletableFuture> getStore(String storeId, Configuration configuration) throws ApiException, FgaInvalidParameterException { + validate(storeId, "storeId", "expand"); + + String path = "/stores/" + urlEncode(storeId); try { - HttpRequest request = getStoreRequestBuilder(storeId, configuration).build(); + HttpRequest request = buildHttpRequest("GET", path, configuration); return new HttpRequestAttempt<>(request, "getStore", GetStoreResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -465,48 +286,6 @@ private CompletableFuture> getStore(String storeId } } - private HttpRequest.Builder getStoreRequestBuilder(String storeId, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'storeId' is set - if (storeId == null) { - throw new ApiException(400, "Missing the required parameter 'storeId' when calling getStore"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/stores/{store_id}".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * List all objects of the given type that the user has a relation with * The ListObjects API returns a list of all the objects of the given type that the user has a relation with. To achieve this, both the store tuples and the authorization model are used. An `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance. You may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`. You may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly. The response will contain the related objects in an array in the \"objects\" field of the response and they will be strings in the object format `<type>:<id>` (e.g. \"document:roadmap\"). The number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first. The objects given will not be sorted, and therefore two identical calls can give a given different set of objects. @@ -538,9 +317,12 @@ public CompletableFuture> listObjects( private CompletableFuture> listObjects( String storeId, ListObjectsRequest body, Configuration configuration) throws ApiException, FgaInvalidParameterException { + validate(storeId, "storeId", "expand"); + validate(body, "ExpandRequest", "expand"); + + String path = "/stores/" + urlEncode(storeId) + "/list-objects"; try { - HttpRequest request = - listObjectsRequestBuilder(storeId, body, configuration).build(); + HttpRequest request = buildHttpRequest("POST", path, body, configuration); return new HttpRequestAttempt<>(request, "listObjects", ListObjectsResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -548,60 +330,6 @@ private CompletableFuture> listObjects( } } - private HttpRequest.Builder listObjectsRequestBuilder( - String storeId, ListObjectsRequest body, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - // verify the required parameter 'storeId' is set - if (storeId == null) { - throw new ApiException(400, "Missing the required parameter 'storeId' when calling listObjects"); - } - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling listObjects"); - } - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = - "/stores/{store_id}/list-objects".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); - - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - - localVarRequestBuilder.header("Content-Type", "application/json"); - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - try { - byte[] localVarPostBody = apiClient.getObjectMapper().writeValueAsBytes(body); - localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); - } catch (IOException e) { - throw new ApiException(e); - } - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * List all stores * Returns a paginated list of OpenFGA stores and a continuation token to get additional stores. The continuation token will be empty if there are no more stores. @@ -633,9 +361,9 @@ public CompletableFuture> listStores( private CompletableFuture> listStores( Integer pageSize, String continuationToken, Configuration configuration) throws ApiException, FgaInvalidParameterException { + String path = paginationPath("/stores", pageSize, continuationToken); try { - HttpRequest request = listStoresRequestBuilder(pageSize, continuationToken, configuration) - .build(); + HttpRequest request = buildHttpRequest("GET", path, configuration); return new HttpRequestAttempt<>(request, "listStores", ListStoresResponse.class, apiClient, configuration) .attemptHttpRequest(); } catch (ApiException e) { @@ -643,63 +371,6 @@ private CompletableFuture> listStores( } } - private HttpRequest.Builder listStoresRequestBuilder( - Integer pageSize, String continuationToken, Configuration configuration) - throws ApiException, FgaInvalidParameterException { - - // verify the Configuration is valid - configuration.assertValid(); - - HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - - String localVarPath = "/stores"; - - List localVarQueryParams = new ArrayList<>(); - StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); - String localVarQueryParameterBaseName; - localVarQueryParameterBaseName = "page_size"; - localVarQueryParams.addAll(ApiClient.parameterToPairs("page_size", pageSize)); - localVarQueryParameterBaseName = "continuation_token"; - localVarQueryParams.addAll(ApiClient.parameterToPairs("continuation_token", continuationToken)); - - if (!localVarQueryParams.isEmpty() || localVarQueryStringJoiner.length() != 0) { - StringJoiner queryJoiner = new StringJoiner("&"); - localVarQueryParams.forEach(p -> queryJoiner.add(p.getName() + '=' + p.getValue())); - if (localVarQueryStringJoiner.length() != 0) { - queryJoiner.add(localVarQueryStringJoiner.toString()); - } - localVarRequestBuilder.uri( - URI.create(configuration.getApiUrl() + localVarPath + '?' + queryJoiner.toString())); - } else { - localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); - } - - localVarRequestBuilder.header("Accept", "application/json"); - - if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { - String accessToken = getAccessToken(configuration); - localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); - } - - if (configuration.getUserAgent() != null) { - localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); - } - - if (configuration.getDefaultHeaders() != null) { - configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); - } - - localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); - Duration readTimeout = configuration.getReadTimeout(); - if (readTimeout != null) { - localVarRequestBuilder.timeout(readTimeout); - } - if (apiClient.getRequestInterceptor() != null) { - apiClient.getRequestInterceptor().accept(localVarRequestBuilder); - } - return localVarRequestBuilder; - } - /** * Get tuples from the store that matches a query, without following userset rewrite rules * The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. It is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. In the body: 1. `tuple_key` is optional. If not specified, it will return all tuples in the store. 2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`). 3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. ## Examples ### Query for all objects in a type definition To query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of ```json { \"tuple_key\": { \"user\": \"user:bob\", \"relation\": \"reader\", \"object\": \"document:\" } } ``` The API will return tuples and a continuation token, something like ```json { \"tuples\": [ { \"key\": { \"user\": \"user:bob\", \"relation\": \"reader\", \"object\": \"document:2021-budget\" }, \"timestamp\": \"2021-10-06T15:32:11.128Z\" } ], \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\" } ``` This means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store. The continuation token will be empty if there are no more tuples to query. ### Query for all stored relationship tuples that have a particular relation and object To query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of ```json { \"tuple_key\": { \"object\": \"document:2021-budget\", \"relation\": \"reader\" } } ``` The API will return something like ```json { \"tuples\": [ { \"key\": { \"user\": \"user:bob\", \"relation\": \"reader\", \"object\": \"document:2021-budget\" }, \"timestamp\": \"2021-10-06T15:32:11.128Z\" } ], \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them. ### Query for all users with all relationships for a particular document To query for all users that have any relationship with `document:2021-budget`, call read API with body of ```json { \"tuple_key\": { \"object\": \"document:2021-budget\" } } ``` The API will return something like ```json { \"tuples\": [ { \"key\": { \"user\": \"user:anne\", \"relation\": \"writer\", \"object\": \"document:2021-budget\" }, \"timestamp\": \"2021-10-05T13:42:12.356Z\" }, { \"key\": { \"user\": \"user:bob\", \"relation\": \"reader\", \"object\": \"document:2021-budget\" }, \"timestamp\": \"2021-10-06T15:32:11.128Z\" } ], \"continuation_token\": \"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==\" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`). @@ -757,7 +428,7 @@ private HttpRequest.Builder readRequestBuilder(String storeId, ReadRequest body, HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - String localVarPath = "/stores/{store_id}/read".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); + String localVarPath = "/stores/{store_id}/read".replace("{store_id}", urlEncode(storeId.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -854,8 +525,8 @@ private HttpRequest.Builder readAssertionsRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/stores/{store_id}/assertions/{authorization_model_id}" - .replace("{store_id}", ApiClient.urlEncode(storeId.toString())) - .replace("{authorization_model_id}", ApiClient.urlEncode(authorizationModelId.toString())); + .replace("{store_id}", urlEncode(storeId.toString())) + .replace("{authorization_model_id}", urlEncode(authorizationModelId.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -947,8 +618,8 @@ private HttpRequest.Builder readAuthorizationModelRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/stores/{store_id}/authorization-models/{id}" - .replace("{store_id}", ApiClient.urlEncode(storeId.toString())) - .replace("{id}", ApiClient.urlEncode(id.toString())); + .replace("{store_id}", urlEncode(storeId.toString())) + .replace("{id}", urlEncode(id.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -1043,8 +714,8 @@ private HttpRequest.Builder readAuthorizationModelsRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - String localVarPath = "/stores/{store_id}/authorization-models" - .replace("{store_id}", ApiClient.urlEncode(storeId.toString())); + String localVarPath = + "/stores/{store_id}/authorization-models".replace("{store_id}", urlEncode(storeId.toString())); List localVarQueryParams = new ArrayList<>(); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); @@ -1156,8 +827,7 @@ private HttpRequest.Builder readChangesRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - String localVarPath = - "/stores/{store_id}/changes".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); + String localVarPath = "/stores/{store_id}/changes".replace("{store_id}", urlEncode(storeId.toString())); List localVarQueryParams = new ArrayList<>(); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); @@ -1263,7 +933,7 @@ private HttpRequest.Builder writeRequestBuilder(String storeId, WriteRequest bod HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - String localVarPath = "/stores/{store_id}/write".replace("{store_id}", ApiClient.urlEncode(storeId.toString())); + String localVarPath = "/stores/{store_id}/write".replace("{store_id}", urlEncode(storeId.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -1369,8 +1039,8 @@ private HttpRequest.Builder writeAssertionsRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/stores/{store_id}/assertions/{authorization_model_id}" - .replace("{store_id}", ApiClient.urlEncode(storeId.toString())) - .replace("{authorization_model_id}", ApiClient.urlEncode(authorizationModelId.toString())); + .replace("{store_id}", urlEncode(storeId.toString())) + .replace("{authorization_model_id}", urlEncode(authorizationModelId.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -1470,8 +1140,8 @@ private HttpRequest.Builder writeAuthorizationModelRequestBuilder( HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); - String localVarPath = "/stores/{store_id}/authorization-models" - .replace("{store_id}", ApiClient.urlEncode(storeId.toString())); + String localVarPath = + "/stores/{store_id}/authorization-models".replace("{store_id}", urlEncode(storeId.toString())); localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + localVarPath)); @@ -1507,6 +1177,80 @@ private HttpRequest.Builder writeAuthorizationModelRequestBuilder( return localVarRequestBuilder; } + private HttpRequest buildHttpRequest(String method, String path, Configuration configuration) + throws ApiException, FgaInvalidParameterException { + return buildHttpRequestWithPublisher(method, path, HttpRequest.BodyPublishers.noBody(), configuration); + } + + private HttpRequest buildHttpRequest(String method, String path, T body, Configuration configuration) + throws ApiException, FgaInvalidParameterException { + try { + byte[] localVarPostBody = apiClient.getObjectMapper().writeValueAsBytes(body); + var bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(localVarPostBody); + return buildHttpRequestWithPublisher(method, path, bodyPublisher, configuration); + } catch (IOException e) { + throw new ApiException(e); + } + } + + private HttpRequest buildHttpRequestWithPublisher( + String method, String path, HttpRequest.BodyPublisher bodyPublisher, Configuration configuration) + throws ApiException, FgaInvalidParameterException { + // verify the Configuration is valid + configuration.assertValid(); + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + localVarRequestBuilder.uri(URI.create(configuration.getApiUrl() + path)); + + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + if (configuration.getCredentials().getCredentialsMethod() != CredentialsMethod.NONE) { + String accessToken = getAccessToken(configuration); + localVarRequestBuilder.header("Authorization", "Bearer " + accessToken); + } + + if (configuration.getUserAgent() != null) { + localVarRequestBuilder.header("User-Agent", configuration.getUserAgent()); + } + + if (configuration.getDefaultHeaders() != null) { + configuration.getDefaultHeaders().forEach(localVarRequestBuilder::header); + } + + localVarRequestBuilder.method(method, bodyPublisher); + + Duration readTimeout = configuration.getReadTimeout(); + if (readTimeout != null) { + localVarRequestBuilder.timeout(readTimeout); + } + if (apiClient.getRequestInterceptor() != null) { + apiClient.getRequestInterceptor().accept(localVarRequestBuilder); + } + + return localVarRequestBuilder.build(); + } + + private String paginationPath(String basePath, Integer pageSize, String continuationToken) { + String path = basePath; + String parameters = Stream.of(Pair.of("page_size", pageSize), Pair.of("continuation_token", continuationToken)) + .filter(Optional::isPresent) + .map(Optional::get) + .map(Pair::asQueryStringPair) + .collect(Collectors.joining("&")); + if (!isNullOrWhitespace(parameters)) { + path += "?" + parameters; + } + return path; + } + + private void validate(Object obj, String name, String context) throws FgaInvalidParameterException { + if (obj == null || obj instanceof String && isNullOrWhitespace((String) obj)) { + throw new FgaInvalidParameterException(name, context); + } + } + /** * Get an access token. Expects that configuration is valid (meaning it can * pass {@link Configuration#assertValid()}) and expects that if the diff --git a/src/main/java/dev/openfga/sdk/api/client/ApiClient.java b/src/main/java/dev/openfga/sdk/api/client/ApiClient.java index 8fa1c79..3945671 100644 --- a/src/main/java/dev/openfga/sdk/api/client/ApiClient.java +++ b/src/main/java/dev/openfga/sdk/api/client/ApiClient.java @@ -31,12 +31,9 @@ import java.time.Duration; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; -import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.StringJoiner; import java.util.function.Consumer; -import java.util.stream.Collectors; import org.openapitools.jackson.nullable.JsonNullableModule; /** @@ -164,59 +161,6 @@ public static List parameterToPairs(String name, Object value) { return Collections.singletonList(new Pair(urlEncode(name), urlEncode(valueToString(value)))); } - /** - * Convert a URL query name/collection parameter to a list of encoded - * {@link Pair} objects. - * - * @param collectionFormat The swagger collectionFormat string (csv, tsv, etc). - * @param name The query name parameter. - * @param values A collection of values for the given query name, which may be - * null. - * @return A list of {@link Pair} objects representing the input parameters, - * which is encoded for use in a URL. If the values collection is null, an - * empty list is returned. - */ - public static List parameterToPairs(String collectionFormat, String name, Collection values) { - if (name == null || name.isEmpty() || values == null || values.isEmpty()) { - return Collections.emptyList(); - } - - // get the collection format (default: csv) - String format = collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat; - - // create the params based on the collection format - if ("multi".equals(format)) { - return values.stream() - .map(value -> new Pair(urlEncode(name), urlEncode(valueToString(value)))) - .collect(Collectors.toList()); - } - - String delimiter; - switch (format) { - case "csv": - delimiter = urlEncode(","); - break; - case "ssv": - delimiter = urlEncode(" "); - break; - case "tsv": - delimiter = urlEncode("\t"); - break; - case "pipes": - delimiter = urlEncode("|"); - break; - default: - throw new IllegalArgumentException("Illegal collection format: " + collectionFormat); - } - - StringJoiner joiner = new StringJoiner(delimiter); - for (Object value : values) { - joiner.add(urlEncode(valueToString(value))); - } - - return Collections.singletonList(new Pair(urlEncode(name), joiner.toString())); - } - protected ObjectMapper createDefaultObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); diff --git a/src/main/java/dev/openfga/sdk/util/Pair.java b/src/main/java/dev/openfga/sdk/util/Pair.java index 772ee9c..1d02263 100644 --- a/src/main/java/dev/openfga/sdk/util/Pair.java +++ b/src/main/java/dev/openfga/sdk/util/Pair.java @@ -12,6 +12,11 @@ package dev.openfga.sdk.util; +import static dev.openfga.sdk.api.client.ApiClient.urlEncode; +import static dev.openfga.sdk.util.StringUtil.isNullOrWhitespace; + +import java.util.Optional; + public class Pair { private String name = ""; private String value = ""; @@ -21,6 +26,17 @@ public Pair(String name, String value) { setValue(value); } + public static Optional of(String name, Object value) { + if (isNullOrWhitespace(name) || value == null) { + return Optional.empty(); + } + return Optional.of(new Pair(name, value.toString())); + } + + public String asQueryStringPair() { + return urlEncode(name) + "=" + urlEncode(value); + } + private void setName(String name) { if (!isValidString(name)) { return; diff --git a/src/test/java/dev/openfga/sdk/api/OpenFgaApiTest.java b/src/test/java/dev/openfga/sdk/api/OpenFgaApiTest.java index fe955ff..0662610 100644 --- a/src/test/java/dev/openfga/sdk/api/OpenFgaApiTest.java +++ b/src/test/java/dev/openfga/sdk/api/OpenFgaApiTest.java @@ -204,12 +204,12 @@ public void createStoreTest() throws Exception { @Test public void createStore_bodyRequired() { // When - ExecutionException execException = assertThrows( - ExecutionException.class, () -> fga.createStore(null).get()); + var exception = assertThrows( + FgaInvalidParameterException.class, () -> fga.createStore(null).get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'body' when calling createStore", exception.getMessage()); + assertEquals( + "Required parameter CreateStoreRequest was invalid when calling createStore.", exception.getMessage()); } @Test @@ -296,12 +296,11 @@ public void getStoreTest() throws Exception { @Test public void getStore_storeIdRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.getStore(null).get()); + var exception = assertThrows( + FgaInvalidParameterException.class, () -> fga.getStore(null).get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'storeId' when calling getStore", exception.getMessage()); + assertEquals("Required parameter storeId was invalid when calling expand.", exception.getMessage()); } @Test @@ -384,12 +383,11 @@ public void deleteStoreTest() throws Exception { @Test public void deleteStore_storeIdRequired() { // When - ExecutionException execException = assertThrows( - ExecutionException.class, () -> fga.deleteStore(null).get()); + var exception = assertThrows( + FgaInvalidParameterException.class, () -> fga.deleteStore(null).get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'storeId' when calling deleteStore", exception.getMessage()); + assertEquals("Required parameter storeId was invalid when calling deleteStore.", exception.getMessage()); } @Test @@ -1358,25 +1356,21 @@ public void check() throws Exception { @Test public void check_storeIdRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.check(null, new CheckRequest()) - .get()); + var exception = assertThrows(FgaInvalidParameterException.class, () -> fga.check(null, new CheckRequest()) + .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'storeId' when calling check", exception.getMessage()); + assertEquals("Required parameter storeId was invalid when calling check.", exception.getMessage()); } @Test public void check_bodyRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.check(DEFAULT_STORE_ID, null) - .get()); + var exception = assertThrows(FgaInvalidParameterException.class, () -> fga.check(DEFAULT_STORE_ID, null) + .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'body' when calling check", exception.getMessage()); + assertEquals("Required parameter CheckRequest was invalid when calling check.", exception.getMessage()); } @Test @@ -1487,25 +1481,21 @@ public void expandTest() throws Exception { @Test public void expand_storeIdRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.expand(null, new ExpandRequest()) - .get()); + var exception = assertThrows(FgaInvalidParameterException.class, () -> fga.expand(null, new ExpandRequest()) + .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'storeId' when calling expand", exception.getMessage()); + assertEquals("Required parameter storeId was invalid when calling expand.", exception.getMessage()); } @Test public void expand_bodyRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.expand(DEFAULT_STORE_ID, null) - .get()); + var exception = assertThrows(FgaInvalidParameterException.class, () -> fga.expand(DEFAULT_STORE_ID, null) + .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'body' when calling expand", exception.getMessage()); + assertEquals("Required parameter ExpandRequest was invalid when calling expand.", exception.getMessage()); } @Test @@ -1603,25 +1593,22 @@ public void listObjectsTest() throws Exception { @Test public void listObjects_storeIdRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.listObjects(null, new ListObjectsRequest()) + var exception = + assertThrows(FgaInvalidParameterException.class, () -> fga.listObjects(null, new ListObjectsRequest()) .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'storeId' when calling listObjects", exception.getMessage()); + assertEquals("Required parameter storeId was invalid when calling expand.", exception.getMessage()); } @Test public void listObjects_bodyRequired() { // When - ExecutionException execException = - assertThrows(ExecutionException.class, () -> fga.listObjects(DEFAULT_STORE_ID, null) - .get()); + var exception = assertThrows(FgaInvalidParameterException.class, () -> fga.listObjects(DEFAULT_STORE_ID, null) + .get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'body' when calling listObjects", exception.getMessage()); + assertEquals("Required parameter ExpandRequest was invalid when calling expand.", exception.getMessage()); } @Test diff --git a/src/test/java/dev/openfga/sdk/api/client/OpenFgaClientTest.java b/src/test/java/dev/openfga/sdk/api/client/OpenFgaClientTest.java index de09cf7..78448fc 100644 --- a/src/test/java/dev/openfga/sdk/api/client/OpenFgaClientTest.java +++ b/src/test/java/dev/openfga/sdk/api/client/OpenFgaClientTest.java @@ -256,8 +256,9 @@ public void createStore_bodyRequired() { ExecutionException.class, () -> fga.createStore(null).get()); // Then - var exception = assertInstanceOf(ApiException.class, execException.getCause()); - assertEquals("Missing the required parameter 'body' when calling createStore", exception.getMessage()); + var exception = assertInstanceOf(FgaInvalidParameterException.class, execException.getCause()); + assertEquals( + "Required parameter CreateStoreRequest was invalid when calling createStore.", exception.getMessage()); } @Test