aboutsummaryrefslogtreecommitdiff
path: root/locationtzprovider/src/main/java/com/android/timezone/location/provider/EnvironmentImpl.java
blob: e1b1fd4cacf5c828c4b49fc9a78fc5cf226954b6 (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
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
/*
 * Copyright (C) 2020 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 com.android.timezone.location.provider;

import static android.location.LocationRequest.QUALITY_BALANCED_POWER_ACCURACY;
import static android.location.LocationRequest.QUALITY_HIGH_ACCURACY;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;

import static com.android.timezone.location.provider.core.LogUtils.LOG_TAG;
import static com.android.timezone.location.provider.core.LogUtils.formatElapsedRealtimeMillis;
import static com.android.timezone.location.provider.core.OfflineLocationTimeZoneDelegate.LOCATION_LISTEN_MODE_ACTIVE;
import static com.android.timezone.location.provider.core.OfflineLocationTimeZoneDelegate.LOCATION_LISTEN_MODE_PASSIVE;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationRequest;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.DeviceConfig;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.timezone.location.lookup.GeoTimeZonesFinder;
import com.android.timezone.location.provider.core.Cancellable;
import com.android.timezone.location.provider.core.Environment;
import com.android.timezone.location.provider.core.LocationListeningAccountant;
import com.android.timezone.location.provider.core.MetricsReporter;
import com.android.timezone.location.provider.core.TimeZoneProviderResult;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;

/**
 * The real implementation of {@link Environment}.
 */
class EnvironmentImpl implements Environment {

    private static final String RESOURCE_CONFIG_PROPERTIES_NAME = "offlineltzprovider.properties";

    /**
     * The config properties key to get the location of the tzs2.dat file to use for time zone
     * boundaries.
     */
    private static final String RESOURCE_CONFIG_KEY_GEODATA_PATH = "geodata.path";

    /**
     * The config properties key for the namespace to pass to {@link android.provider.DeviceConfig}
     * for server-pushed configuration.
     */
    private static final String RESOURCE_CONFIG_KEY_DEVICE_CONFIG_NAMESPACE =
            "deviceconfig.namespace";

    /**
     * The config properties key for the prefix that should be applied to keys passed to
     * {@link android.provider.DeviceConfig}.
     */
    private static final String RESOURCE_CONFIG_KEY_DEVICE_CONFIG_KEY_PREFIX =
            "deviceconfig.key_prefix";

    /**
     * The config properties key for the implementation of {@link MetricsReporter} to use.
     */
    private static final String RESOURCE_CONFIG_METRICS_REPORTER_IMPL = "metrics_reporter.impl";

    /**
     * An identifier that can be used to distinguish between different deployments of the same code.
     */
    private static final String RESOURCE_CONFIG_METRICS_REPORTER_DEPLOYMENT_IDENTIFIER =
            "metrics_reporter.identifier";

    /** An arbitrary value larger than the largest time we might want to hold a wake lock. */
    private static final long WAKELOCK_ACQUIRE_MILLIS = Duration.ofMinutes(1).toMillis();

    /**
     * For every hour spent passive listening, 40 seconds of active listening are allowed, i.e.
     * 90 passive time units : 1 active time units.
     */
    private static final long DEFAULT_PASSIVE_TO_ACTIVE_RATIO = (60 * 60) / 40;
    private static final String DEVICE_CONFIG_KEY_SUFFIX_PASSIVE_TO_ACTIVE_RATIO =
            "passive_to_active_ratio";

    private static final Duration DEFAULT_MINIMUM_PASSIVE_LISTENING_DURATION =
            Duration.ofMinutes(2);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_MINIMUM_PASSIVE_LISTENING_DURATION_MILLIS =
            "min_passive_listening_duration_millis";

    private static final Duration DEFAULT_LOCATION_NOT_KNOWN_AGE_THRESHOLD = Duration.ofMinutes(1);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_LOCATION_NOT_KNOWN_AGE_THRESHOLD_MILLIS =
            "location_not_known_age_threshold_millis";

    private static final Duration DEFAULT_LOCATION_KNOWN_AGE_THRESHOLD = Duration.ofMinutes(15);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_LOCATION_KNOWN_AGE_THRESHOLD_MILLIS =
            "location_known_age_threshold_millis";

    private static final Duration DEFAULT_MINIMUM_ACTIVE_LISTENING_DURATION = Duration.ofSeconds(5);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_MINIMUM_ACTIVE_LISTENING_DURATION_MILLIS =
            "min_active_listening_duration_millis";

    private static final Duration DEFAULT_MAXIMUM_ACTIVE_LISTENING_DURATION =
            Duration.ofSeconds(10);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_MAXIMUM_ACTIVE_LISTENING_DURATION_MILLIS =
            "max_active_listening_duration_millis";

    private static final Duration DEFAULT_INITIAL_ACTIVE_LISTENING_BUDGET =
            DEFAULT_MINIMUM_ACTIVE_LISTENING_DURATION;
    private static final String DEVICE_CONFIG_KEY_SUFFIX_INITIAL_ACTIVE_LISTENING_BUDGET_MILLIS =
            "min_initial_active_listening_budget_millis";

    private static final Duration DEFAULT_MAX_ACTIVE_LISTENING_BUDGET =
            DEFAULT_MAXIMUM_ACTIVE_LISTENING_DURATION.multipliedBy(4);
    private static final String DEVICE_CONFIG_KEY_SUFFIX_MAX_ACTIVE_LISTENING_BUDGET_MILLIS =
            "max_active_listening_budget_millis";

    @NonNull private final LocationManager mLocationManager;
    @NonNull private final Handler mHandler;
    @NonNull private final Consumer<TimeZoneProviderResult> mResultConsumer;
    @NonNull private final HandlerExecutor mExecutor;
    @NonNull private final File mGeoDataFile;
    @NonNull private final PowerManager.WakeLock mWakeLock;
    @NonNull private final String mDeviceConfigNamespace;
    @NonNull private final String mDeviceConfigKeyPrefix;
    @NonNull private final DelegatingLocationListeningAccountant mLocationListeningAccountant;
    @NonNull private final MetricsReporter mMetricsReporter;

    EnvironmentImpl(@NonNull Context context,
            @NonNull Consumer<TimeZoneProviderResult> resultConsumer) {
        mLocationManager = context.getSystemService(LocationManager.class);

        PowerManager powerManager = context.getSystemService(PowerManager.class);
        mWakeLock = powerManager.newWakeLock(PARTIAL_WAKE_LOCK, LOG_TAG + ":wakelock");

        mResultConsumer = Objects.requireNonNull(resultConsumer);
        mHandler = new Handler(Looper.getMainLooper());
        mExecutor = new HandlerExecutor(mHandler);

        Properties configProperties = loadConfigProperties(getClass().getClassLoader());
        mGeoDataFile = new File(configProperties.getProperty(RESOURCE_CONFIG_KEY_GEODATA_PATH));
        mDeviceConfigNamespace = Objects.requireNonNull(
                configProperties.getProperty(RESOURCE_CONFIG_KEY_DEVICE_CONFIG_NAMESPACE));
        mDeviceConfigKeyPrefix = Objects.requireNonNull(
                configProperties.getProperty(RESOURCE_CONFIG_KEY_DEVICE_CONFIG_KEY_PREFIX));

        String metricsReporterClassName =
                configProperties.getProperty(RESOURCE_CONFIG_METRICS_REPORTER_IMPL);
        mMetricsReporter = createMetricsReporter(metricsReporterClassName);

        LocationListeningAccountant realLocationListeningAccountant =
                createRealLocationListeningAccountant();
        mLocationListeningAccountant =
                new DelegatingLocationListeningAccountant(realLocationListeningAccountant);

        Duration initialActiveListeningBudget = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_INITIAL_ACTIVE_LISTENING_BUDGET_MILLIS,
                DEFAULT_INITIAL_ACTIVE_LISTENING_BUDGET);
        mLocationListeningAccountant.depositActiveListeningAmount(initialActiveListeningBudget);

        // Monitor for changes that affect the accountant's configuration.
        DeviceConfig.addOnPropertiesChangedListener(
                mDeviceConfigNamespace, mExecutor, this::handleDeviceConfigChanged);
    }

    private MetricsReporter createMetricsReporter(@NonNull String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return (MetricsReporter) clazz.newInstance();
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException("Unable to instantiate MetricsReporter", e);
        }
    }

    private static Properties loadConfigProperties(ClassLoader classLoader) {
        Properties configProperties = new Properties();
        try (InputStream configStream =
                classLoader.getResourceAsStream(RESOURCE_CONFIG_PROPERTIES_NAME)) {
            if (configStream == null) {
                throw new IllegalStateException("Unable to find config properties"
                        + " resource=" + RESOURCE_CONFIG_PROPERTIES_NAME);
            }
            configProperties.load(configStream);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to load config properties from"
                    + " resource=" + RESOURCE_CONFIG_PROPERTIES_NAME, e);
        }
        return configProperties;
    }

    private void handleDeviceConfigChanged(@NonNull DeviceConfig.Properties properties) {
        LocationListeningAccountant newAccountant = createRealLocationListeningAccountant();
        mLocationListeningAccountant.replaceDelegate(newAccountant);
    }

    @NonNull
    private LocationListeningAccountant createRealLocationListeningAccountant() {
        Duration minPassiveListeningDuration = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_MINIMUM_PASSIVE_LISTENING_DURATION_MILLIS,
                DEFAULT_MINIMUM_PASSIVE_LISTENING_DURATION);
        Duration maxActiveListeningBalance = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_MAX_ACTIVE_LISTENING_BUDGET_MILLIS,
                DEFAULT_MAX_ACTIVE_LISTENING_BUDGET);
        Duration minActiveListeningDuration = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_MINIMUM_ACTIVE_LISTENING_DURATION_MILLIS,
                DEFAULT_MINIMUM_ACTIVE_LISTENING_DURATION);
        Duration maxActiveListeningDuration = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_MAXIMUM_ACTIVE_LISTENING_DURATION_MILLIS,
                DEFAULT_MAXIMUM_ACTIVE_LISTENING_DURATION);
        Duration locationNotKnownAgeThreshold = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_LOCATION_NOT_KNOWN_AGE_THRESHOLD_MILLIS,
                DEFAULT_LOCATION_NOT_KNOWN_AGE_THRESHOLD);
        Duration locationKnownAgeThreshold = getDeviceConfigDuration(
                DEVICE_CONFIG_KEY_SUFFIX_LOCATION_KNOWN_AGE_THRESHOLD_MILLIS,
                DEFAULT_LOCATION_KNOWN_AGE_THRESHOLD);
        long passiveToActiveRatio = getDeviceConfigLong(
                DEVICE_CONFIG_KEY_SUFFIX_PASSIVE_TO_ACTIVE_RATIO,
                DEFAULT_PASSIVE_TO_ACTIVE_RATIO);
        return new RealLocationListeningAccountant(
                minPassiveListeningDuration, maxActiveListeningBalance,
                minActiveListeningDuration, maxActiveListeningDuration,
                locationNotKnownAgeThreshold, locationKnownAgeThreshold,
                passiveToActiveRatio);
    }

    @Override
    @NonNull
    public LocationListeningAccountant getLocationListeningAccountant() {
        return mLocationListeningAccountant;
    }

    @Override
    @NonNull
    public <T> Cancellable requestDelayedCallback(
            @NonNull Consumer<T> callback, @Nullable T callbackToken, @NonNull Duration delay) {
        Objects.requireNonNull(callback);
        Objects.requireNonNull(delay);

        // Deliberate use of an anonymous class as the equality of lambdas is not well defined but
        // instance equality is required for the remove call.
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                callback.accept(callbackToken);
            }
        };

        String identifier = delay + "@" + formatElapsedRealtimeMillis(elapsedRealtimeMillis());
        Cancellable cancellable = new BaseCancellable(identifier) {
            @Override
            public void onCancel() {
                mHandler.removeCallbacks(runnable);
            }
        };

        mHandler.postDelayed(runnable, delay.toMillis());
        return cancellable;
    }

    @Override
    @NonNull
    public Cancellable startPassiveLocationListening(@NonNull Duration duration,
            @NonNull Consumer<LocationListeningResult> listeningResultConsumer,
            @NonNull Consumer<Duration> passiveListeningCompletedCallback) {
        Objects.requireNonNull(duration);
        Objects.requireNonNull(listeningResultConsumer);

        try {
            // Keep a wakelock while we call requestLocationUpdates() so we can calculate a fairly
            // accurate (upper bound) of how long the device has been passively listening.
            acquireWakeLock();
            long startElapsedRealtimeMillis = elapsedRealtimeMillis();

            // Deliberate use of an anonymous class as the equality of lambdas is not well defined.
            LocationListener locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    long resultElapsedRealtimeMillis = elapsedRealtimeMillis();
                    LocationListeningResult result = new LocationListeningResult(
                            LOCATION_LISTEN_MODE_PASSIVE,
                            duration, startElapsedRealtimeMillis,
                            resultElapsedRealtimeMillis,
                            location);

                    // Note: We only log metrics when listening stops (since we're primarily
                    // interested in active usage for system health reasons). Passive listening
                    // continues until it is cancelled or the timeout managed by this class
                    // triggers, so there is no need to do metrics logging here.

                    listeningResultConsumer.accept(result);
                }
            };

            // A value that tries to ensure we will get some updates while listening.
            long minUpdateInterval = duration.dividedBy(3).toMillis();

            // Using the passive provider means we will potentially see GPS-originated locations
            // in addition to just "fused" locationprovider updates.
            // We don't use the setDurationMillis() with a real time, since we handle our own
            // timeout below, which provides an explicit callback when listening stops.
            LocationRequest locationRequest = new LocationRequest.Builder(minUpdateInterval)
                    .setMinUpdateDistanceMeters(0)
                    .setMinUpdateIntervalMillis(minUpdateInterval)
                    .setDurationMillis(Long.MAX_VALUE  /* indefinite updates, until cancelled */)
                    .setMaxUpdates(Integer.MAX_VALUE /* indefinite updates, until cancelled */)
                    .setQuality(QUALITY_BALANCED_POWER_ACCURACY) /* try not to be power hungry */
                    .setMaxUpdateDelayMillis(0 /* no batching */)
                    .build();

            mLocationManager.requestLocationUpdates(
                    LocationManager.PASSIVE_PROVIDER, locationRequest, mExecutor, locationListener);

            String callbackIdentifier = "passive:" + duration + "@"
                    + formatElapsedRealtimeMillis(startElapsedRealtimeMillis);
            Consumer<String> timeoutCallback = token -> {
                // When the timeout triggers we must cancel the location listening.
                mLocationManager.removeUpdates(locationListener);

                // Also calculate the amount of time the device was actually listening. Because
                // passive listening doesn't prevent sleep, we calculate the actual time, not the
                // time we asked for. This is done under a partial wake lock to ensure we don't
                // sleep in the middle and get misleading values.
                try {
                    acquireWakeLock();
                    long actualTimeListeningMillis =
                            elapsedRealtimeMillis() - startElapsedRealtimeMillis;
                    Duration actualTimeListening = Duration.ofMillis(actualTimeListeningMillis);
                    passiveListeningCompletedCallback.accept(actualTimeListening);

                    mMetricsReporter.reportLocationListeningCompletedEvent(
                            LOCATION_LISTEN_MODE_PASSIVE, duration.toMillis(),
                            actualTimeListeningMillis,
                            MetricsReporter.LISTENING_STOPPED_REASON_TIMED_OUT);
                } finally {
                    releaseWakeLock();
                }
            };
            Cancellable timeoutCancellable =
                    requestDelayedCallback(timeoutCallback, callbackIdentifier, duration);

            return new BaseCancellable(callbackIdentifier) {
                @Override
                public void onCancel() {
                    long timeListeningMillis = elapsedRealtimeMillis() - startElapsedRealtimeMillis;
                    mMetricsReporter.reportLocationListeningCompletedEvent(
                            LOCATION_LISTEN_MODE_PASSIVE, duration.toMillis(), timeListeningMillis,
                            MetricsReporter.LISTENING_STOPPED_REASON_CANCELLED);

                    timeoutCancellable.cancel();
                    mLocationManager.removeUpdates(locationListener);
                }
            };
        } finally {
            releaseWakeLock();
        }
    }

    @NonNull
    @Override
    public Cancellable startActiveGetCurrentLocation(@NonNull Duration duration,
            @NonNull Consumer<LocationListeningResult> locationResultConsumer) {
        try {
            // Keep a wakelock while we call getCurrentLocation() so we can calculate a fairly
            // accurate (upper bound) of how long the device has been actively listening when we
            // get a result.
            acquireWakeLock();

            CancellationSignal cancellationSignal = new CancellationSignal();
            long startElapsedRealtimeMillis = elapsedRealtimeMillis();
            String identifier = "active:"  + duration + "@"
                    + formatElapsedRealtimeMillis(startElapsedRealtimeMillis);
            Cancellable locationListenerCancellable = new BaseCancellable(identifier) {
                @Override
                protected void onCancel() {
                    long timeListeningMillis = elapsedRealtimeMillis() - startElapsedRealtimeMillis;
                    mMetricsReporter.reportLocationListeningCompletedEvent(
                            LOCATION_LISTEN_MODE_ACTIVE, duration.toMillis(), timeListeningMillis,
                            MetricsReporter.LISTENING_STOPPED_REASON_CANCELLED);

                    cancellationSignal.cancel();
                }
            };

            long intervalMillis = 0; // Not used
            long requestedDurationMillis = duration.toMillis();
            LocationRequest locationRequest = new LocationRequest.Builder(intervalMillis)
                    .setDurationMillis(requestedDurationMillis)
                    .setQuality(QUALITY_HIGH_ACCURACY /* try to force GPS on when it's needed */)
                    .setMaxUpdateDelayMillis(0 /* no batching */)
                    .build();

            Consumer<Location> locationConsumer = location -> {
                long resultElapsedRealtimeMillis = elapsedRealtimeMillis();
                LocationListeningResult result = new LocationListeningResult(
                        LOCATION_LISTEN_MODE_ACTIVE,
                        duration,
                        startElapsedRealtimeMillis,
                        resultElapsedRealtimeMillis,
                        location);
                mMetricsReporter.reportLocationListeningCompletedEvent(
                        LOCATION_LISTEN_MODE_ACTIVE,
                        result.getRequestedListeningDuration().toMillis(),
                        result.getTotalEstimatedTimeListening().toMillis(),
                        MetricsReporter.LISTENING_STOPPED_REASON_LOCATION_OBTAINED);

                locationResultConsumer.accept(result);
            };

            mLocationManager.getCurrentLocation(
                    LocationManager.FUSED_PROVIDER, locationRequest, cancellationSignal, mExecutor,
                    locationConsumer);

            return locationListenerCancellable;
        } finally {
            releaseWakeLock();
        }
    }

    @Override
    @NonNull
    public GeoTimeZonesFinder createGeoTimeZoneFinder() throws IOException {
        return GeoTimeZonesFinder.create(mGeoDataFile);
    }

    @Override
    public void reportTimeZoneProviderResult(@NonNull TimeZoneProviderResult result) {
        mResultConsumer.accept(result);
    }

    @Override
    public void acquireWakeLock() {
        mWakeLock.acquire(WAKELOCK_ACQUIRE_MILLIS);
    }

    @Override
    public void releaseWakeLock() {
        mWakeLock.release();
    }

    @Override
    public long elapsedRealtimeMillis() {
        return SystemClock.elapsedRealtime();
    }

    @NonNull
    private Duration getDeviceConfigDuration(@NonNull String key, @NonNull Duration defaultValue) {
        Objects.requireNonNull(defaultValue);

        long deviceConfigValue = getDeviceConfigLong(key, -1);
        if (deviceConfigValue < 0) {
            return defaultValue;
        }
        return Duration.ofMillis(deviceConfigValue);
    }

    private long getDeviceConfigLong(@NonNull String keySuffix, long defaultValue) {
        String key = mDeviceConfigKeyPrefix + keySuffix;
        return DeviceConfig.getLong(mDeviceConfigNamespace, key, defaultValue);
    }

    private static class HandlerExecutor implements Executor {
        private final Handler mHandler;

        HandlerExecutor(@NonNull Handler handler) {
            mHandler = Objects.requireNonNull(handler);
        }

        @Override
        public void execute(Runnable command) {
            if (!mHandler.post(command)) {
                throw new RejectedExecutionException(mHandler + " is shutting down");
            }
        }
    }

    private abstract static class BaseCancellable implements Cancellable {
        final String mIdentifier;
        boolean mCancelled = false;

        BaseCancellable(String identifier) {
            mIdentifier = identifier;
        }

        @Override
        public void cancel() {
            if (!mCancelled) {
                mCancelled = true;
                onCancel();
            }
        }

        protected abstract void onCancel();

        @Override
        public String toString() {
            return "{"
                    + "mIdentifier=" + mIdentifier
                    + ", mCancelled=" + mCancelled
                    + '}';
        }
    }
}