|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package com.google.firebase.remoteconfig.internal; |
| 16 | + |
| 17 | +import static com.google.firebase.remoteconfig.FirebaseRemoteConfig.TAG; |
| 18 | + |
| 19 | +import android.util.Log; |
| 20 | +import androidx.annotation.GuardedBy; |
| 21 | +import androidx.annotation.VisibleForTesting; |
| 22 | +import com.google.android.gms.tasks.Task; |
| 23 | +import com.google.android.gms.tasks.Tasks; |
| 24 | +import com.google.firebase.remoteconfig.ConfigUpdateListener; |
| 25 | +import com.google.firebase.remoteconfig.FirebaseRemoteConfigException; |
| 26 | +import com.google.firebase.remoteconfig.FirebaseRemoteConfigRealtimeUpdateFetchException; |
| 27 | +import com.google.firebase.remoteconfig.FirebaseRemoteConfigRealtimeUpdateStreamException; |
| 28 | +import java.io.BufferedReader; |
| 29 | +import java.io.IOException; |
| 30 | +import java.io.InputStream; |
| 31 | +import java.io.InputStreamReader; |
| 32 | +import java.net.HttpURLConnection; |
| 33 | +import java.util.Random; |
| 34 | +import java.util.Set; |
| 35 | +import java.util.concurrent.Executor; |
| 36 | +import java.util.concurrent.ScheduledExecutorService; |
| 37 | +import java.util.concurrent.TimeUnit; |
| 38 | +import org.json.JSONException; |
| 39 | +import org.json.JSONObject; |
| 40 | + |
| 41 | +public class ConfigAutoFetch { |
| 42 | + |
| 43 | + private static final int FETCH_RETRY = 3; |
| 44 | + |
| 45 | + @GuardedBy("this") |
| 46 | + private final Set<ConfigUpdateListener> eventListeners; |
| 47 | + |
| 48 | + @GuardedBy("this") |
| 49 | + private final HttpURLConnection httpURLConnection; |
| 50 | + |
| 51 | + private final ConfigFetchHandler configFetchHandler; |
| 52 | + private final ConfigUpdateListener retryCallback; |
| 53 | + private final ScheduledExecutorService scheduledExecutorService; |
| 54 | + private final Random random; |
| 55 | + private final Executor executor; |
| 56 | + |
| 57 | + public ConfigAutoFetch( |
| 58 | + HttpURLConnection httpURLConnection, |
| 59 | + ConfigFetchHandler configFetchHandler, |
| 60 | + Set<ConfigUpdateListener> eventListeners, |
| 61 | + ConfigUpdateListener retryCallback, |
| 62 | + Executor executor, |
| 63 | + ScheduledExecutorService scheduledExecutorService) { |
| 64 | + this.httpURLConnection = httpURLConnection; |
| 65 | + this.configFetchHandler = configFetchHandler; |
| 66 | + this.eventListeners = eventListeners; |
| 67 | + this.retryCallback = retryCallback; |
| 68 | + this.scheduledExecutorService = scheduledExecutorService; |
| 69 | + this.random = new Random(); |
| 70 | + this.executor = executor; |
| 71 | + } |
| 72 | + |
| 73 | + public void beginAutoFetch() { |
| 74 | + executor.execute( |
| 75 | + new Runnable() { |
| 76 | + @Override |
| 77 | + public void run() { |
| 78 | + listenForNotifications(); |
| 79 | + } |
| 80 | + }); |
| 81 | + } |
| 82 | + |
| 83 | + private synchronized void propagateErrors(FirebaseRemoteConfigException exception) { |
| 84 | + for (ConfigUpdateListener listener : eventListeners) { |
| 85 | + listener.onError(exception); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + private synchronized void executeAllListenerCallbacks() { |
| 90 | + for (ConfigUpdateListener listener : eventListeners) { |
| 91 | + listener.onEvent(); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + // Check connection and establish InputStream |
| 96 | + @VisibleForTesting |
| 97 | + public synchronized void listenForNotifications() { |
| 98 | + if (httpURLConnection != null) { |
| 99 | + try { |
| 100 | + int responseCode = httpURLConnection.getResponseCode(); |
| 101 | + if (responseCode == 200) { |
| 102 | + InputStream inputStream = httpURLConnection.getInputStream(); |
| 103 | + handleNotifications(inputStream); |
| 104 | + inputStream.close(); |
| 105 | + } else { |
| 106 | + propagateErrors( |
| 107 | + new FirebaseRemoteConfigRealtimeUpdateStreamException( |
| 108 | + "Http connection responded with error: " + responseCode)); |
| 109 | + } |
| 110 | + } catch (IOException ex) { |
| 111 | + propagateErrors( |
| 112 | + new FirebaseRemoteConfigRealtimeUpdateFetchException( |
| 113 | + "Error handling stream messages while fetching.", ex.getCause())); |
| 114 | + } |
| 115 | + } |
| 116 | + retryCallback.onEvent(); |
| 117 | + } |
| 118 | + |
| 119 | + // Auto-fetch new config and execute callbacks on each new message |
| 120 | + private void handleNotifications(InputStream inputStream) throws IOException { |
| 121 | + BufferedReader reader = new BufferedReader((new InputStreamReader(inputStream, "utf-8"))); |
| 122 | + String message; |
| 123 | + while ((message = reader.readLine()) != null) { |
| 124 | + long targetTemplateVersion = configFetchHandler.getTemplateVersionNumber(); |
| 125 | + try { |
| 126 | + JSONObject jsonObject = new JSONObject(message); |
| 127 | + if (jsonObject.has("latestTemplateVersionNumber")) { |
| 128 | + targetTemplateVersion = jsonObject.getLong("latestTemplateVersionNumber"); |
| 129 | + } |
| 130 | + } catch (JSONException ex) { |
| 131 | + Log.i(TAG, "Unable to parse latest config update message."); |
| 132 | + } |
| 133 | + |
| 134 | + autoFetch(FETCH_RETRY, targetTemplateVersion); |
| 135 | + } |
| 136 | + reader.close(); |
| 137 | + } |
| 138 | + |
| 139 | + private void autoFetch(int remainingAttempts, long targetVersion) { |
| 140 | + if (remainingAttempts == 0) { |
| 141 | + propagateErrors( |
| 142 | + new FirebaseRemoteConfigRealtimeUpdateFetchException("Unable to fetch latest version.")); |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + // Needs fetch to occur between 2 - 12 seconds. Randomize to not cause ddos alerts in backend |
| 147 | + int timeTillFetch = random.nextInt(6) + 1; |
| 148 | + scheduledExecutorService.schedule( |
| 149 | + new Runnable() { |
| 150 | + @Override |
| 151 | + public void run() { |
| 152 | + fetchLatestConfig(remainingAttempts, targetVersion); |
| 153 | + } |
| 154 | + }, |
| 155 | + timeTillFetch, |
| 156 | + TimeUnit.SECONDS); |
| 157 | + } |
| 158 | + |
| 159 | + @VisibleForTesting |
| 160 | + public synchronized void fetchLatestConfig(int remainingAttempts, long targetVersion) { |
| 161 | + Task<ConfigFetchHandler.FetchResponse> fetchTask = configFetchHandler.fetch(0L); |
| 162 | + fetchTask.onSuccessTask( |
| 163 | + (fetchResponse) -> { |
| 164 | + long newTemplateVersion = 0; |
| 165 | + if (fetchResponse.getFetchedConfigs() != null) { |
| 166 | + newTemplateVersion = fetchResponse.getFetchedConfigs().getTemplateVersionNumber(); |
| 167 | + } |
| 168 | + |
| 169 | + if (newTemplateVersion >= targetVersion) { |
| 170 | + executeAllListenerCallbacks(); |
| 171 | + } else { |
| 172 | + Log.i( |
| 173 | + TAG, |
| 174 | + "Fetched template version is the same as SDK's current version." |
| 175 | + + " Retrying fetch."); |
| 176 | + // Continue fetching until template version number if greater then current. |
| 177 | + autoFetch(remainingAttempts - 1, targetVersion); |
| 178 | + } |
| 179 | + return Tasks.forResult(null); |
| 180 | + }); |
| 181 | + } |
| 182 | +} |
0 commit comments