1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.adservices.data.measurement; 18 19 import android.adservices.measurement.DeletionRequest; 20 import android.net.Uri; 21 import android.util.Pair; 22 23 import androidx.annotation.NonNull; 24 import androidx.annotation.Nullable; 25 26 import com.android.adservices.service.measurement.Attribution; 27 import com.android.adservices.service.measurement.EventReport; 28 import com.android.adservices.service.measurement.EventSurfaceType; 29 import com.android.adservices.service.measurement.KeyValueData; 30 import com.android.adservices.service.measurement.KeyValueData.DataType; 31 import com.android.adservices.service.measurement.Source; 32 import com.android.adservices.service.measurement.Trigger; 33 import com.android.adservices.service.measurement.aggregation.AggregateEncryptionKey; 34 import com.android.adservices.service.measurement.aggregation.AggregateReport; 35 import com.android.adservices.service.measurement.registration.AsyncRegistration; 36 import com.android.adservices.service.measurement.reporting.DebugReport; 37 38 import java.time.Instant; 39 import java.util.Collection; 40 import java.util.List; 41 import java.util.Map; 42 import java.util.Optional; 43 import java.util.Set; 44 45 /** Interface for Measurement related data access operations. */ 46 public interface IMeasurementDao { 47 /** Set the transaction. */ setTransaction(ITransaction transaction)48 void setTransaction(ITransaction transaction); 49 50 /** Add an entry to the Trigger datastore. */ insertTrigger(Trigger trigger)51 void insertTrigger(Trigger trigger) throws DatastoreException; 52 53 /** Returns list of ids for all pending {@link Trigger}. */ getPendingTriggerIds()54 List<String> getPendingTriggerIds() throws DatastoreException; 55 56 /** 57 * Queries and returns the {@link Source}. 58 * 59 * @param sourceId ID of the requested Source 60 * @return the requested Source 61 */ getSource(@onNull String sourceId)62 Source getSource(@NonNull String sourceId) throws DatastoreException; 63 64 /** 65 * Queries and returns the {@link Source}'s destinations. 66 * 67 * @param sourceId ID of the requested Source 68 * @return a Pair of lists of app destination and web destination Uris 69 */ getSourceDestinations(@onNull String sourceId)70 Pair<List<Uri>, List<Uri>> getSourceDestinations(@NonNull String sourceId) 71 throws DatastoreException; 72 73 /** 74 * Queries and returns the {@link Source}'s attribution scopes. 75 * 76 * @param sourceId ID of the requested Source. 77 * @return a list of attribution scopes. 78 */ getSourceAttributionScopes(@onNull String sourceId)79 List<String> getSourceAttributionScopes(@NonNull String sourceId) throws DatastoreException; 80 81 /** 82 * Updates existing sources based on the following criteria for attribution scope: 83 * 84 * <ol> 85 * <li>Deactivates sources with {@link Source#getMaxEventStates()} different from {@code 86 * pendingSource}. 87 * <li>Deactivates sources with {@link Source#getAttributionScopeLimit()} smaller than {@code 88 * pendingSource}. 89 * <li>Removes attribution scopes for existing sources not selected as the latest k 90 * attribution scopes, where k = {@code pendingSource#getAttributionScopeLimit()}. 91 * </ol> 92 * 93 * @param pendingSource The pending source to compare against existing sources. 94 * @throws DatastoreException If an error occurs while processing the data in the datastore. 95 */ updateSourcesForAttributionScope(@onNull Source pendingSource)96 void updateSourcesForAttributionScope(@NonNull Source pendingSource) throws DatastoreException; 97 98 /** 99 * Queries and returns the {@link Source}. 100 * 101 * @param sourceId ID of the requested Source 102 * @return the source registrant from requested Source 103 */ getSourceRegistrant(@onNull String sourceId)104 String getSourceRegistrant(@NonNull String sourceId) throws DatastoreException; 105 106 /** 107 * Queries and returns the {@link Trigger}. 108 * 109 * @param triggerId Id of the request Trigger 110 * @return the requested Trigger 111 */ getTrigger(String triggerId)112 Trigger getTrigger(String triggerId) throws DatastoreException; 113 114 /** 115 * Fetches the count of aggregate reports for the provided destination. 116 * 117 * @param attributionDestination Uri for the destination 118 * @param destinationType DestinationType App/Web 119 * @return number of aggregate reports in the database attributed to the provided destination 120 */ getNumAggregateReportsPerDestination( @onNull Uri attributionDestination, @EventSurfaceType int destinationType)121 int getNumAggregateReportsPerDestination( 122 @NonNull Uri attributionDestination, @EventSurfaceType int destinationType) 123 throws DatastoreException; 124 125 /** 126 * Fetches the count of aggregate reports for the provided source id. 127 * 128 * @param sourceId source id 129 * @return number of aggregate reports in the database attributed to the provided source id. 130 */ getNumAggregateReportsPerSource(@onNull String sourceId)131 int getNumAggregateReportsPerSource(@NonNull String sourceId) throws DatastoreException; 132 133 /** 134 * Fetches the count of event reports for the provided destination. 135 * 136 * @param attributionDestination Uri for the destination 137 * @param destinationType DestinationType App/Web 138 * @return number of event reports in the database attributed to the provided destination 139 */ getNumEventReportsPerDestination( @onNull Uri attributionDestination, @EventSurfaceType int destinationType)140 int getNumEventReportsPerDestination( 141 @NonNull Uri attributionDestination, @EventSurfaceType int destinationType) 142 throws DatastoreException; 143 144 /** 145 * Gets the number of sources associated to a publisher. 146 * 147 * @param publisherUri Uri for the publisher 148 * @param publisherType PublisherType App/Web 149 * @return Number of sources registered for the given publisher 150 */ getNumSourcesPerPublisher(Uri publisherUri, @EventSurfaceType int publisherType)151 long getNumSourcesPerPublisher(Uri publisherUri, @EventSurfaceType int publisherType) 152 throws DatastoreException; 153 154 /** Gets the number of triggers associated to a destination. */ getNumTriggersPerDestination(Uri destination, @EventSurfaceType int destinationType)155 long getNumTriggersPerDestination(Uri destination, @EventSurfaceType int destinationType) 156 throws DatastoreException; 157 158 /** 159 * Returns a list of app names that have measurement data. These app names are not part of the 160 * installedApps list. 161 * 162 * @param installedApps app names with their android-app:// scheme 163 * @return list of app names with their android-app:// scheme 164 * @throws DatastoreException if transaction is not active 165 */ getUninstalledAppNamesHavingMeasurementData(List<Uri> installedApps)166 List<Uri> getUninstalledAppNamesHavingMeasurementData(List<Uri> installedApps) 167 throws DatastoreException; 168 169 /** 170 * Gets the count of distinct reporting origins in the Attribution table in a time window with 171 * matching publisher and destination, excluding a given reporting origin. 172 */ countDistinctReportingOriginsPerPublisherXDestInAttribution( Uri sourceSite, Uri destination, Uri excludedReportingOrigin, long windowStartTime, long windowEndTime)173 Integer countDistinctReportingOriginsPerPublisherXDestInAttribution( 174 Uri sourceSite, 175 Uri destination, 176 Uri excludedReportingOrigin, 177 long windowStartTime, 178 long windowEndTime) 179 throws DatastoreException; 180 181 /** 182 * Gets the count of distinct Uris of destinations in the Source table in a time window with 183 * matching publisher, enrollment, and unexpired; excluding given destinations. 184 */ countDistinctDestPerPubXEnrollmentInUnexpiredSourceInWindow( Uri publisher, @EventSurfaceType int publisherType, String enrollmentId, List<Uri> excludedDestinations, @EventSurfaceType int destinationType, long windowStartTime, long windowEndTime)185 Integer countDistinctDestPerPubXEnrollmentInUnexpiredSourceInWindow( 186 Uri publisher, 187 @EventSurfaceType int publisherType, 188 String enrollmentId, 189 List<Uri> excludedDestinations, 190 @EventSurfaceType int destinationType, 191 long windowStartTime, 192 long windowEndTime) 193 throws DatastoreException; 194 195 /** 196 * Gets the count of distinct Uris of destinations in the Source table with matching publisher, 197 * enrollment, and unexpired; excluding given destinations. 198 */ countDistinctDestinationsPerPubXEnrollmentInUnexpiredSource( Uri publisher, @EventSurfaceType int publisherType, String enrollmentId, List<Uri> excludedDestinations, @EventSurfaceType int destinationType, long windowEndTime)199 Integer countDistinctDestinationsPerPubXEnrollmentInUnexpiredSource( 200 Uri publisher, 201 @EventSurfaceType int publisherType, 202 String enrollmentId, 203 List<Uri> excludedDestinations, 204 @EventSurfaceType int destinationType, 205 long windowEndTime) 206 throws DatastoreException; 207 208 /** 209 * Gets the count of distinct Uris of destinations in the Source table in a time window with 210 * matching publisher; excluding given destinations. 211 */ countDistinctDestinationsPerPublisherPerRateLimitWindow( Uri publisher, @EventSurfaceType int publisherType, List<Uri> excludedDestinations, @EventSurfaceType int destinationType, long windowStartTime, long windowEndTime)212 Integer countDistinctDestinationsPerPublisherPerRateLimitWindow( 213 Uri publisher, 214 @EventSurfaceType int publisherType, 215 List<Uri> excludedDestinations, 216 @EventSurfaceType int destinationType, 217 long windowStartTime, 218 long windowEndTime) 219 throws DatastoreException; 220 221 /** 222 * Gets the count of sources in the source table in a time period before event time with 223 * matching publisher, enrollment; excluding the given registration origin. 224 */ countSourcesPerPublisherXEnrollmentExcludingRegOrigin( Uri registrationOrigin, Uri publisher, @EventSurfaceType int publisherType, String enrollmentId, long eventTime, long timePeriodInMs)225 Integer countSourcesPerPublisherXEnrollmentExcludingRegOrigin( 226 Uri registrationOrigin, 227 Uri publisher, 228 @EventSurfaceType int publisherType, 229 String enrollmentId, 230 long eventTime, 231 long timePeriodInMs) 232 throws DatastoreException; 233 234 /** 235 * Gets the count of distinct IDs of enrollments in the Source table in a time window with 236 * matching publisher and destination; excluding a given reporting origin. 237 */ countDistinctReportingOriginsPerPublisherXDestinationInSource( Uri publisher, @EventSurfaceType int publisherType, List<Uri> destinations, Uri excludedReportingOrigin, long windowStartTime, long windowEndTime)238 Integer countDistinctReportingOriginsPerPublisherXDestinationInSource( 239 Uri publisher, 240 @EventSurfaceType int publisherType, 241 List<Uri> destinations, 242 Uri excludedReportingOrigin, 243 long windowStartTime, 244 long windowEndTime) 245 throws DatastoreException; 246 247 /** 248 * Updates the {@link Trigger.Status} value for the provided {@link Trigger}. 249 * 250 * @param triggerIds trigger to update 251 * @param status status to apply 252 * @throws DatastoreException database transaction related issues 253 */ updateTriggerStatus(@onNull Collection<String> triggerIds, @Trigger.Status int status)254 void updateTriggerStatus(@NonNull Collection<String> triggerIds, @Trigger.Status int status) 255 throws DatastoreException; 256 257 /** 258 * Add an entry to the Source datastore and returns the source ID. 259 * 260 * @param source Source data to be inserted. 261 * @return source ID, if source ID is null, the record was not saved. 262 */ insertSource(Source source)263 String insertSource(Source source) throws DatastoreException; 264 265 /** 266 * Queries and returns the list of matching {@link Source} for the provided {@link Trigger}. 267 * 268 * @return list of active matching sources; Null in case of SQL failure 269 */ getMatchingActiveSources(Trigger trigger)270 List<Source> getMatchingActiveSources(Trigger trigger) throws DatastoreException; 271 272 /** 273 * Queries and returns the most recent matching delayed {@link Source} (Optional) for the 274 * provided {@link Trigger}. 275 */ getNearestDelayedMatchingActiveSource(@onNull Trigger trigger)276 Optional<Source> getNearestDelayedMatchingActiveSource(@NonNull Trigger trigger) 277 throws DatastoreException; 278 279 /** 280 * Updates the {@link Source.Status} value for the provided list of {@link Source} 281 * 282 * @param sourceIds list of sources. 283 * @param status value to be set 284 */ updateSourceStatus(@onNull Collection<String> sourceIds, @Source.Status int status)285 void updateSourceStatus(@NonNull Collection<String> sourceIds, @Source.Status int status) 286 throws DatastoreException; 287 288 /** 289 * @param sourceId the source ID 290 * @param attributionStatus the source's JSON-encoded attributed triggers 291 * @throws DatastoreException throws DatastoreException 292 */ updateSourceAttributedTriggers(String sourceId, String attributionStatus)293 void updateSourceAttributedTriggers(String sourceId, String attributionStatus) 294 throws DatastoreException; 295 296 /** 297 * Update the value of {@link Source.Status} for the corresponding {@link Source} 298 * 299 * @param source the {@link Source} object. 300 */ updateSourceEventReportDedupKeys(@onNull Source source)301 void updateSourceEventReportDedupKeys(@NonNull Source source) throws DatastoreException; 302 303 /** 304 * Update the set of Aggregate dedup keys contained in the provided {@link Source} 305 * 306 * @param source the {@link Source} object. 307 */ updateSourceAggregateReportDedupKeys(@onNull Source source)308 void updateSourceAggregateReportDedupKeys(@NonNull Source source) throws DatastoreException; 309 310 /** 311 * Updates the value of aggregate contributions for the corresponding {@link Source} 312 * 313 * @param source the {@link Source} object. 314 */ updateSourceAggregateContributions(@onNull Source source)315 void updateSourceAggregateContributions(@NonNull Source source) throws DatastoreException; 316 317 /** 318 * Returns list of all the reports associated with the {@link Source}. 319 * 320 * @param source for querying reports 321 * @return list of relevant eventReports 322 */ getSourceEventReports(Source source)323 List<EventReport> getSourceEventReports(Source source) throws DatastoreException; 324 325 /** 326 * Queries and returns the {@link EventReport}. 327 * 328 * @param eventReportId Id of the request Event Report 329 * @return the requested Event Report; Null in case of SQL failure 330 */ 331 @Nullable getEventReport(String eventReportId)332 EventReport getEventReport(String eventReportId) throws DatastoreException; 333 334 /** 335 * Queries and returns the {@link AggregateReport} 336 * 337 * @param aggregateReportId Id of the request Aggregate Report 338 * @return the request Aggregate Report; Null in case of SQL failure 339 */ 340 @Nullable getAggregateReport(String aggregateReportId)341 AggregateReport getAggregateReport(String aggregateReportId) throws DatastoreException; 342 343 /** 344 * Queries and returns the {@link DebugReport} 345 * 346 * @param debugReportId of the request Debug Report 347 * @return the request Debug Report; Null in case of SQL failure 348 */ 349 @Nullable getDebugReport(String debugReportId)350 DebugReport getDebugReport(String debugReportId) throws DatastoreException; 351 352 /** 353 * Change the status of an event report to DELIVERED 354 * 355 * @param eventReportId the id of the event report to be updated 356 * @param status status of the event report 357 */ markEventReportStatus(String eventReportId, @EventReport.Status int status)358 void markEventReportStatus(String eventReportId, @EventReport.Status int status) 359 throws DatastoreException; 360 361 /** 362 * Change the summary bucket of the event report 363 * 364 * @param eventReportId the id of the event report to be updated 365 * @param summaryBucket the new summary bucket of the report 366 * @throws DatastoreException 367 */ updateEventReportSummaryBucket( @onNull String eventReportId, @NonNull String summaryBucket)368 void updateEventReportSummaryBucket( 369 @NonNull String eventReportId, @NonNull String summaryBucket) throws DatastoreException; 370 ; 371 372 /** 373 * Change the status of an event debug report to DELIVERED 374 * 375 * @param eventReportId the id of the event report to be updated 376 */ markEventDebugReportDelivered(String eventReportId)377 void markEventDebugReportDelivered(String eventReportId) throws DatastoreException; 378 379 /** 380 * Change the status of an aggregate report to DELIVERED 381 * 382 * @param aggregateReportId the id of the event report to be updated 383 * @param status new status to set 384 */ markAggregateReportStatus(String aggregateReportId, @AggregateReport.Status int status)385 void markAggregateReportStatus(String aggregateReportId, @AggregateReport.Status int status) 386 throws DatastoreException; 387 388 /** 389 * Change the status of an aggregate debug report to DELIVERED 390 * 391 * @param aggregateReportId the id of the event report to be updated 392 */ markAggregateDebugReportDelivered(String aggregateReportId)393 void markAggregateDebugReportDelivered(String aggregateReportId) throws DatastoreException; 394 395 /** Saves the {@link EventReport} to the datastore. */ insertEventReport(EventReport eventReport)396 void insertEventReport(EventReport eventReport) throws DatastoreException; 397 398 /** Deletes the {@link EventReport} and associated {@link Attribution} from the datastore. */ deleteEventReportAndAttribution(EventReport eventReport)399 void deleteEventReportAndAttribution(EventReport eventReport) throws DatastoreException; 400 401 /** Deletes the {@link DebugReport} from the datastore. */ deleteDebugReport(String debugReportId)402 void deleteDebugReport(String debugReportId) throws DatastoreException; 403 404 /** 405 * Deletes the {@link DebugReport} from the datastore based on parameters. 406 * 407 * @param registrant 408 * @param start 409 * @param end 410 * @return number of debug records deleted 411 * @throws DatastoreException 412 */ deleteDebugReports(@onNull Uri registrant, @NonNull Instant start, @NonNull Instant end)413 int deleteDebugReports(@NonNull Uri registrant, @NonNull Instant start, @NonNull Instant end) 414 throws DatastoreException; 415 416 /** 417 * Returns list of all event reports that have a scheduled reporting time in the given window. 418 */ getPendingEventReportIdsInWindow(long windowStartTime, long windowEndTime)419 List<String> getPendingEventReportIdsInWindow(long windowStartTime, long windowEndTime) 420 throws DatastoreException; 421 422 /** Returns list of all debug event reports. */ getPendingDebugEventReportIds()423 List<String> getPendingDebugEventReportIds() throws DatastoreException; 424 425 /** Returns list of all pending event reports for a given app right away. */ getPendingEventReportIdsForGivenApp(Uri appName)426 List<String> getPendingEventReportIdsForGivenApp(Uri appName) throws DatastoreException; 427 428 /** 429 * Find the number of entries for a rate limit window, scoped to event- or aggregate-level using 430 * the {@link Source} and {@link Trigger}. Rate-Limit Window: (Scope, Source Site, Destination 431 * Site, Window) from triggerTime. 432 * 433 * @return the number of entries for the window. 434 */ getAttributionsPerRateLimitWindow(@ttribution.Scope int scope, @NonNull Source source, @NonNull Trigger trigger)435 long getAttributionsPerRateLimitWindow(@Attribution.Scope int scope, @NonNull Source source, 436 @NonNull Trigger trigger) throws DatastoreException; 437 438 /** Add an entry in Attribution datastore. */ insertAttribution(@onNull Attribution attribution)439 void insertAttribution(@NonNull Attribution attribution) throws DatastoreException; 440 441 /** Deletes all expired records in measurement tables. */ deleteExpiredRecords( long earliestValidInsertion, int registrationRetryLimit, @Nullable Long earliestValidAppReportInsertion)442 void deleteExpiredRecords( 443 long earliestValidInsertion, 444 int registrationRetryLimit, 445 @Nullable Long earliestValidAppReportInsertion) 446 throws DatastoreException; 447 448 /** 449 * Mark relevant source as install attributed. 450 * 451 * @param uri package identifier 452 * @param eventTimestamp timestamp of installation event 453 */ doInstallAttribution(Uri uri, long eventTimestamp)454 void doInstallAttribution(Uri uri, long eventTimestamp) throws DatastoreException; 455 456 /** 457 * Undo any install attributed source events. 458 * 459 * @param uri package identifier 460 */ undoInstallAttribution(Uri uri)461 void undoInstallAttribution(Uri uri) throws DatastoreException; 462 463 /** Save aggregate encryption key to the datastore. */ insertAggregateEncryptionKey(AggregateEncryptionKey aggregateEncryptionKey)464 void insertAggregateEncryptionKey(AggregateEncryptionKey aggregateEncryptionKey) 465 throws DatastoreException; 466 467 /** 468 * Retrieve all aggregate encryption keys from the datastore whose expiry time is greater than 469 * or equal to {@code expiry}. 470 */ getNonExpiredAggregateEncryptionKeys(Uri coordinator, long expiry)471 List<AggregateEncryptionKey> getNonExpiredAggregateEncryptionKeys(Uri coordinator, long expiry) 472 throws DatastoreException; 473 474 /** Remove aggregate encryption keys from the datastore older than {@code expiry}. */ deleteExpiredAggregateEncryptionKeys(long expiry)475 void deleteExpiredAggregateEncryptionKeys(long expiry) throws DatastoreException; 476 477 /** Save unencrypted aggregate payload to the datastore. */ insertAggregateReport(AggregateReport payload)478 void insertAggregateReport(AggregateReport payload) throws DatastoreException; 479 480 /** Save debug report payload to the datastore. */ insertDebugReport(DebugReport payload)481 void insertDebugReport(DebugReport payload) throws DatastoreException; 482 483 /** 484 * Returns a map of coordinator to pending aggregate reports that have a scheduled reporting 485 * time in the given window. 486 */ getPendingAggregateReportIdsByCoordinatorInWindow( long windowStartTime, long windowEndTime)487 Map<String, List<String>> getPendingAggregateReportIdsByCoordinatorInWindow( 488 long windowStartTime, long windowEndTime) throws DatastoreException; 489 490 /** Returns a map of coordinator to pending aggregate debug reports */ getPendingAggregateDebugReportIdsByCoordinator()491 Map<String, List<String>> getPendingAggregateDebugReportIdsByCoordinator() 492 throws DatastoreException; 493 494 /** Returns list of all debug reports. */ getDebugReportIds()495 List<String> getDebugReportIds() throws DatastoreException; 496 497 /** Returns list of all pending aggregate reports for a given app right away. */ getPendingAggregateReportIdsForGivenApp(Uri appName)498 List<String> getPendingAggregateReportIdsForGivenApp(Uri appName) throws DatastoreException; 499 500 /** 501 * Delete all data generated by Measurement API, except for tables in the exclusion list. 502 * 503 * @param tablesToExclude a {@link List} of tables that won't be deleted. An empty list will 504 * delete every table. 505 */ deleteAllMeasurementData(List<String> tablesToExclude)506 void deleteAllMeasurementData(List<String> tablesToExclude) throws DatastoreException; 507 508 /** 509 * Delete records from source table that match provided source IDs. 510 * 511 * @param sourceIds source IDs to match 512 * @throws DatastoreException database transaction issues 513 */ deleteSources(@onNull Collection<String> sourceIds)514 void deleteSources(@NonNull Collection<String> sourceIds) throws DatastoreException; 515 516 /** 517 * Delete records from trigger table that match provided trigger IDs. 518 * 519 * @param triggerIds trigger IDs to match 520 * @throws DatastoreException database transaction issues 521 */ deleteTriggers(@onNull Collection<String> triggerIds)522 void deleteTriggers(@NonNull Collection<String> triggerIds) throws DatastoreException; 523 524 /** 525 * Delete records from async registration table that match provided async registration IDs. 526 * 527 * @param asyncRegistrationIds async registration IDs to match 528 * @throws DatastoreException database transaction issues 529 */ deleteAsyncRegistrations(@onNull List<String> asyncRegistrationIds)530 void deleteAsyncRegistrations(@NonNull List<String> asyncRegistrationIds) 531 throws DatastoreException; 532 533 /** 534 * Insert a record into the Async Registration Table. 535 * 536 * @param asyncRegistration a {@link AsyncRegistration} to insert into the Async Registration 537 * table 538 */ insertAsyncRegistration(@onNull AsyncRegistration asyncRegistration)539 void insertAsyncRegistration(@NonNull AsyncRegistration asyncRegistration) 540 throws DatastoreException; 541 542 /** 543 * Delete a record from the AsyncRegistration table. 544 * 545 * @param id a {@link String} id of the record to delete from the AsyncRegistration table. 546 */ deleteAsyncRegistration(@onNull String id)547 void deleteAsyncRegistration(@NonNull String id) throws DatastoreException; 548 549 /** 550 * Get the record with the earliest request time and a valid retry count. 551 * 552 * @param retryLimit a long that is used for determining the next valid record to be serviced 553 * @param failedOrigins set of origins that have failed during the current run 554 */ fetchNextQueuedAsyncRegistration(int retryLimit, Set<Uri> failedOrigins)555 AsyncRegistration fetchNextQueuedAsyncRegistration(int retryLimit, Set<Uri> failedOrigins) 556 throws DatastoreException; 557 558 /** 559 * Insert/Update the supplied {@link KeyValueData} object 560 * 561 * @param keyValueData a {@link KeyValueData} to be stored/update 562 * @throws DatastoreException when insertion fails 563 */ insertOrUpdateKeyValueData(@onNull KeyValueData keyValueData)564 void insertOrUpdateKeyValueData(@NonNull KeyValueData keyValueData) throws DatastoreException; 565 566 /** 567 * Returns the {@link KeyValueData} for {key, dataType} pair 568 * 569 * @param key of the stored data 570 * @param dataType of the stored datta 571 * @return {@link KeyValueData} object 572 */ getKeyValueData(@onNull String key, @NonNull DataType dataType)573 KeyValueData getKeyValueData(@NonNull String key, @NonNull DataType dataType) 574 throws DatastoreException; 575 576 /** 577 * Update the retry count for a record in the Async Registration table. 578 * 579 * @param asyncRegistration a {@link AsyncRegistration} for which the retryCount will be updated 580 */ updateRetryCount(@onNull AsyncRegistration asyncRegistration)581 void updateRetryCount(@NonNull AsyncRegistration asyncRegistration) throws DatastoreException; 582 583 /** 584 * Fetches aggregate reports that match either given source or trigger IDs. If A1 is set of 585 * aggregate reports that match any of sourceIds and A2 is set of aggregate reports that match 586 * any of triggerIds, then we delete (A1 U A2). 587 * 588 * @param sourceIds sources to be matched with aggregate reports 589 * @param triggerIds triggers to be matched with aggregate reports 590 */ fetchMatchingAggregateReports( @onNull Collection<String> sourceIds, @NonNull Collection<String> triggerIds)591 List<AggregateReport> fetchMatchingAggregateReports( 592 @NonNull Collection<String> sourceIds, @NonNull Collection<String> triggerIds) 593 throws DatastoreException; 594 595 /** 596 * Fetches event reports that match either given source or trigger IDs. If A1 is set of event 597 * reports that match any of sourceIds and A2 is set of event reports that match any of 598 * triggerIds, then we delete (A1 U A2). 599 * 600 * @param sourceIds sources to be matched with event reports 601 * @param triggerIds triggers to be matched with event reports 602 */ fetchMatchingEventReports( @onNull Collection<String> sourceIds, @NonNull Collection<String> triggerIds)603 List<EventReport> fetchMatchingEventReports( 604 @NonNull Collection<String> sourceIds, @NonNull Collection<String> triggerIds) 605 throws DatastoreException; 606 607 /** 608 * Get source IDs based on trigger IDs for flexible event API 609 * 610 * @param triggerIds triggers to be matched with source 611 * @return the list of sourced ids 612 * @throws DatastoreException throw DatastoreException 613 */ fetchFlexSourceIdsFor(@onNull Collection<String> triggerIds)614 Set<String> fetchFlexSourceIdsFor(@NonNull Collection<String> triggerIds) 615 throws DatastoreException; 616 617 /** Deletes the {@link EventReport}s and associated {@link Attribution}s from the datastore. */ deleteFlexEventReportsAndAttributions(List<EventReport> eventReports)618 void deleteFlexEventReportsAndAttributions(List<EventReport> eventReports) 619 throws DatastoreException; 620 621 /** 622 * Returns list of sources matching registrant, publishers and also in the provided time frame. 623 * It matches registrant and time range (start & end) irrespective of the {@code matchBehavior}. 624 * In the resulting set, if matchBehavior is {@link 625 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_DELETE}, then it 626 * matches origins and domains. In case of {@link 627 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_PRESERVE}, it 628 * returns the records that don't match origins or domain. 629 * 630 * @param registrant registrant to match 631 * @param start event time should be after this instant (inclusive) 632 * @param end event time should be after this instant (inclusive) 633 * @param origins publisher site match 634 * @param domains publisher top level domain matches 635 * @param matchBehavior indicates whether to return matching or inversely matching (everything 636 * except matching) data 637 * @return list of source IDs 638 * @throws DatastoreException database transaction level issues 639 */ fetchMatchingSources( @onNull Uri registrant, @NonNull Instant start, @NonNull Instant end, @NonNull List<Uri> origins, @NonNull List<Uri> domains, @DeletionRequest.MatchBehavior int matchBehavior)640 List<String> fetchMatchingSources( 641 @NonNull Uri registrant, 642 @NonNull Instant start, 643 @NonNull Instant end, 644 @NonNull List<Uri> origins, 645 @NonNull List<Uri> domains, 646 @DeletionRequest.MatchBehavior int matchBehavior) 647 throws DatastoreException; 648 649 /** 650 * Returns list of triggers matching registrant and destinations in the provided time frame. 651 * It matches registrant and time range (start & end) irrespective of the {@code matchBehavior}. 652 * In the resulting set, if matchBehavior is {@link 653 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_DELETE}, then it 654 * matches origins and domains. In case of {@link 655 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_PRESERVE}, it 656 * returns the records that don't match origins or domain. 657 * 658 * @param registrant registrant to match 659 * @param start trigger time should be after this instant (inclusive) 660 * @param end trigger time should be after this instant (inclusive) 661 * @param origins destination site match 662 * @param domains destination top level domain matches 663 * @param matchBehavior indicates whether to return matching or inversely matching (everything 664 * except matching) data 665 * @return list of trigger IDs 666 * @throws DatastoreException database transaction level issues 667 */ fetchMatchingTriggers( @onNull Uri registrant, @NonNull Instant start, @NonNull Instant end, @NonNull List<Uri> origins, @NonNull List<Uri> domains, @DeletionRequest.MatchBehavior int matchBehavior)668 Set<String> fetchMatchingTriggers( 669 @NonNull Uri registrant, 670 @NonNull Instant start, 671 @NonNull Instant end, 672 @NonNull List<Uri> origins, 673 @NonNull List<Uri> domains, 674 @DeletionRequest.MatchBehavior int matchBehavior) 675 throws DatastoreException; 676 677 /** 678 * Returns list of async registrations matching registrant and top origins in the provided time 679 * frame. It matches registrant and time range (start & end) irrespective of the {@code 680 * matchBehavior}. In the resulting set, if matchBehavior is {@link 681 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_DELETE}, then it 682 * matches origins and domains. In case of {@link 683 * android.adservices.measurement.DeletionRequest.MatchBehavior#MATCH_BEHAVIOR_PRESERVE}, it 684 * returns the records that don't match origins or domain. 685 * 686 * @param registrant registrant to match 687 * @param start request time should be after this instant (inclusive) 688 * @param end request time should be after this instant (inclusive) 689 * @param origins top origin site match 690 * @param domains top origin top level domain matches 691 * @param matchBehavior indicates whether to return matching or inversely matching (everything 692 * except matching) data 693 * @return list of async registration IDs 694 * @throws DatastoreException database transaction level issues 695 */ fetchMatchingAsyncRegistrations( @onNull Uri registrant, @NonNull Instant start, @NonNull Instant end, @NonNull List<Uri> origins, @NonNull List<Uri> domains, @DeletionRequest.MatchBehavior int matchBehavior)696 List<String> fetchMatchingAsyncRegistrations( 697 @NonNull Uri registrant, 698 @NonNull Instant start, 699 @NonNull Instant end, 700 @NonNull List<Uri> origins, 701 @NonNull List<Uri> domains, 702 @DeletionRequest.MatchBehavior int matchBehavior) 703 throws DatastoreException; 704 705 /** 706 * Fetches the XNA relevant sources. It includes sources associated to the trigger's enrollment 707 * ID as well as the sources associated to the provided SAN enrollment IDs. 708 * 709 * @param trigger trigger to match 710 * @param xnaEnrollmentIds SAN enrollment IDs to match 711 * @return XNA relevant sources 712 * @throws DatastoreException when SQLite issue occurs 713 */ fetchTriggerMatchingSourcesForXna( @onNull Trigger trigger, @NonNull Collection<String> xnaEnrollmentIds)714 List<Source> fetchTriggerMatchingSourcesForXna( 715 @NonNull Trigger trigger, @NonNull Collection<String> xnaEnrollmentIds) 716 throws DatastoreException; 717 718 /** 719 * Insert an entry of source ID with enrollment ID into the {@link 720 * MeasurementTables.XnaIgnoredSourcesContract#TABLE}. It means that the provided source should 721 * be ignored to be picked up for doing XNA based attribution on the provided enrollment. 722 * 723 * @param sourceId source ID 724 * @param enrollmentId enrollment ID 725 */ insertIgnoredSourceForEnrollment(@onNull String sourceId, @NonNull String enrollmentId)726 void insertIgnoredSourceForEnrollment(@NonNull String sourceId, @NonNull String enrollmentId) 727 throws DatastoreException; 728 729 /** 730 * Increments Retry Counter for EventReporting Records and return the updated retry count. This 731 * is used for Retry Limiting. 732 * 733 * @param id Primary key id of Record in Measurement Event Report Table. 734 * @param reportType KeyValueData.DataType corresponding with Record type being incremented. 735 * @return current report count 736 */ incrementAndGetReportingRetryCount(String id, DataType reportType)737 int incrementAndGetReportingRetryCount(String id, DataType reportType) 738 throws DatastoreException; 739 740 /** 741 * Returns the number of unique AdIds provided by an Ad Tech in web contexts to match with the 742 * platform AdID from app contexts for debug key population in reports. It counts distinct AdIDs 743 * provided by the AdTech across sources and triggers in the DB. 744 * 745 * @param enrollmentId enrollmentId of previous source/trigger registrations to check AdId 746 * provided on registration. 747 * @return number of unique AdIds the AdTech has provided. 748 * @throws DatastoreException when SQLite issue occurs 749 */ countDistinctDebugAdIdsUsedByEnrollment(@onNull String enrollmentId)750 long countDistinctDebugAdIdsUsedByEnrollment(@NonNull String enrollmentId) 751 throws DatastoreException; 752 753 /** 754 * Inserts an entry of app report history with enrollment ID into the {@link 755 * MeasurementTables.AppReportHistoryContract#TABLE}. It means that event / aggregate reports 756 * for the given app destination have been delivered to the registration origin. 757 * 758 * @param appDestination app destination 759 * @param registrationOrigin source registration origin 760 * @param lastReportDeliveredTimestamp last deliver time for the report 761 * @throws DatastoreException when SQLite issue occurs. 762 */ insertOrUpdateAppReportHistory( @onNull Uri appDestination, @NonNull Uri registrationOrigin, long lastReportDeliveredTimestamp)763 void insertOrUpdateAppReportHistory( 764 @NonNull Uri appDestination, 765 @NonNull Uri registrationOrigin, 766 long lastReportDeliveredTimestamp) 767 throws DatastoreException; 768 769 /** 770 * Returns the number of unique navigation sources by reporting origin and registration id. 771 * 772 * @param reportingOrigin the reporting origin to match. 773 * @param registrationId the registration id to match. 774 * @return the number of matched navigation sources. 775 * @throws DatastoreException 776 */ countNavigationSourcesPerReportingOrigin( @onNull Uri reportingOrigin, @NonNull String registrationId)777 long countNavigationSourcesPerReportingOrigin( 778 @NonNull Uri reportingOrigin, @NonNull String registrationId) throws DatastoreException; 779 780 /** 781 * Let matchingSources be unexpired sources that match the provided publisher, publisher type 782 * destination surface type and enrollmentId. Pick and return the sources that have the least 783 * recently used destination excluding the provided list of destinations. 784 * 785 * @param publisher publisher to match 786 * @param publisherType publisher surface type, i.e. app/web to match 787 * @param enrollmentId matching enrollment 788 * @param excludedDestinations destinations to exclude while matching 789 * @param destinationType destination type app/web 790 * @param windowEndTime selected sources' expiry needs to be greater than this time 791 * @return sources with least recently used destination 792 * @throws DatastoreException when accessing the DB fails 793 */ fetchSourceIdsForLruDestinationXEnrollmentXPublisher( Uri publisher, int publisherType, String enrollmentId, List<Uri> excludedDestinations, int destinationType, long windowEndTime)794 List<String> fetchSourceIdsForLruDestinationXEnrollmentXPublisher( 795 Uri publisher, 796 int publisherType, 797 String enrollmentId, 798 List<Uri> excludedDestinations, 799 int destinationType, 800 long windowEndTime) 801 throws DatastoreException; 802 803 /** 804 * Deletes pending aggregate reports for the provided sources. Also delete the attributions that 805 * are associated to those reports. 806 * 807 * @param sourceIds sources to consider to query the pending reports 808 * @throws DatastoreException when accessing the DB fails 809 */ deletePendingAggregateReportsAndAttributionsForSources(List<String> sourceIds)810 void deletePendingAggregateReportsAndAttributionsForSources(List<String> sourceIds) 811 throws DatastoreException; 812 813 /** 814 * Return the timestamp of the latest pending report (Event or Aggregate) in the batching 815 * window. The batching window is calculated as the earliest report's timestamp + batchWindow. 816 * If there are no reports, return null. 817 * 818 * @param batchWindow Size of the batching window, in ms, starting at the next pending report. 819 * @return Latest report's timestamp, in ms, within the batching window. 820 * @throws DatastoreException when SQLite issue occurs 821 */ getLatestReportTimeInBatchWindow(long batchWindow)822 Long getLatestReportTimeInBatchWindow(long batchWindow) throws DatastoreException; 823 } 824