summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/measurement/Trigger.java
blob: 13182a1bbb1b1440e2b034539af236bad92ba230 (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
/*
 * 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.measurement;

import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.net.Uri;

import com.android.adservices.service.measurement.aggregation.AggregatableAttributionTrigger;
import com.android.adservices.service.measurement.aggregation.AggregateFilterData;
import com.android.adservices.service.measurement.aggregation.AggregateTriggerData;
import com.android.adservices.service.measurement.util.Validation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

/**
 * POJO for Trigger.
 */

public class Trigger {

    private String mId;
    private Uri mAttributionDestination;
    @EventSurfaceType private int mDestinationType;
    private String mEnrollmentId;
    private long mTriggerTime;
    private String mEventTriggers;
    @Status private int mStatus;
    private Uri mRegistrant;
    private String mAggregateTriggerData;
    private String mAggregateValues;
    private AggregatableAttributionTrigger mAggregatableAttributionTrigger;
    private String mFilters;
    private @Nullable Long mDebugKey;

    @IntDef(value = {
            Status.PENDING,
            Status.IGNORED,
            Status.ATTRIBUTED,
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface Status {
        int PENDING = 0;
        int IGNORED = 1;
        int ATTRIBUTED = 2;
    }

    private Trigger() {
        mStatus = Status.PENDING;
        // Making this default explicit since it anyway occur on an uninitialised int field.
        mDestinationType = EventSurfaceType.APP;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Trigger)) {
            return false;
        }
        Trigger trigger = (Trigger) obj;
        return Objects.equals(mId, trigger.getId())
                && Objects.equals(mAttributionDestination, trigger.mAttributionDestination)
                && mDestinationType == trigger.mDestinationType
                && Objects.equals(mEnrollmentId, trigger.mEnrollmentId)
                && mTriggerTime == trigger.mTriggerTime
                && Objects.equals(mDebugKey, trigger.mDebugKey)
                && Objects.equals(mEventTriggers, trigger.mEventTriggers)
                && mStatus == trigger.mStatus
                && Objects.equals(mRegistrant, trigger.mRegistrant)
                && Objects.equals(mAggregateTriggerData, trigger.mAggregateTriggerData)
                && Objects.equals(mAggregateValues, trigger.mAggregateValues)
                && Objects.equals(
                        mAggregatableAttributionTrigger, trigger.mAggregatableAttributionTrigger)
                && Objects.equals(mFilters, trigger.mFilters);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                mId,
                mAttributionDestination,
                mDestinationType,
                mEnrollmentId,
                mTriggerTime,
                mEventTriggers,
                mStatus,
                mAggregateTriggerData,
                mAggregateValues,
                mAggregatableAttributionTrigger,
                mFilters,
                mDebugKey);
    }

    /**
     * Unique identifier for the {@link Trigger}.
     */
    public String getId() {
        return mId;
    }

    /**
     * Destination where {@link Trigger} occurred.
     */
    public Uri getAttributionDestination() {
        return mAttributionDestination;
    }

    /** Destination type of the {@link Trigger}. */
    @EventSurfaceType
    public int getDestinationType() {
        return mDestinationType;
    }

    /**
     * AdTech enrollment ID.
     */
    public String getEnrollmentId() {
        return mEnrollmentId;
    }

    /**
     * Time when the event occurred.
     */
    public long getTriggerTime() {
        return mTriggerTime;
    }

    /**
     * Event triggers containing priority, de-dup key, trigger data and event-level filters info.
     */
    public String getEventTriggers() {
        return mEventTriggers;
    }

    /** Current state of the {@link Trigger}. */
    @Status
    public int getStatus() {
        return mStatus;
    }

    /**
     * Set the status.
     */
    public void setStatus(@Status int status) {
        mStatus = status;
    }

    /**
     * Registrant of this trigger, primarily an App.
     */
    public Uri getRegistrant() {
        return mRegistrant;
    }

    /**
     * Returns aggregate trigger data string used for aggregation. aggregate trigger data json is a
     * JSONArray.
     * example:
     * [
     * // Each dict independently adds pieces to multiple source keys.
     * {
     *   // Conversion type purchase = 2 at a 9 bit offset, i.e. 2 << 9.
     *   // A 9 bit offset is needed because there are 511 possible campaigns, which
     *   // will take up 9 bits in the resulting key.
     *   "key_piece": "0x400",
     *   // Apply this key piece to:
     *   "source_keys": ["campaignCounts"]
     * },
     * {
     *   // Purchase category shirts = 21 at a 7 bit offset, i.e. 21 << 7.
     *   // A 7 bit offset is needed because there are ~100 regions for the geo key,
     *   // which will take up 7 bits of space in the resulting key.
     *   "key_piece": "0xA80",
     *   // Apply this key piece to:
     *   "source_keys": ["geoValue", "nonMatchingKeyIdsAreIgnored"]
     * }
     * ]
     */
    public String getAggregateTriggerData() {
        return mAggregateTriggerData;
    }

    /**
     * Returns aggregate value string used for aggregation. aggregate value json is a JSONObject.
     * example:
     * {
     *   "campaignCounts": 32768,
     *   "geoValue": 1664
     * }
     */
    public String getAggregateValues() {
        return mAggregateValues;
    }

    /**
     * Returns the AggregatableAttributionTrigger object, which is constructed using the aggregate
     * trigger data string and aggregate values string in Trigger.
     */
    public AggregatableAttributionTrigger getAggregatableAttributionTrigger() {
        return mAggregatableAttributionTrigger;
    }

    /**
     * Returns top level filters. The value is in json format.
     *
     * <p>Will be used for deciding if the trigger can be attributed to the source. If the source
     * fails the filtering against these filters then no reports(event/aggregate) are generated.
     * example: { "key1" : ["value11", "value12"], "key2" : ["value21", "value22"] }
     */
    public String getFilters() {
        return mFilters;
    }

    /** Debug key of {@link Trigger}. */
    public @Nullable Long getDebugKey() {
        return mDebugKey;
    }
    /**
     * Generates AggregatableAttributionTrigger from aggregate trigger data string and aggregate
     * values string in Trigger.
     */
    public Optional<AggregatableAttributionTrigger> parseAggregateTrigger()
            throws JSONException, NumberFormatException {
        if (this.mAggregateTriggerData == null || this.mAggregateValues == null) {
            return Optional.empty();
        }
        JSONArray jsonArray = new JSONArray(this.mAggregateTriggerData);
        List<AggregateTriggerData> triggerDataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // Remove "0x" prefix.
            String hexString = jsonObject.getString("key_piece").substring(2);
            BigInteger bigInteger = new BigInteger(hexString, 16);
            JSONArray sourceKeys = jsonObject.getJSONArray("source_keys");
            Set<String> sourceKeySet = new HashSet<>();
            for (int j = 0; j < sourceKeys.length(); j++) {
                sourceKeySet.add(sourceKeys.getString(j));
            }
            AggregateTriggerData.Builder builder =
                    new AggregateTriggerData.Builder()
                            .setKey(bigInteger)
                            .setSourceKeys(sourceKeySet);
            if (jsonObject.has("filters") && !jsonObject.isNull("filters")) {
                AggregateFilterData filters = new AggregateFilterData.Builder()
                        .buildAggregateFilterData(jsonObject.getJSONObject("filters")).build();
                builder.setFilter(filters);
            }
            if (jsonObject.has("not_filters")
                    && !jsonObject.isNull("not_filters")) {
                AggregateFilterData notFilters = new AggregateFilterData.Builder()
                        .buildAggregateFilterData(
                                jsonObject.getJSONObject("not_filters")).build();
                builder.setNotFilter(notFilters);
            }
            triggerDataList.add(builder.build());
        }
        JSONObject values = new JSONObject(this.mAggregateValues);
        Map<String, Integer> valueMap = new HashMap<>();
        for (String key : values.keySet()) {
            valueMap.put(key, values.getInt(key));
        }
        return Optional.of(new AggregatableAttributionTrigger.Builder()
                .setTriggerData(triggerDataList).setValues(valueMap).build());
    }

    /**
     * Parses the json array under {@link #mEventTriggers} to form a list of {@link EventTrigger}s.
     *
     * @return list of {@link EventTrigger}s
     * @throws JSONException if JSON parsing fails
     */
    public List<EventTrigger> parseEventTriggers() throws JSONException {
        JSONArray jsonArray = new JSONArray(this.mEventTriggers);
        List<EventTrigger> eventTriggers = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            EventTrigger.Builder eventTriggerBuilder = new EventTrigger.Builder();
            JSONObject eventTriggersJsonString = jsonArray.getJSONObject(i);

            if (!eventTriggersJsonString.isNull(EventTriggerContract.TRIGGER_DATA)) {
                eventTriggerBuilder.setTriggerData(
                        eventTriggersJsonString.getLong(EventTriggerContract.TRIGGER_DATA));
            }

            if (!eventTriggersJsonString.isNull(EventTriggerContract.PRIORITY)) {
                eventTriggerBuilder.setTriggerPriority(
                        eventTriggersJsonString.getLong(EventTriggerContract.PRIORITY));
            }

            if (!eventTriggersJsonString.isNull(EventTriggerContract.DEDUPLICATION_KEY)) {
                eventTriggerBuilder.setDedupKey(
                        eventTriggersJsonString.getLong(EventTriggerContract.DEDUPLICATION_KEY));
            }

            if (!eventTriggersJsonString.isNull(EventTriggerContract.FILTERS)) {
                AggregateFilterData filters =
                        new AggregateFilterData.Builder()
                                .buildAggregateFilterData(
                                        eventTriggersJsonString.getJSONObject(
                                                EventTriggerContract.FILTERS))
                                .build();
                eventTriggerBuilder.setFilter(filters);
            }

            if (!eventTriggersJsonString.isNull(EventTriggerContract.NOT_FILTERS)) {
                AggregateFilterData notFilters =
                        new AggregateFilterData.Builder()
                                .buildAggregateFilterData(
                                        eventTriggersJsonString.getJSONObject(
                                                EventTriggerContract.NOT_FILTERS))
                                .build();
                eventTriggerBuilder.setNotFilter(notFilters);
            }
            eventTriggers.add(eventTriggerBuilder.build());
        }

        return eventTriggers;
    }

    /**
     * Builder for {@link Trigger}.
     */
    public static final class Builder {

        private final Trigger mBuilding;

        public Builder() {
            mBuilding = new Trigger();
        }

        /** See {@link Trigger#getId()}. */
        @NonNull
        public Builder setId(String id) {
            mBuilding.mId = id;
            return this;
        }

        /** See {@link Trigger#getAttributionDestination()}. */
        @NonNull
        public Builder setAttributionDestination(Uri attributionDestination) {
            Validation.validateUri(attributionDestination);
            mBuilding.mAttributionDestination = attributionDestination;
            return this;
        }

        /** See {@link Trigger#getDestinationType()}. */
        @NonNull
        public Builder setDestinationType(@EventSurfaceType int destinationType) {
            mBuilding.mDestinationType = destinationType;
            return this;
        }

        /** See {@link Trigger#getEnrollmentId()} ()}. */
        @NonNull
        public Builder setEnrollmentId(String enrollmentId) {
            mBuilding.mEnrollmentId = enrollmentId;
            return this;
        }

        /** See {@link Trigger#getStatus()}. */
        @NonNull
        public Builder setStatus(@Status int status) {
            mBuilding.mStatus = status;
            return this;
        }

        /** See {@link Trigger#getTriggerTime()}. */
        @NonNull
        public Builder setTriggerTime(long triggerTime) {
            mBuilding.mTriggerTime = triggerTime;
            return this;
        }

        /** See {@link Trigger#getEventTriggers()}. */
        @NonNull
        public Builder setEventTriggers(@NonNull String eventTriggers) {
            Validation.validateNonNull(eventTriggers);
            mBuilding.mEventTriggers = eventTriggers;
            return this;
        }

        /** See {@link Trigger#getRegistrant()} */
        @NonNull
        public Builder setRegistrant(@NonNull Uri registrant) {
            Validation.validateUri(registrant);
            mBuilding.mRegistrant = registrant;
            return this;
        }

        /** See {@link Trigger#getAggregateTriggerData()}. */
        @NonNull
        public Builder setAggregateTriggerData(@Nullable String aggregateTriggerData) {
            mBuilding.mAggregateTriggerData = aggregateTriggerData;
            return this;
        }

        /** See {@link Trigger#getAggregateValues()} */
        @NonNull
        public Builder setAggregateValues(@Nullable String aggregateValues) {
            mBuilding.mAggregateValues = aggregateValues;
            return this;
        }

        /** See {@link Trigger#getFilters()} */
        @NonNull
        public Builder setFilters(@Nullable String filters) {
            mBuilding.mFilters = filters;
            return this;
        }

        /** See {@link Trigger#getDebugKey()} ()} */
        public Builder setDebugKey(@Nullable Long debugKey) {
            mBuilding.mDebugKey = debugKey;
            return this;
        }

        /** See {@link Trigger#getAggregatableAttributionTrigger()} */
        @NonNull
        public Builder setAggregatableAttributionTrigger(
                @Nullable AggregatableAttributionTrigger aggregatableAttributionTrigger) {
            mBuilding.mAggregatableAttributionTrigger = aggregatableAttributionTrigger;
            return this;
        }

        /** Build the {@link Trigger}. */
        @NonNull
        public Trigger build() {
            Validation.validateNonNull(
                    mBuilding.mAttributionDestination,
                    mBuilding.mEnrollmentId,
                    mBuilding.mRegistrant);

            return mBuilding;
        }
    }

    /** Event trigger field keys. */
    public interface EventTriggerContract {
        String TRIGGER_DATA = "trigger_data";
        String PRIORITY = "priority";
        String DEDUPLICATION_KEY = "deduplication_key";
        String FILTERS = "filters";
        String NOT_FILTERS = "not_filters";
    }
}