Skip to content

Add initial classes for Remote Config API #477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.remoteconfig;

/**
* An interface for managing Firebase Remote Config templates.
*/
interface FirebaseRemoteConfigClient {

/**
* Gets the current active version of the Remote Config template.
*
* @return A {@link RemoteConfigTemplate}.
* @throws FirebaseRemoteConfigException If an error occurs while getting the template.
*/
RemoteConfigTemplate getTemplate() throws FirebaseRemoteConfigException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.remoteconfig;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.api.client.json.JsonFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.ImplFirebaseTrampolines;
import com.google.firebase.IncomingHttpResponse;
import com.google.firebase.internal.AbstractPlatformErrorHandler;
import com.google.firebase.internal.ApiClientUtils;
import com.google.firebase.internal.ErrorHandlingHttpClient;
import com.google.firebase.internal.HttpRequestInfo;
import com.google.firebase.internal.SdkUtils;
import com.google.firebase.remoteconfig.internal.RemoteConfigServiceErrorResponse;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* A helper class for interacting with Firebase Remote Config service.
*/
final class FirebaseRemoteConfigClientImpl implements FirebaseRemoteConfigClient {

private static final String REMOTE_CONFIG_URL = "https://firebaseremoteconfig.googleapis.com/v1/projects/%s/remoteConfig";

private static final Map<String, String> COMMON_HEADERS =
ImmutableMap.of(
"X-Firebase-Client", "fire-admin-java/" + SdkUtils.getVersion(),
// There is a known issue in which the ETag is not properly returned in cases
// where the request does not specify a compression type. Currently, it is
// required to include the header `Accept-Encoding: gzip` or equivalent in all
// requests. https://firebase.google.com/docs/remote-config/use-config-rest#etag_usage_and_forced_updates
"Accept-Encoding", "gzip"
);

private final String remoteConfigUrl;
private final HttpRequestFactory requestFactory;
private final JsonFactory jsonFactory;
private final ErrorHandlingHttpClient<FirebaseRemoteConfigException> httpClient;

private FirebaseRemoteConfigClientImpl(Builder builder) {
checkArgument(!Strings.isNullOrEmpty(builder.projectId));
this.remoteConfigUrl = String.format(REMOTE_CONFIG_URL, builder.projectId);
this.requestFactory = checkNotNull(builder.requestFactory);
this.jsonFactory = checkNotNull(builder.jsonFactory);
HttpResponseInterceptor responseInterceptor = builder.responseInterceptor;
RemoteConfigErrorHandler errorHandler = new RemoteConfigErrorHandler(this.jsonFactory);
this.httpClient = new ErrorHandlingHttpClient<>(requestFactory, jsonFactory, errorHandler)
.setInterceptor(responseInterceptor);
}

@VisibleForTesting
String getRemoteConfigUrl() {
return remoteConfigUrl;
}

@VisibleForTesting
HttpRequestFactory getRequestFactory() {
return requestFactory;
}

@VisibleForTesting
JsonFactory getJsonFactory() {
return jsonFactory;
}

@Override
public RemoteConfigTemplate getTemplate() throws FirebaseRemoteConfigException {
HttpRequestInfo request = HttpRequestInfo.buildGetRequest(remoteConfigUrl)
.addAllHeaders(COMMON_HEADERS);
IncomingHttpResponse response = httpClient.send(request);
RemoteConfigTemplate parsed = httpClient.parse(response, RemoteConfigTemplate.class);
parsed.setETag(getETag(response));
return parsed;
}

private String getETag(IncomingHttpResponse response) {
List<String> etagList = (List<String>) response.getHeaders().get("etag");
checkState(etagList != null && !etagList.isEmpty(),
"ETag header is not available in the server response.");

String etag = etagList.get(0);
checkState(!Strings.isNullOrEmpty(etag),
"ETag header is not available in the server response.");

return etag;
}

static FirebaseRemoteConfigClientImpl fromApp(FirebaseApp app) {
String projectId = ImplFirebaseTrampolines.getProjectId(app);
checkArgument(!Strings.isNullOrEmpty(projectId),
"Project ID is required to access Remote Config service. Use a service "
+ "account credential or set the project ID explicitly via FirebaseOptions. "
+ "Alternatively you can also set the project ID via the GOOGLE_CLOUD_PROJECT "
+ "environment variable.");
return FirebaseRemoteConfigClientImpl.builder()
.setProjectId(projectId)
.setRequestFactory(ApiClientUtils.newAuthorizedRequestFactory(app))
.setJsonFactory(app.getOptions().getJsonFactory())
.build();
}

static Builder builder() {
return new Builder();
}

static final class Builder {

private String projectId;
private HttpRequestFactory requestFactory;
private JsonFactory jsonFactory;
private HttpResponseInterceptor responseInterceptor;

private Builder() { }

Builder setProjectId(String projectId) {
this.projectId = projectId;
return this;
}

Builder setRequestFactory(HttpRequestFactory requestFactory) {
this.requestFactory = requestFactory;
return this;
}

Builder setJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}

Builder setResponseInterceptor(
HttpResponseInterceptor responseInterceptor) {
this.responseInterceptor = responseInterceptor;
return this;
}

FirebaseRemoteConfigClientImpl build() {
return new FirebaseRemoteConfigClientImpl(this);
}
}

private static class RemoteConfigErrorHandler
extends AbstractPlatformErrorHandler<FirebaseRemoteConfigException> {

private RemoteConfigErrorHandler(JsonFactory jsonFactory) {
super(jsonFactory);
}

@Override
protected FirebaseRemoteConfigException createException(FirebaseException base) {
String response = getResponse(base);
RemoteConfigServiceErrorResponse parsed = safeParse(response);
return FirebaseRemoteConfigException.withRemoteConfigErrorCode(
base, parsed.getRemoteConfigErrorCode());
}

private String getResponse(FirebaseException base) {
if (base.getHttpResponse() == null) {
return null;
}

return base.getHttpResponse().getContent();
}

private RemoteConfigServiceErrorResponse safeParse(String response) {
if (!Strings.isNullOrEmpty(response)) {
try {
return jsonFactory.createJsonParser(response)
.parseAndClose(RemoteConfigServiceErrorResponse.class);
} catch (IOException ignore) {
// Ignore any error that may occur while parsing the error response. The server
// may have responded with a non-json payload.
}
}

return new RemoteConfigServiceErrorResponse();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.remoteconfig;

import com.google.firebase.ErrorCode;
import com.google.firebase.FirebaseException;
import com.google.firebase.IncomingHttpResponse;
import com.google.firebase.internal.NonNull;
import com.google.firebase.internal.Nullable;

/**
* Generic exception related to Firebase Remote Config. Check the error code and message for more
* details.
*/
public final class FirebaseRemoteConfigException extends FirebaseException {

private final RemoteConfigErrorCode errorCode;

public FirebaseRemoteConfigException(
@NonNull ErrorCode errorCode,
@NonNull String message,
@Nullable Throwable cause,
@Nullable IncomingHttpResponse response,
@Nullable RemoteConfigErrorCode remoteConfigErrorCode) {
super(errorCode, message, cause, response);
this.errorCode = remoteConfigErrorCode;
}

static FirebaseRemoteConfigException withRemoteConfigErrorCode(
FirebaseException base, @Nullable RemoteConfigErrorCode errorCode) {
return new FirebaseRemoteConfigException(
base.getErrorCode(),
base.getMessage(),
base.getCause(),
base.getHttpResponse(),
errorCode);
}

@Nullable
public RemoteConfigErrorCode getRemoteConfigErrorCode() {
return errorCode;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.remoteconfig;

/**
* Error codes that can be raised by the Remote Config APIs.
*/
public enum RemoteConfigErrorCode {

/**
* One or more arguments specified in the request were invalid.
*/
INVALID_ARGUMENT,

/**
* Internal server error.
*/
INTERNAL,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.remoteconfig;

import com.google.api.client.util.Key;

public final class RemoteConfigTemplate {

@Key("etag")
private String etag;

public String getETag() {
return this.etag;
}

void setETag(String etag) {
this.etag = etag;
}
}
Loading