summaryrefslogtreecommitdiff
path: root/sdksandbox/framework/java/android/app/sdksandbox/SharedPreferencesSyncManager.java
blob: 5e0c3837835fb806511ee02bf843254d2e14289c (plain)
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
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * 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 android.app.sdksandbox;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Syncs specified keys in default {@link SharedPreferences} to Sandbox.
 *
 * <p>This class is a singleton since we want to maintain sync between app process and sandbox
 * process.
 *
 * @hide
 */
public class SharedPreferencesSyncManager {

    private static final String TAG = "SdkSandboxSyncManager";
    private static ArrayMap<String, SharedPreferencesSyncManager> sInstanceMap = new ArrayMap<>();
    private final ISdkSandboxManager mService;
    private final Context mContext;
    private final Object mLock = new Object();
    private final ISharedPreferencesSyncCallback mCallback = new SharedPreferencesSyncCallback();

    @GuardedBy("mLock")
    private boolean mWaitingForSandbox = false;

    // Set to a listener after initial bulk sync is successful
    @GuardedBy("mLock")
    private ChangeListener mListener = null;

    // Set of keys that this manager needs to keep in sync.
    @GuardedBy("mLock")
    private ArraySet<String> mKeysToSync = new ArraySet<>();

    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
    public SharedPreferencesSyncManager(
            @NonNull Context context, @NonNull ISdkSandboxManager service) {
        mContext = context.getApplicationContext();
        mService = service;
    }

    /**
     * Returns a new instance of this class if there is a new package, otherewise returns a
     * singleton instance.
     */
    public static synchronized SharedPreferencesSyncManager getInstance(
            @NonNull Context context, @NonNull ISdkSandboxManager service) {
        final String packageName = context.getPackageName();
        if (!sInstanceMap.containsKey(packageName)) {
            sInstanceMap.put(packageName, new SharedPreferencesSyncManager(context, service));
        }
        return sInstanceMap.get(packageName);
    }

    /**
     * Adds keys for syncing from app's default {@link SharedPreferences} to SdkSandbox.
     *
     * @see SdkSandboxManager#addSyncedSharedPreferencesKeys(Set)
     */
    public void addSharedPreferencesSyncKeys(@NonNull Set<String> keyNames) {
        // TODO(b/239403323): Validate the parameters in SdkSandboxManager
        synchronized (mLock) {
            mKeysToSync.addAll(keyNames);

            if (mListener == null) {
                mListener = new ChangeListener();
                getDefaultSharedPreferences().registerOnSharedPreferenceChangeListener(mListener);
            }
            syncData();
        }
    }

