summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/customaudience/BackgroundFetchJobService.java
blob: ab00789899bb8e2208ac22d9e2f134aa66ec5101 (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
/*
 * 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 com.android.adservices.service.customaudience;

import static com.android.adservices.service.AdServicesConfig.FLEDGE_BACKGROUND_FETCH_JOB_ID;

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;

import com.android.adservices.LogUtil;
import com.android.adservices.concurrency.AdServicesExecutors;
import com.android.adservices.service.Flags;
import com.android.adservices.service.FlagsFactory;
import com.android.adservices.service.consent.ConsentManager;
import com.android.internal.annotations.VisibleForTesting;

import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * Background fetch for FLEDGE Custom Audience API, executing periodic garbage collection and custom
 * audience updates.
 */
public class BackgroundFetchJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters params) {
        LogUtil.d("BackgroundFetchJobService.onStartJob");

        if (!FlagsFactory.getFlags().getFledgeBackgroundFetchEnabled()) {
            LogUtil.d("FLEDGE background fetch is disabled; skipping and cancelling job");
            return skipAndCancelBackgroundJob(params);
        }

        if (FlagsFactory.getFlags().getFledgeCustomAudienceServiceKillSwitch()
                || !ConsentManager.getInstance(this).getConsent().isGiven()) {
            LogUtil.d("FLEDGE Custom Audience API is disabled ; skipping and cancelling job");
            return skipAndCancelBackgroundJob(params);
        }

        // TODO(b/235841960): Consider using com.android.adservices.service.stats.Clock instead of
        //  Java Clock
        Instant jobStartTime = Clock.systemUTC().instant();
        LogUtil.d("Starting FLEDGE background fetch job at %s", jobStartTime.toString());

        AdServicesExecutors.getBackgroundExecutor()
                .execute(
                        () -> {
                            try {
                                BackgroundFetchWorker.getInstance(this)
                                        .runBackgroundFetch(jobStartTime);
                            } catch (InterruptedException exception) {
                                LogUtil.e(
                                        exception,
                                        "FLEDGE background fetch interrupted while waiting for"
                                                + " custom audience updates");
                            } catch (ExecutionException exception) {
                                LogUtil.e(
                                        exception,
                                        "FLEDGE background fetch failed due to internal error");
                            } catch (TimeoutException exception) {
                                LogUtil.e(exception, "FLEDGE background fetch timeout exceeded");
                            }

                            // Never manually reschedule the background fetch job, since it is
                            // already scheduled periodically and should try again multiple times
                            // per day
                            jobFinished(params, false);
                        });

        return true;
    }

    private boolean skipAndCancelBackgroundJob(final JobParameters params) {
        this.getSystemService(JobScheduler.class).cancel(FLEDGE_BACKGROUND_FETCH_JOB_ID);

        jobFinished(params, false);
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        LogUtil.d("BackgroundFetchJobService.onStopJob");
        BackgroundFetchWorker.getInstance(this).stopWork();
        return true;
    }

    /**
     * Attempts to schedule the FLEDGE Background Fetch as a singleton periodic job if it is not
     * already scheduled.
     *
     * <p>The background fetch primarily updates custom audiences' ads and bidding data. It also
     * prunes the custom audience database of any expired data.
     */
    public static void scheduleIfNeeded(Context context, Flags flags, boolean forceSchedule) {
        if (!flags.getFledgeBackgroundFetchEnabled()) {
            LogUtil.v("FLEDGE background fetch is disabled; skipping schedule");
            return;
        }

        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);

        // Scheduling a job can be expensive, and forcing a schedule could interrupt a job that is
        // already in progress
        // TODO(b/221837833): Intelligently decide when to overwrite a scheduled job
        if ((jobScheduler.getPendingJob(FLEDGE_BACKGROUND_FETCH_JOB_ID) == null) || forceSchedule) {
            schedule(context, flags);
            LogUtil.d("Scheduled FLEDGE Background Fetch job");
        } else {
            LogUtil.v("FLEDGE Background Fetch job already scheduled, skipping reschedule");
        }
    }

    /**
     * Actually schedules the FLEDGE Background Fetch as a singleton periodic job.
     *
     * <p>Split out from {@link #scheduleIfNeeded(Context, Flags, boolean)} for mockable testing
     * without pesky permissions.
     */
    @VisibleForTesting
    protected static void schedule(Context context, Flags flags) {
        if (!flags.getFledgeBackgroundFetchEnabled()) {
            LogUtil.v("FLEDGE background fetch is disabled; skipping schedule");
            return;
        }

        final JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
        final JobInfo job =
                new JobInfo.Builder(
                                FLEDGE_BACKGROUND_FETCH_JOB_ID,
                                new ComponentName(context, BackgroundFetchJobService.class))
                        .setRequiresBatteryNotLow(true)
                        .setRequiresDeviceIdle(true)
                        .setPeriodic(
                                flags.getFledgeBackgroundFetchJobPeriodMs(),
                                flags.getFledgeBackgroundFetchJobFlexMs())
                        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                        .setPersisted(true)
                        .build();
        jobScheduler.schedule(job);
    }
}