Add device config database

Includes a DataStore, DbAdapter, DbHelper and DeviceConfigService

Test: follow-up

Bug: 263955152
Change-Id: I89ceaa0692043a424b5e76844725a49fd3bb6a0e
diff --git a/service/java/com/android/server/deviceconfig/DeviceConfigServiceImpl.java b/service/java/com/android/server/deviceconfig/DeviceConfigServiceImpl.java
new file mode 100644
index 0000000..7b51b6a
--- /dev/null
+++ b/service/java/com/android/server/deviceconfig/DeviceConfigServiceImpl.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2023 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.server.deviceconfig;
+
+import android.content.Context;
+import android.os.RemoteException;
+
+import com.android.server.deviceconfig.db.DeviceConfigDbAdapter;
+import com.android.server.deviceconfig.db.DeviceConfigDbHelper;
+
+import java.util.Map;
+
+/**
+ * DeviceConfig Service implementation (updatable via Mainline) that uses a SQLite database as a storage mechanism
+ * for the configuration values.
+ *
+ * @hide
+ */
+public class DeviceConfigServiceImpl {
+    private final DeviceConfigDbAdapter mDbAdapter;
+
+    public DeviceConfigServiceImpl(Context context) {
+        DeviceConfigDbHelper dbHelper = new DeviceConfigDbHelper(context);
+        mDbAdapter = new DeviceConfigDbAdapter(dbHelper.getWritableDatabase());
+    }
+
+    public Map<String, String> getProperties(String namespace, String[] names) throws RemoteException {
+        return mDbAdapter.getValuesForNamespace(namespace, names);
+    }
+
+    public boolean setProperties(String namespace, Map<String, String> values) {
+        return mDbAdapter.setValues(namespace, values);
+    }
+
+    public boolean setProperty(String namespace, String key, String value, boolean makeDefault) {
+        return mDbAdapter.setValue(namespace, key, value, makeDefault);
+    }
+}
diff --git a/service/java/com/android/server/deviceconfig/db/DeviceConfigDbAdapter.java b/service/java/com/android/server/deviceconfig/db/DeviceConfigDbAdapter.java
new file mode 100644
index 0000000..2688a93
--- /dev/null
+++ b/service/java/com/android/server/deviceconfig/db/DeviceConfigDbAdapter.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2023 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.server.deviceconfig.db;
+
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.text.TextUtils;
+
+import com.android.server.deviceconfig.db.DeviceConfigDbHelper.Contract.DeviceConfigEntry;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @hide
+ */
+public class DeviceConfigDbAdapter {
+
+    private final SQLiteDatabase mDb;
+
+    public DeviceConfigDbAdapter(SQLiteDatabase db) {
+        mDb = db;
+    }
+
+    public Map<String, String> getValuesForNamespace(String namespace, String... keys) {
+
+        String[] projection = {
+                DeviceConfigEntry.COLUMN_NAME_KEY,
+                DeviceConfigEntry.COLUMN_NAME_VALUE
+        };
+
+        String selection;
+        String[] selectionArgs;
+        if (keys != null && keys.length > 0) {
+            selection = DeviceConfigEntry.COLUMN_NAME_NAMESPACE + " = ? "
+                    + "and " + DeviceConfigEntry.COLUMN_NAME_KEY + " in ( ? ) ";
+            String keySelection = TextUtils.join(",", keys);
+            selectionArgs = new String[]{namespace, keySelection};
+        } else {
+            selection = DeviceConfigEntry.COLUMN_NAME_NAMESPACE + " = ?";
+            selectionArgs = new String[]{namespace};
+        }
+        Cursor cursor = mDb.query(
+                DeviceConfigEntry.TABLE_NAME,
+                projection,
+                selection,
+                selectionArgs,
+                null,
+                null,
+                null
+        );
+
+        Map<String, String> map = new HashMap<>(cursor.getCount());
+        while (cursor.moveToNext()) {
+            String key = cursor.getString(
+                    cursor.getColumnIndexOrThrow(DeviceConfigEntry.COLUMN_NAME_KEY));
+            String value = cursor.getString(
+                    cursor.getColumnIndexOrThrow(DeviceConfigEntry.COLUMN_NAME_VALUE));
+            map.put(key, value);
+        }
+        cursor.close();
+        return map;
+    }
+
+    /**
+     *
+     * @return true if the data was inserted or updated in the database
+     */
+    private boolean insertOrUpdateValue_inTransaction(String namespace, String key, String value) {
+        // TODO(b/265948914): see if this is the most performant way to either insert or update a record
+        ContentValues values = new ContentValues();
+        values.put(DeviceConfigEntry.COLUMN_NAME_NAMESPACE, namespace);
+        values.put(DeviceConfigEntry.COLUMN_NAME_KEY, key);
+        values.put(DeviceConfigEntry.COLUMN_NAME_VALUE, value);
+
+        String where = DeviceConfigEntry.COLUMN_NAME_NAMESPACE + " = ? "
+                + "and " + DeviceConfigEntry.COLUMN_NAME_VALUE + " = ? ";
+
+        String[] whereArgs = {namespace, key};
+        int updatedRows = mDb.update(DeviceConfigEntry.TABLE_NAME, values, where, whereArgs);
+        if (updatedRows == 0) {
+            // this is a new row, we need to insert it
+            long id = mDb.insert(DeviceConfigEntry.TABLE_NAME, null, values);
+            return id != -1;
+        }
+        return updatedRows > 0;
+    }
+
+    /**
+     * Set or update the values in the map into the namespace.
+     *
+     * @return true if all values were set. Returns true if the map is empty.
+     */
+    public boolean setValues(String namespace, Map<String, String> map) {
+        if (map.size() == 0) {
+            return true;
+        }
+        boolean allSucceeded = true;
+        try {
+            mDb.beginTransaction();
+            for (Map.Entry<String, String> entry : map.entrySet()) {
+                // TODO(b/265948914) probably should call yieldIfContendedSafely in this loop
+                allSucceeded &= insertOrUpdateValue_inTransaction(namespace, entry.getKey(),
+                        entry.getValue());
+            }
+            mDb.setTransactionSuccessful();
+        } finally {
+            mDb.endTransaction();
+        }
+        return allSucceeded;
+    }
+
+    /**
+     *
+     * @return true if the value was set
+     */
+    public boolean setValue(String namespace, String key, String value, boolean makeDefault) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put(key, value);
+        return setValues(namespace, map);
+        // TODO(b/265948914) implement make default!
+    }
+
+    public void deleteValue(String namespace, String key) {
+        String where = DeviceConfigEntry.COLUMN_NAME_NAMESPACE + " = ? "
+                + "and " + DeviceConfigEntry.COLUMN_NAME_KEY + " = ? ";
+        String[] whereArgs = { namespace, key };
+        mDb.delete(DeviceConfigEntry.TABLE_NAME, where, whereArgs);
+    }
+}
diff --git a/service/java/com/android/server/deviceconfig/db/DeviceConfigDbHelper.java b/service/java/com/android/server/deviceconfig/db/DeviceConfigDbHelper.java
new file mode 100644
index 0000000..d7c90cc
--- /dev/null
+++ b/service/java/com/android/server/deviceconfig/db/DeviceConfigDbHelper.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2023 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.server.deviceconfig.db;
+
+import android.content.Context;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.provider.BaseColumns;
+
+/**
+ * @hide
+ */
+public class DeviceConfigDbHelper extends SQLiteOpenHelper {
+    public static final int DATABASE_VERSION = 1;
+    public static final String DATABASE_NAME = "config_infrastructure.db";
+
+    /**
+     * TODO(b/265948914) / to consider:
+     *
+     * - enforce uniqueness of (namespace, key) pairs
+     * - synchronize calls that modify the db (maybe reads too?)
+     * - probably use a read/write lock
+     * - per-process caching of results so we don't go to the db every time
+     * - test the sql commands to make sure they work well (e.g. where clauses are
+     * written properly)
+     * - check the performance of the sql commands and look for optimizations
+     * - write a test for adapter.setProperties that has some but not all
+     * preexisting properties
+     * - Settings.Config has a concept "makeDefault" which is not implemented here
+     * - ensure that any sql exceptions are not thrown to the callers (where methods
+     * can return
+     * false)
+     * - see what happens if a caller starts observing changes before the database
+     * is loaded/ready (early in the boot process)
+     * - I've seen strict mode alerts about doing I/O in the main thread after a
+     * device boots. Maybe we can't avoid it but double check.
+     * - finish API implementation in DatabaseDataStore
+     */
+
+    interface Contract {
+        class DeviceConfigEntry implements BaseColumns {
+            public static final String TABLE_NAME = "config";
+            public static final String COLUMN_NAME_NAMESPACE = "namespace";
+            public static final String COLUMN_NAME_KEY = "config_key";
+            public static final String COLUMN_NAME_VALUE = "config_value";
+        }
+    }
+
+    private static final String SQL_CREATE_ENTRIES =
+            "CREATE TABLE " + Contract.DeviceConfigEntry.TABLE_NAME + " (" +
+                    Contract.DeviceConfigEntry._ID + " INTEGER PRIMARY KEY," +
+                    Contract.DeviceConfigEntry.COLUMN_NAME_NAMESPACE + " TEXT," +
+                    Contract.DeviceConfigEntry.COLUMN_NAME_KEY + " TEXT," +
+                    Contract.DeviceConfigEntry.COLUMN_NAME_VALUE + " TEXT)";
+
+    public DeviceConfigDbHelper(Context context) {
+        super(context, DATABASE_NAME, null, DATABASE_VERSION);
+    }
+
+    @Override
+    public void onCreate(SQLiteDatabase db) {
+        db.execSQL(SQL_CREATE_ENTRIES);
+    }
+
+    @Override
+    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+        // no op for now
+    }
+
+}