    /**
     * Removes keys from set of keys that have been added using {@link
     * #addSharedPreferencesSyncKeys(Set)}
     *
     * @see SdkSandboxManager#removeSyncedSharedPreferencesKeys(Set)
     */
    public void removeSharedPreferencesSyncKeys(@NonNull Set<String> keys) {
        synchronized (mLock) {
            mKeysToSync.removeAll(keys);

            final ArrayList<SharedPreferencesKey> keysWithTypeBeingRemoved = new ArrayList<>();

            for (final String key : keys) {
                keysWithTypeBeingRemoved.add(
                        new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING));
            }
            final SharedPreferencesUpdate update =
                    new SharedPreferencesUpdate(keysWithTypeBeingRemoved, new Bundle());
            try {
                mService.syncDataFromClient(
                        mContext.getPackageName(),
                        /*timeAppCalledSystemServer=*/ System.currentTimeMillis(),
                        update,
                        mCallback);
            } catch (RemoteException e) {
                Log.e(TAG, "Couldn't connect to SdkSandboxManagerService: " + e.getMessage());
            }
        }
    }

    /**
     * Returns the set of all keys that are being synced from app's default {@link
     * SharedPreferences} to sandbox.
     */
    public Set<String> getSharedPreferencesSyncKeys() {
        synchronized (mLock) {
            return new ArraySet(mKeysToSync);
        }
    }

    /**
     * Returns true if sync is in waiting state.
     *
     * <p>Sync transitions into waiting state whenever sdksandbox is unavailable. It resumes syncing
     * again when SdkSandboxManager notifies us that sdksandbox is available again.
     */
    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
    public boolean isWaitingForSandbox() {
        synchronized (mLock) {
            return mWaitingForSandbox;
        }
    }

    /**
     * Syncs data to SdkSandbox.
     *
     * <p>Syncs values of specified keys {@link #mKeysToSync} from the default {@link
     * SharedPreferences} of the app.
     *
     * <p>Once bulk sync is complete, it also registers listener for updates which maintains the
     * sync.
     */
    private void syncData() {
        synchronized (mLock) {
            // Do not sync if keys have not been specified by the client.
            if (mKeysToSync.isEmpty()) {
                return;
            }

            bulkSyncData();
        }
    }

    @GuardedBy("mLock")
    private void bulkSyncData() {
        // Collect data in a bundle
        final Bundle data = new Bundle();
        final SharedPreferences pref = getDefaultSharedPreferences();
        final Map<String, ?> allData = pref.getAll();
        final ArrayList<SharedPreferencesKey> keysWithTypeBeingSynced = new ArrayList<>();

        for (int i = 0; i < mKeysToSync.size(); i++) {
            final String key = mKeysToSync.valueAt(i);
            final Object value = allData.get(key);
            if (value == null) {
                // Keep the key missing from the bundle; that means key has been removed.
                // Type of missing key doesn't matter, so we use a random type.
                keysWithTypeBeingSynced.add(
                        new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING));
                continue;
            }
            final SharedPreferencesKey keyWithTypeAdded = updateBundle(data, key, value);
            keysWithTypeBeingSynced.add(keyWithTypeAdded);
        }

        final SharedPreferencesUpdate update =
                new SharedPreferencesUpdate(keysWithTypeBeingSynced, data);
        try {
            mService.syncDataFromClient(
                    mContext.getPackageName(),
                    /*timeAppCalledSystemServer=*/ System.currentTimeMillis(),
                    update,
                    mCallback);
        } catch (RemoteException e) {
            Log.e(TAG, "Couldn't connect to SdkSandboxManagerService: " + e.getMessage());
        }
    }

    private SharedPreferences getDefaultSharedPreferences() {
        final Context appContext = mContext.getApplicationContext();
        return PreferenceManager.getDefaultSharedPreferences(appContext);
    }

    private class ChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences pref, @Nullable String key) {
            // Sync specified keys only
            synchronized (mLock) {
                // Do not sync if we are in waiting state
                if (mWaitingForSandbox) {
                    return;
                }

                if (key == null) {
                    // All keys have been cleared. Bulk sync so that we send null for every key.
                    bulkSyncData();
                    return;
                }

                if (!mKeysToSync.contains(key)) {
                    return;
                }

                final Bundle data = new Bundle();
                SharedPreferencesKey keyWithType;
                final Object value = pref.getAll().get(key);
                if (value != null) {
                    keyWithType = updateBundle(data, key, value);
                } else {
                    keyWithType =
                            new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING);
                }

                final SharedPreferencesUpdate update =
                        new SharedPreferencesUpdate(List.of(keyWithType), data);
                try {
                    mService.syncDataFromClient(
                            mContext.getPackageName(),
                            /*timeAppCalledSystemServer=*/ System.currentTimeMillis(),
                            update,
                            mCallback);
                } catch (RemoteException e) {
                    Log.e(TAG, "Couldn't connect to SdkSandboxManagerService: " + e.getMessage());
                }
            }
        }
    }

    /**
     * Adds key to bundle based on type of value
     *
     * @return SharedPreferenceKey of the key that has been added
     */
    @GuardedBy("mLock")
    private SharedPreferencesKey updateBundle(Bundle data, String key, Object value) {
        final String type = value.getClass().getSimpleName();
        try {
            switch (type) {
                case "String":
                    data.putString(key, value.toString());
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING);
                case "Boolean":
                    data.putBoolean(key, (Boolean) value);
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_BOOLEAN);
                case "Integer":
                    data.putInt(key, (Integer) value);
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_INTEGER);
                case "Float":
                    data.putFloat(key, (Float) value);
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_FLOAT);
                case "Long":
                    data.putLong(key, (Long) value);
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_LONG);
                case "HashSet":
                    // TODO(b/239403323): Verify the set contains string
                    data.putStringArrayList(key, new ArrayList<>((Set<String>) value));
                    return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING_SET);
                default:
                    Log.e(
                            TAG,
                            "Unknown type found in default SharedPreferences for Key: "
                                    + key
                                    + " type: "
                                    + type);
            }
        } catch (ClassCastException ignore) {
            data.remove(key);
            Log.e(
                    TAG,
                    "Wrong type found in default SharedPreferences for Key: "
                            + key
                            + " Type: "
                            + type);
        }
        // By default, assume it's string
        return new SharedPreferencesKey(key, SharedPreferencesKey.KEY_TYPE_STRING);
    }

    private class SharedPreferencesSyncCallback extends ISharedPreferencesSyncCallback.Stub {
        @Override
        public void onSandboxStart() {
            synchronized (mLock) {
                if (mWaitingForSandbox) {
                    // Retry bulk sync if we were waiting for sandbox to start
                    mWaitingForSandbox = false;
                    bulkSyncData();
                }
            }
        }

        @Override
        public void onError(int errorCode, String errorMsg) {
            synchronized (mLock) {
                // Transition to waiting state when sandbox is unavailable
                if (!mWaitingForSandbox
                        && errorCode == ISharedPreferencesSyncCallback.SANDBOX_NOT_AVAILABLE) {
                    Log.w(TAG, "Waiting for SdkSandbox: " + errorMsg);
                    // Wait for sandbox to start. When it starts, server will call onSandboxStart
                    mWaitingForSandbox = true;
                    return;
                }
                Log.e(TAG, "errorCode: " + errorCode + " errorMsg: " + errorMsg);
            }
        }
    }
}