• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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.signals;
18 
19 import android.adservices.common.AdTechIdentifier;
20 import android.annotation.SuppressLint;
21 import android.content.Context;
22 import android.util.AtomicFile;
23 
24 import androidx.annotation.NonNull;
25 
26 import com.android.adservices.LoggerFactory;
27 import com.android.adservices.service.common.compat.FileCompatUtils;
28 import com.android.adservices.shared.common.ApplicationContextSingleton;
29 import com.android.internal.annotations.VisibleForTesting;
30 
31 import com.google.errorprone.annotations.concurrent.GuardedBy;
32 
33 import java.io.File;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.nio.charset.StandardCharsets;
38 import java.util.Objects;
39 
40 /**
41  * Handles persistence and retrieval of encoding logic for buyers. By leveraging Atomic files it
42  * ensures that we do not read half written encoders. This persistence layer is not strictly
43  * sequential, and will honor the last completed write for parallel writes. Multiple encoder write
44  * updates are unlikely to happen.
45  */
46 public final class EncoderPersistenceDao {
47 
48     private static final LoggerFactory.Logger sLogger = LoggerFactory.getFledgeLogger();
49 
50     /**
51      * TODO(ag/24355874) : remove this once ag/24355874 gets merged and utility for filename prefix
52      * becomes available
53      */
54     @VisibleForTesting static final String ADSERVICES_PREFIX = "adservices_";
55 
56     @VisibleForTesting static final String ENCODERS_DIR = ADSERVICES_PREFIX + "encoders";
57     @VisibleForTesting static final String ENCODER_FILE_SUFFIX = ".encoder";
58 
59     @NonNull private File mFilesDir;
60     private static final Object SINGLETON_LOCK = new Object();
61 
62     @GuardedBy("SINGLETON_LOCK")
63     private static volatile EncoderPersistenceDao sInstance;
64 
65     @SuppressLint("NewAdServicesFile")
EncoderPersistenceDao(Context context)66     private EncoderPersistenceDao(Context context) {
67         this.mFilesDir = context.getFilesDir();
68     }
69 
70     /** Provides a singleton instance of {@link EncoderPersistenceDao} */
getInstance()71     public static EncoderPersistenceDao getInstance() {
72         EncoderPersistenceDao singleInstance = sInstance;
73         if (singleInstance != null) {
74             return singleInstance;
75         }
76 
77         synchronized (SINGLETON_LOCK) {
78             if (sInstance == null) {
79                 Context context = ApplicationContextSingleton.get();
80                 sInstance = new EncoderPersistenceDao(context);
81             }
82         }
83         return sInstance;
84     }
85 
86     /**
87      * Stores encoding logic for a buyer
88      *
89      * @param buyer Ad tech for which encoding logic needs to be persisted
90      * @param encodingLogic for encoding raw signals
91      * @return true, if successfully created and written
92      */
persistEncoder(@onNull AdTechIdentifier buyer, @NonNull String encodingLogic)93     public boolean persistEncoder(@NonNull AdTechIdentifier buyer, @NonNull String encodingLogic) {
94         File encoderDir = createEncodersDirectoryIfDoesNotExist();
95         String uniqueFileNamePerBuyer = generateFileNameForBuyer(buyer);
96         File encoderFile = createFileInDirectory(encoderDir, uniqueFileNamePerBuyer);
97         return writeDataToFile(encoderFile, encodingLogic);
98     }
99 
100     /**
101      * Fetches encoding logic for a buyer
102      *
103      * @param buyer Ad tech for which encoding logic is persisted
104      * @return the encoding logic as a String, if not present or in error returns an empty string
105      */
getEncoder(@onNull AdTechIdentifier buyer)106     public String getEncoder(@NonNull AdTechIdentifier buyer) {
107         File encoderDir = createEncodersDirectoryIfDoesNotExist();
108 
109         String uniqueFileNamePerBuyer = generateFileNameForBuyer(buyer);
110         return readDataFromFile(encoderDir, uniqueFileNamePerBuyer);
111     }
112 
113     /**
114      * Deletes encoding logic for a buyer
115      *
116      * @param buyer Ad tech for which encoding logic needs to be deleted
117      * @return true if the encoding logic never existed or was successfully deleted
118      */
deleteEncoder(@onNull AdTechIdentifier buyer)119     public boolean deleteEncoder(@NonNull AdTechIdentifier buyer) {
120         String uniqueFileNamePerBuyer = generateFileNameForBuyer(buyer);
121         File file =
122                 FileCompatUtils.newFileHelper(
123                         FileCompatUtils.newFileHelper(mFilesDir, ENCODERS_DIR),
124                         uniqueFileNamePerBuyer);
125         boolean deletionComplete = false;
126         if (!file.exists()) {
127             deletionComplete = true;
128         } else {
129             AtomicFile atomicFile = new AtomicFile(file);
130             atomicFile.delete();
131             deletionComplete = !file.exists();
132         }
133         return deletionComplete;
134     }
135 
136     /**
137      * Deletes all encoders persisted ever persisted
138      *
139      * @return true if the encoding logics were all deleted
140      */
deleteAllEncoders()141     public boolean deleteAllEncoders() {
142         return deleteDirectory(createEncodersDirectoryIfDoesNotExist());
143     }
144 
145     @VisibleForTesting
createEncodersDirectoryIfDoesNotExist()146     File createEncodersDirectoryIfDoesNotExist() {
147         // This itself does not create a directory or file
148         File encodersDir = FileCompatUtils.newFileHelper(mFilesDir, ENCODERS_DIR);
149         if (!encodersDir.exists()) {
150 
151             // This creates the actual directory
152             if (encodersDir.mkdirs()) {
153                 sLogger.v("New Encoders directory creation succeeded at: `" + encodersDir + "`");
154             } else {
155                 sLogger.e("New Encoders directory creation failed");
156             }
157         } else {
158             sLogger.v("Encoders directory already exists at :" + encodersDir.getPath());
159         }
160         return encodersDir;
161     }
162 
163     @VisibleForTesting
createFileInDirectory(File directory, String fileName)164     File createFileInDirectory(File directory, String fileName) {
165         // This itself does not create a directory or file
166         File file = FileCompatUtils.newFileHelper(directory, fileName);
167         if (!file.isFile()) {
168             try {
169                 // This creates the actual file
170                 if (file.createNewFile()) {
171                     sLogger.v("New Encoder file creation succeeded");
172                 } else {
173                     sLogger.e("New Encoder file creation failed");
174                 }
175             } catch (IOException e) {
176                 sLogger.e("Exception trying to create the file");
177             }
178         } else {
179             sLogger.v("Encoder file already exists at :" + file.getPath());
180         }
181         return file;
182     }
183 
184     @VisibleForTesting
writeDataToFile(File file, String data)185     boolean writeDataToFile(File file, String data) {
186         FileOutputStream fos = null;
187         AtomicFile atomicFile = new AtomicFile(file);
188         try {
189             fos = atomicFile.startWrite();
190             fos.write(data.getBytes(StandardCharsets.UTF_8));
191             atomicFile.finishWrite(fos);
192             // If successful return true
193             return true;
194         } catch (FileNotFoundException e) {
195             sLogger.e(String.format("Could not find file: %s", file.getName()));
196             failWriteToFile(fos, atomicFile);
197         } catch (IOException e) {
198             sLogger.e(String.format("Could not write to file: %s", file.getName()));
199             failWriteToFile(fos, atomicFile);
200         }
201         return false;
202     }
203 
204     /** Closes the file output stream associated with the atomic file */
failWriteToFile(FileOutputStream fos, AtomicFile atomicFile)205     private void failWriteToFile(FileOutputStream fos, AtomicFile atomicFile) {
206         if (fos != null && atomicFile != null) {
207             atomicFile.failWrite(fos);
208         }
209     }
210 
211     @VisibleForTesting
readDataFromFile(File directory, String fileName)212     String readDataFromFile(File directory, String fileName) {
213         try {
214             // This does not create a new file
215             File file = FileCompatUtils.newFileHelper(directory, fileName);
216             AtomicFile atomicFile = new AtomicFile(file);
217             byte[] fileContents = atomicFile.readFully();
218             return new String(fileContents, StandardCharsets.UTF_8);
219         } catch (IOException e) {
220             sLogger.e(String.format("Exception trying to read file: %s", fileName));
221         }
222         return null;
223     }
224 
225     @VisibleForTesting
deleteDirectory(File directory)226     boolean deleteDirectory(File directory) {
227         if (directory.exists() && directory.isDirectory()) {
228             File[] children = directory.listFiles();
229             if (children != null) {
230                 for (File child : children) {
231                     sLogger.v(
232                             String.format(
233                                     "Deleting from path: %s , file: %s",
234                                     child.getPath(), child.getName()));
235                     AtomicFile atomicFile = new AtomicFile(child);
236                     atomicFile.delete();
237                 }
238             }
239         }
240         // This only succeeds if the children files have been deleted first
241         return directory.delete();
242     }
243 
244     /**
245      * Explicitly avoids filename format being changed across systems for a buyer, by giving control
246      * to the persistence layer on how to decide a filename.
247      *
248      * @param buyer Ad tech for which the file has to be stored
249      * @return the String representing filename for the buyer
250      */
251     @VisibleForTesting
generateFileNameForBuyer(@onNull AdTechIdentifier buyer)252     String generateFileNameForBuyer(@NonNull AdTechIdentifier buyer) {
253         Objects.requireNonNull(buyer);
254         return ADSERVICES_PREFIX + buyer + ENCODER_FILE_SUFFIX;
255     }
256 }
257