Diff
Modified: trunk/Source/WebCore/ChangeLog (289138 => 289139)
--- trunk/Source/WebCore/ChangeLog 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/ChangeLog 2022-02-04 23:21:32 UTC (rev 289139)
@@ -1,3 +1,70 @@
+2022-02-04 Ben Nham <[email protected]>
+
+ Add PushDatabase
+ https://bugs.webkit.org/show_bug.cgi?id=234194
+
+ Reviewed by Brady Eidson.
+
+ This adds a persistence layer for push subscriptions stored in webpushd. The operations
+ that we support for now are:
+
+ - inserting a record (used when subscribing)
+ - removing a record (used when unsubscribing)
+ - retrieving a record (used when receiving a push)
+ - enumerating all records by wake state (used to provide the push service the list of all
+ topics that we are subscribed to by wake state)
+
+ There are two basic data types in this data model:
+
+ - Subscriptions, which are uniquely identified by (bundleID, serviceWorkerScope). This
+ stores data that is unique to each subscription, e.g. encryption keys and the HTTP
+ endpoint used by the server to send pushes to this subscription.
+ - SubscriptionSets, which encompass one or more Subscriptions, and are uniquely identified
+ by (bundleID, securityOrigin). This stores state this common to multiple subscriptions,
+ e.g. whether or not all pushes sent by a particular origin should be non-waking.
+
+ For instance, suppose webkit.org in Safari has two service worker registrations scoped to
+ webkit.org/foo and webkit.org/bar. Each registration has successfully registered for push.
+ This would result in three rows in the database:
+
+ 1. Subscription row identified by (bundleID=safari, scope=webkit.org/foo)
+ 2. Subscription row identified by (bundleID=safari, scope=webkit.org/bar)
+ 3. SubscriptionSet row identified by (bundleID=safari, securityOrigin=webkit.org)
+
+ Both subscriptions (1) and (2) are part of the subscription set (3).
+
+ Covered by new API tests.
+
+ * Headers.cmake:
+ * Modules/push-api/PushDatabase.cpp: Added.
+ (WebCore::PushRecord::isolatedCopy const):
+ (WebCore::PushRecord::isolatedCopy):
+ (WebCore::openAndMigrateDatabaseImpl):
+ (WebCore::openAndMigrateDatabase):
+ (WebCore::PushDatabase::create):
+ (WebCore::PushDatabase::PushDatabase):
+ (WebCore::PushDatabase::~PushDatabase):
+ (WebCore::PushDatabase::dispatchOnWorkQueue):
+ (WebCore::PushDatabase::cachedStatementOnQueue):
+ (WebCore::bindExpirationTime):
+ (WebCore::expirationTimeFromValue):
+ (WebCore::completeOnMainQueue):
+ (WebCore::PushDatabase::insertRecord):
+ (WebCore::PushDatabase::removeRecordByIdentifier):
+ (WebCore::makePushRecordFromRow):
+ (WebCore::PushDatabase::getRecordByTopic):
+ (WebCore::PushDatabase::getRecordByBundleIdentifierAndScope):
+ (WebCore::PushDatabase::getIdentifiers):
+ (WebCore::PushDatabase::getTopicsByWakeState):
+ * Modules/push-api/PushDatabase.h: Added.
+ * Sources.txt:
+ * WebCore.xcodeproj/project.pbxproj:
+ * platform/Logging.h:
+ * platform/sql/SQLiteDatabase.cpp:
+ (WebCore::SQLiteDatabase::inMemoryPath):
+ (WebCore::SQLiteDatabase::open):
+ * platform/sql/SQLiteDatabase.h:
+
2022-02-04 Commit Queue <[email protected]>
Unreviewed, reverting r289098.
Modified: trunk/Source/WebCore/Headers.cmake (289138 => 289139)
--- trunk/Source/WebCore/Headers.cmake 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/Headers.cmake 2022-02-04 23:21:32 UTC (rev 289139)
@@ -294,6 +294,7 @@
Modules/permissions/PermissionState.h
Modules/push-api/PushCrypto.h
+ Modules/push-api/PushDatabase.h
Modules/push-api/PushMessageCrypto.h
Modules/push-api/PushPermissionState.h
Modules/push-api/PushSubscriptionData.h
Added: trunk/Source/WebCore/Modules/push-api/PushDatabase.cpp (0 => 289139)
--- trunk/Source/WebCore/Modules/push-api/PushDatabase.cpp (rev 0)
+++ trunk/Source/WebCore/Modules/push-api/PushDatabase.cpp 2022-02-04 23:21:32 UTC (rev 289139)
@@ -0,0 +1,552 @@
+/*
+ * Copyright (C) 2022 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "PushDatabase.h"
+
+#if ENABLE(SERVICE_WORKER)
+
+#include "Logging.h"
+#include "SQLValue.h"
+#include "SQLiteFileSystem.h"
+#include "SQLiteTransaction.h"
+#include "SecurityOrigin.h"
+#include <wtf/CrossThreadCopier.h>
+#include <wtf/Expected.h>
+#include <wtf/FileSystem.h>
+#include <wtf/RunLoop.h>
+#include <wtf/UniqueRef.h>
+
+#define PUSHDB_RELEASE_LOG(fmt, ...) RELEASE_LOG(Push, "%p - PushDatabase::" fmt, this, ##__VA_ARGS__)
+#define PUSHDB_RELEASE_LOG_ERROR(fmt, ...) RELEASE_LOG_ERROR(Push, "%p - PushDatabase::" fmt, this, ##__VA_ARGS__)
+#define PUSHDB_RELEASE_LOG_BIND_ERROR() PUSHDB_RELEASE_LOG_ERROR("Failed to bind statement (%d): %s", m_db->lastError(), m_db->lastErrorMsg())
+
+namespace WebCore {
+
+static constexpr int currentPushDatabaseVersion = 1;
+
+static const ASCIILiteral pushDatabaseSchemaV1Statements[] = {
+ "PRAGMA auto_vacuum=INCREMENTAL"_s,
+ "CREATE TABLE SubscriptionSets("
+ " creationTime INT NOT NULL,"
+ " bundleID TEXT NOT NULL,"
+ " securityOrigin TEXT NOT NULL,"
+ " wakeState INT NOT NULL,"
+ " UNIQUE(bundleID, securityOrigin))"_s,
+ "CREATE TABLE Subscriptions("
+ " creationTime INT NOT NULL,"
+ " subscriptionSetID INT NOT NULL,"
+ " scope TEXT NOT NULL,"
+ " endpoint TEXT NOT NULL,"
+ " topic TEXT NOT NULL UNIQUE,"
+ " serverVAPIDPublicKey BLOB NOT NULL,"
+ " clientPublicKey BLOB NOT NULL,"
+ " clientPrivateKey BLOB NOT NULL,"
+ " sharedAuthSecret BLOB NOT NULL,"
+ " expirationTime INT,"
+ " UNIQUE(scope, subscriptionSetID))"_s,
+ "CREATE INDEX Subscriptions_SubscriptionSetID_Index ON Subscriptions(subscriptionSetID)"_s,
+ "PRAGMA user_version = 1"_s
+};
+
+PushRecord PushRecord::isolatedCopy() const &
+{
+ return {
+ identifier,
+ bundleID.isolatedCopy(),
+ securityOrigin.isolatedCopy(),
+ scope.isolatedCopy(),
+ endpoint.isolatedCopy(),
+ topic.isolatedCopy(),
+ serverVAPIDPublicKey,
+ clientPublicKey,
+ clientPrivateKey,
+ sharedAuthSecret,
+ expirationTime,
+ wakeState
+ };
+}
+
+PushRecord PushRecord::isolatedCopy() &&
+{
+ return {
+ identifier,
+ WTFMove(bundleID).isolatedCopy(),
+ WTFMove(securityOrigin).isolatedCopy(),
+ WTFMove(scope).isolatedCopy(),
+ WTFMove(endpoint).isolatedCopy(),
+ WTFMove(topic).isolatedCopy(),
+ WTFMove(serverVAPIDPublicKey),
+ WTFMove(clientPublicKey),
+ WTFMove(clientPrivateKey),
+ WTFMove(sharedAuthSecret),
+ expirationTime,
+ wakeState
+ };
+}
+
+enum class ShouldDeleteAndRetry { No, Yes };
+
+static Expected<UniqueRef<SQLiteDatabase>, ShouldDeleteAndRetry> openAndMigrateDatabaseImpl(const String& path)
+{
+ ASSERT(!RunLoop::isMain());
+
+ if (path != ":memory:"_s && !FileSystem::fileExists(path) && !FileSystem::makeAllDirectories(FileSystem::parentPath(path))) {
+ RELEASE_LOG_ERROR(Push, "Couldn't create PushDatabase parent directories for path %s", path.utf8().data());
+ return makeUnexpected(ShouldDeleteAndRetry::No);
+ }
+
+ auto db = WTF::makeUniqueRef<SQLiteDatabase>();
+ db->disableThreadingChecks();
+
+ if (!db->open(path)) {
+ RELEASE_LOG_ERROR(Push, "Couldn't open PushDatabase at path %s", path.utf8().data());
+ return makeUnexpected(ShouldDeleteAndRetry::Yes);
+ }
+
+ int version = 0;
+ {
+ auto sql = db->prepareStatement("PRAGMA user_version"_s);
+ if (!sql || sql->step() != SQLITE_ROW) {
+ RELEASE_LOG_ERROR(Push, "Couldn't get PushDatabase version at path %s", path.utf8().data());
+ return makeUnexpected(ShouldDeleteAndRetry::Yes);
+ }
+ version = sql->columnInt(0);
+ }
+
+ if (version && version != currentPushDatabaseVersion) {
+ // FIXME: add migration when we need it.
+ RELEASE_LOG_ERROR(Push, "Found unexpected PushDatabase version: %d (expected: %d) at path: %s", version, currentPushDatabaseVersion, path.utf8().data());
+ return makeUnexpected(ShouldDeleteAndRetry::Yes);
+ }
+
+ if (!version) {
+ SQLiteTransaction transaction(db);
+ transaction.begin();
+
+ for (auto& statement : pushDatabaseSchemaV1Statements) {
+ if (!db->executeCommand(statement)) {
+ RELEASE_LOG_ERROR(Push, "Error executing PushDatabase DDL statement %s at path %s", statement.characters(), path.utf8().data());
+ return makeUnexpected(ShouldDeleteAndRetry::Yes);
+ }
+ }
+
+ transaction.commit();
+ }
+
+ return WTFMove(db);
+}
+
+static std::unique_ptr<SQLiteDatabase> openAndMigrateDatabase(const String& path)
+{
+ ASSERT(!RunLoop::isMain());
+
+ auto result = openAndMigrateDatabaseImpl(path);
+ if (!result && result.error() == ShouldDeleteAndRetry::Yes) {
+ if (path == SQLiteDatabase::inMemoryPath() || !SQLiteFileSystem::deleteDatabaseFile(path)) {
+ RELEASE_LOG(Push, "Failed to delete PushDatabase at path %s; bailing on recreating from scratch", path.utf8().data());
+ return nullptr;
+ }
+
+ RELEASE_LOG(Push, "Deleted PushDatabase at path %s and recreating from scratch", path.utf8().data());
+ result = openAndMigrateDatabaseImpl(path);
+ }
+
+ if (!result)
+ return nullptr;
+
+ auto database = WTFMove(*result);
+ return database.moveToUniquePtr();
+}
+
+void PushDatabase::create(const String& path, CreationHandler&& completionHandler)
+{
+ ASSERT(RunLoop::isMain());
+
+ auto queue = WorkQueue::create("PushDatabase I/O Thread");
+ queue->dispatch([queue, path = crossThreadCopy(path), completionHandler = WTFMove(completionHandler)]() mutable {
+ auto database = openAndMigrateDatabase(path);
+ WorkQueue::main().dispatch([queue = WTFMove(queue), database = WTFMove(database), completionHandler = WTFMove(completionHandler)]() mutable {
+ if (!database) {
+ completionHandler(nullptr);
+ return;
+ }
+
+ completionHandler(std::unique_ptr<PushDatabase>(new PushDatabase(WTFMove(queue), makeUniqueRefFromNonNullUniquePtr(WTFMove(database)))));
+ });
+ });
+}
+
+PushDatabase::PushDatabase(Ref<WorkQueue>&& queue, UniqueRef<SQLiteDatabase>&& db)
+ : m_queue(WTFMove(queue))
+ , m_db(WTFMove(db))
+{
+}
+
+PushDatabase::~PushDatabase()
+{
+ // In practice we aren't actually expecting this to run, since a NeverDestroyed<WebPushDaemon> instance
+ // holds on to this object.
+ //
+ // If we intend to delete this object for real, we should probably make this object refcounted and make
+ // the blocks on the queue protect the database object rather than using dispatchSync.
+ ASSERT(RunLoop::isMain());
+
+ // Flush any outstanding requests.
+ m_queue->dispatchSync([]() { });
+
+ // Finalize member variables on the queue, since they were are only meant to be used on the queue.
+ m_queue->dispatchSync([db = WTFMove(m_db), statements = WTFMove(m_statements)]() mutable {
+ statements.clear();
+ db->close();
+ });
+}
+
+void PushDatabase::dispatchOnWorkQueue(Function<void()>&& function)
+{
+ RELEASE_ASSERT(RunLoop::isMain());
+ m_queue->dispatch(WTFMove(function));
+}
+
+SQLiteStatementAutoResetScope PushDatabase::cachedStatementOnQueue(ASCIILiteral query)
+{
+ ASSERT(!RunLoop::isMain());
+
+ auto it = m_statements.find(query);
+ if (it != m_statements.end())
+ return SQLiteStatementAutoResetScope(it->value.ptr());
+
+ auto result = m_db->prepareHeapStatement(query);
+ if (!result) {
+ PUSHDB_RELEASE_LOG_ERROR("Failed with %d preparing statement: %" PUBLIC_LOG_STRING, result.error(), query.characters());
+ return SQLiteStatementAutoResetScope(nullptr);
+ }
+
+ auto ref = WTFMove(*result);
+ auto statement = ref.ptr();
+ m_statements.add(query, WTFMove(ref));
+ return SQLiteStatementAutoResetScope(statement);
+}
+
+static int bindExpirationTime(SQLiteStatement* sql, int index, std::optional<EpochTimeStamp> timestamp)
+{
+ return timestamp ? sql->bindInt64(index, convertEpochTimeStampToSeconds(*timestamp)) : sql->bindNull(index);
+}
+
+static std::optional<EpochTimeStamp> expirationTimeFromValue(SQLValue value)
+{
+ if (std::holds_alternative<double>(value))
+ return convertSecondsToEpochTimeStamp(std::get<double>(value));
+ return std::nullopt;
+}
+
+template <class T, class U>
+static void completeOnMainQueue(CompletionHandler<void(T)>&& completionHandler, U&& result)
+{
+ ASSERT(!RunLoop::isMain());
+ WorkQueue::main().dispatch([completionHandler = WTFMove(completionHandler), result = crossThreadCopy(WTFMove(result))]() mutable {
+ completionHandler(WTFMove(result));
+ });
+}
+
+void PushDatabase::insertRecord(const PushRecord& record, CompletionHandler<void(std::optional<PushRecord>&&)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, record = crossThreadCopy(record), completionHandler = WTFMove(completionHandler)]() mutable {
+ SQLiteTransaction transaction(m_db);
+ transaction.begin();
+
+ int64_t subscriptionSetID = 0;
+
+ {
+ auto sql = cachedStatementOnQueue("SELECT rowid, wakeState FROM SubscriptionSets WHERE bundleID = ? AND securityOrigin = ?"_s);
+ if (!sql
+ || sql->bindText(1, record.bundleID) != SQLITE_OK
+ || sql->bindText(2, record.securityOrigin) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ if (sql->step() == SQLITE_ROW) {
+ subscriptionSetID = sql->columnInt64(0);
+ record.wakeState = static_cast<PushWakeState>(sql->columnInt(1));
+ }
+ }
+
+ if (!subscriptionSetID) {
+ auto sql = cachedStatementOnQueue("INSERT INTO SubscriptionSets VALUES(?, ?, ?, ?)"_s);
+ if (!sql
+ || sql->bindInt64(1, time(nullptr)) != SQLITE_OK
+ || sql->bindText(2, record.bundleID) != SQLITE_OK
+ || sql->bindText(3, record.securityOrigin) != SQLITE_OK
+ || sql->bindInt(4, static_cast<int>(record.wakeState)) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ if (sql->step() != SQLITE_DONE) {
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ subscriptionSetID = m_db->lastInsertRowID();
+ }
+
+ {
+ auto sql = cachedStatementOnQueue("INSERT INTO Subscriptions VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"_s);
+ if (!sql
+ || sql->bindInt64(1, time(nullptr)) != SQLITE_OK
+ || sql->bindInt64(2, subscriptionSetID) != SQLITE_OK
+ || sql->bindText(3, record.scope) != SQLITE_OK
+ || sql->bindText(4, record.endpoint) != SQLITE_OK
+ || sql->bindText(5, record.topic) != SQLITE_OK
+ || sql->bindBlob(6, record.serverVAPIDPublicKey) != SQLITE_OK
+ || sql->bindBlob(7, record.clientPublicKey) != SQLITE_OK
+ || sql->bindBlob(8, record.clientPrivateKey) != SQLITE_OK
+ || sql->bindBlob(9, record.sharedAuthSecret) != SQLITE_OK
+ || bindExpirationTime(sql.get(), 10, record.expirationTime) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ if (sql->step() != SQLITE_DONE) {
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ record.identifier = makeObjectIdentifier<PushSubscriptionIdentifierType>(m_db->lastInsertRowID());
+ }
+
+ transaction.commit();
+
+ completeOnMainQueue(WTFMove(completionHandler), WTFMove(record));
+ });
+}
+
+void PushDatabase::removeRecordByIdentifier(PushSubscriptionIdentifier identifier, CompletionHandler<void(bool)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, rowIdentifier = identifier.toUInt64(), completionHandler = WTFMove(completionHandler)]() mutable {
+ SQLiteTransaction transaction(m_db);
+ transaction.begin();
+
+ bool isLastSubscriptionInSet = false;
+ int64_t subscriptionSetID = 0;
+
+ {
+ auto sql = cachedStatementOnQueue("SELECT subscriptionSetID FROM Subscriptions WHERE rowid = ?"_s);
+
+ if (!sql || sql->bindInt64(1, rowIdentifier) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+
+ if (sql->step() != SQLITE_ROW) {
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+
+ subscriptionSetID = sql->columnInt64(0);
+ }
+
+ {
+ // TODO: on SQLite >3.35.0, we could use RETURNING to avoid the SELECT above.
+ auto sql = cachedStatementOnQueue("DELETE FROM Subscriptions WHERE rowid = ?"_s);
+
+ if (!sql || sql->bindInt64(1, rowIdentifier) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+
+ if (sql->step() != SQLITE_DONE) {
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+ }
+
+ {
+ // Check if this was the last subscription in the subscription set.
+ auto sql = cachedStatementOnQueue("SELECT rowid FROM Subscriptions WHERE subscriptionSetID = ?"_s);
+
+ if (!sql || sql->bindInt64(1, subscriptionSetID) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+
+ isLastSubscriptionInSet = (sql->step() == SQLITE_DONE);
+ }
+
+ if (isLastSubscriptionInSet) {
+ // Delete the entire subscription set if it is no longer associated with any subscriptions.
+ auto sql = cachedStatementOnQueue("DELETE FROM SubscriptionSets WHERE rowid = ?"_s);
+ if (!sql || sql->bindInt64(1, subscriptionSetID) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+
+ if (sql->step() != SQLITE_DONE) {
+ completeOnMainQueue(WTFMove(completionHandler), false);
+ return;
+ }
+ }
+
+ transaction.commit();
+
+ completeOnMainQueue(WTFMove(completionHandler), true);
+ });
+}
+
+static PushRecord makePushRecordFromRow(SQLiteStatementAutoResetScope& sql)
+{
+ PushRecord record;
+ record.identifier = makeObjectIdentifier<PushSubscriptionIdentifierType>(sql->columnInt64(0));
+ record.bundleID = sql->columnText(1);
+ record.securityOrigin = sql->columnText(2);
+ record.scope = sql->columnText(3);
+ record.endpoint = sql->columnText(4);
+ record.topic = sql->columnText(5);
+ record.serverVAPIDPublicKey = sql->columnBlob(6);
+ record.clientPublicKey = sql->columnBlob(7);
+ record.clientPrivateKey = sql->columnBlob(8);
+ record.sharedAuthSecret = sql->columnBlob(9);
+ record.expirationTime = expirationTimeFromValue(sql->columnValue(10));
+ record.wakeState = static_cast<PushWakeState>(sql->columnInt(11));
+
+ return record;
+}
+
+void PushDatabase::getRecordByTopic(const String& topic, CompletionHandler<void(std::optional<PushRecord>&&)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, topic = crossThreadCopy(topic), completionHandler = WTFMove(completionHandler)]() mutable {
+ // Force SQLite to consult the Subscriptions(scope) index first via CROSS JOIN.
+ auto sql = cachedStatementOnQueue(
+ "SELECT "
+ " sub.rowID, ss.bundleID, ss.securityOrigin, sub.scope, sub.endpoint, sub.topic, "
+ " sub.serverVAPIDPublicKey, sub.clientPublicKey, sub.clientPrivateKey, "
+ " sub.sharedAuthSecret, sub.expirationTime, ss.wakeState "
+ "FROM Subscriptions sub "
+ "CROSS JOIN SubscriptionSets ss "
+ "ON sub.subscriptionSetID = ss.rowid "
+ "WHERE sub.topic = ?"_s);
+
+ if (!sql || sql->bindText(1, topic) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ if (sql->step() != SQLITE_ROW) {
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ completeOnMainQueue(WTFMove(completionHandler), makePushRecordFromRow(sql));
+ });
+}
+
+void PushDatabase::getRecordByBundleIdentifierAndScope(const String& bundleID, const String& scope, CompletionHandler<void(std::optional<PushRecord>&&)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, bundleID = crossThreadCopy(bundleID), scope = crossThreadCopy(scope), completionHandler = WTFMove(completionHandler)]() mutable {
+ // Force SQLite to consult the Subscriptions(scope) index first via CROSS JOIN.
+ auto sql = cachedStatementOnQueue(
+ "SELECT "
+ " sub.rowID, ss.bundleID, ss.securityOrigin, sub.scope, sub.endpoint, sub.topic, "
+ " sub.serverVAPIDPublicKey, sub.clientPublicKey, sub.clientPrivateKey, "
+ " sub.sharedAuthSecret, sub.expirationTime, ss.wakeState "
+ "FROM Subscriptions sub "
+ "CROSS JOIN SubscriptionSets ss "
+ "ON sub.subscriptionSetID = ss.rowid "
+ "WHERE sub.scope = ? AND ss.bundleID = ?"_s);
+
+ if (!sql || sql->bindText(1, scope) != SQLITE_OK || sql->bindText(2, bundleID) != SQLITE_OK) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ if (sql->step() != SQLITE_ROW) {
+ completeOnMainQueue(WTFMove(completionHandler), std::optional<PushRecord> { });
+ return;
+ }
+
+ completeOnMainQueue(WTFMove(completionHandler), makePushRecordFromRow(sql));
+ });
+}
+
+void PushDatabase::getIdentifiers(CompletionHandler<void(HashSet<PushSubscriptionIdentifier>&&)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, completionHandler = WTFMove(completionHandler)]() mutable {
+ HashSet<PushSubscriptionIdentifier> result;
+ auto sql = cachedStatementOnQueue("SELECT rowid FROM Subscriptions"_s);
+ while (sql && sql->step() == SQLITE_ROW)
+ result.add(makeObjectIdentifier<PushSubscriptionIdentifierType>(sql->columnInt64(0)));
+
+ completeOnMainQueue(WTFMove(completionHandler), WTFMove(result));
+ });
+}
+
+void PushDatabase::getTopicsByWakeState(CompletionHandler<void(PushWakeStateToTopicMap&&)>&& completionHandler)
+{
+ dispatchOnWorkQueue([this, completionHandler = WTFMove(completionHandler)]() mutable {
+ constexpr int numberOfWakeStates = static_cast<int>(PushWakeState::NumberOfStates);
+ Vector<Vector<String>, numberOfWakeStates> topicsByWakeState(numberOfWakeStates); // used because HashMap::isolatedCopy doesn't exist
+
+ auto sql = cachedStatementOnQueue(
+ "SELECT ss.wakeState, sub.topic "
+ "FROM Subscriptions sub "
+ "JOIN SubscriptionSets ss "
+ "ON sub.subscriptionSetID = ss.rowid"_s);
+ if (!sql) {
+ PUSHDB_RELEASE_LOG_BIND_ERROR();
+ WorkQueue::main().dispatch([completionHandler = WTFMove(completionHandler)]() mutable {
+ completionHandler({ });
+ });
+ return;
+ }
+
+ while (sql->step() == SQLITE_ROW) {
+ auto pushWakeState = sql->columnInt(0);
+ auto topic = sql->columnText(1);
+ if (pushWakeState >= 0 && pushWakeState < numberOfWakeStates)
+ topicsByWakeState[pushWakeState].append(WTFMove(topic));
+ }
+
+ WorkQueue::main().dispatch([completionHandler = WTFMove(completionHandler), topicsByWakeState = crossThreadCopy(WTFMove(topicsByWakeState))]() mutable {
+ PushWakeStateToTopicMap result;
+ for (int i = 0; i < static_cast<int>(PushWakeState::NumberOfStates); ++i)
+ result.add(static_cast<PushWakeState>(i), WTFMove(topicsByWakeState[i]));
+ completionHandler(WTFMove(result));
+ });
+ });
+}
+
+} // namespace WebCore
+
+#endif // ENABLE(SERVICE_WORKER)
Added: trunk/Source/WebCore/Modules/push-api/PushDatabase.h (0 => 289139)
--- trunk/Source/WebCore/Modules/push-api/PushDatabase.h (rev 0)
+++ trunk/Source/WebCore/Modules/push-api/PushDatabase.h 2022-02-04 23:21:32 UTC (rev 289139)
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2022 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if ENABLE(SERVICE_WORKER)
+
+#include "EpochTimeStamp.h"
+#include "PushSubscriptionIdentifier.h"
+#include "SQLiteDatabase.h"
+#include "SQLiteStatement.h"
+#include "SQLiteStatementAutoResetScope.h"
+#include <wtf/CompletionHandler.h>
+#include <wtf/FastMalloc.h>
+#include <wtf/HashMap.h>
+#include <wtf/HashSet.h>
+#include <wtf/UniqueRef.h>
+#include <wtf/Vector.h>
+#include <wtf/WorkQueue.h>
+
+namespace WebCore {
+
+// Wake state that applies for devices that race-to-sleep.
+enum class PushWakeState : uint8_t {
+ Waking, // All pushes will wake device.
+ Opportunistic, // Low priority pushes may not wake device.
+ NonWaking, // No pushes will wake device.
+ NumberOfStates
+};
+
+struct PushRecord {
+ PushSubscriptionIdentifier identifier;
+ String bundleID;
+ String securityOrigin;
+ String scope;
+ String endpoint;
+ String topic;
+ Vector<uint8_t> serverVAPIDPublicKey;
+ Vector<uint8_t> clientPublicKey;
+ Vector<uint8_t> clientPrivateKey;
+ Vector<uint8_t> sharedAuthSecret;
+ std::optional<EpochTimeStamp> expirationTime { };
+ PushWakeState wakeState { PushWakeState::Waking };
+
+ WEBCORE_EXPORT PushRecord isolatedCopy() const &;
+ WEBCORE_EXPORT PushRecord isolatedCopy() &&;
+};
+
+class PushDatabase {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ using CreationHandler = CompletionHandler<void(std::unique_ptr<PushDatabase>&&)>;
+
+ WEBCORE_EXPORT static void create(const String& path, CreationHandler&&);
+ WEBCORE_EXPORT ~PushDatabase();
+
+ WEBCORE_EXPORT void insertRecord(const PushRecord&, CompletionHandler<void(std::optional<PushRecord>&&)>&&);
+ WEBCORE_EXPORT void removeRecordByIdentifier(PushSubscriptionIdentifier, CompletionHandler<void(bool)>&&);
+ WEBCORE_EXPORT void getRecordByTopic(const String& topic, CompletionHandler<void(std::optional<PushRecord>&&)>&&);
+ WEBCORE_EXPORT void getRecordByBundleIdentifierAndScope(const String& bundleID, const String& scope, CompletionHandler<void(std::optional<PushRecord>&&)>&&);
+ WEBCORE_EXPORT void getIdentifiers(CompletionHandler<void(HashSet<PushSubscriptionIdentifier>&&)>&&);
+
+ using PushWakeStateToTopicMap = HashMap<PushWakeState, Vector<String>, WTF::IntHash<PushWakeState>, WTF::StrongEnumHashTraits<PushWakeState>>;
+ WEBCORE_EXPORT void getTopicsByWakeState(CompletionHandler<void(PushWakeStateToTopicMap&&)>&&);
+
+private:
+ PushDatabase(Ref<WorkQueue>&&, UniqueRef<WebCore::SQLiteDatabase>&&);
+ WebCore::SQLiteStatementAutoResetScope cachedStatementOnQueue(ASCIILiteral query);
+ void dispatchOnWorkQueue(Function<void()>&&);
+
+ Ref<WorkQueue> m_queue;
+ UniqueRef<WebCore::SQLiteDatabase> m_db;
+ HashMap<const char*, UniqueRef<WebCore::SQLiteStatement>> m_statements;
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(SERVICE_WORKER)
Modified: trunk/Source/WebCore/Sources.txt (289138 => 289139)
--- trunk/Source/WebCore/Sources.txt 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/Sources.txt 2022-02-04 23:21:32 UTC (rev 289139)
@@ -261,6 +261,7 @@
Modules/pictureinpicture/HTMLVideoElementPictureInPicture.cpp
Modules/pictureinpicture/PictureInPictureWindow.cpp
Modules/push-api/PushCrypto.cpp
+Modules/push-api/PushDatabase.cpp
Modules/push-api/PushEvent.cpp
Modules/push-api/PushMessageCrypto.cpp
Modules/push-api/PushMessageData.cpp
Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (289138 => 289139)
--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj 2022-02-04 23:21:32 UTC (rev 289139)
@@ -5471,6 +5471,7 @@
EB28ED442717AC11005F0393 /* PushSubscriptionData.h in Headers */ = {isa = PBXBuildFile; fileRef = EB28ED412717ABA9005F0393 /* PushSubscriptionData.h */; settings = {ATTRIBUTES = (Private, ); }; };
EB3C29B62729C38800FB65B4 /* PushSubscriptionChangeEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3C29B42729C36E00FB65B4 /* PushSubscriptionChangeEvent.h */; };
EB3C29B72729C38C00FB65B4 /* PushSubscriptionChangeEventInit.h in Headers */ = {isa = PBXBuildFile; fileRef = EB3C29B12729C36D00FB65B4 /* PushSubscriptionChangeEventInit.h */; };
+ EB9AD8CB27646E9400D893A4 /* PushDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = EB9AD8C827646E9000D893A4 /* PushDatabase.h */; settings = {ATTRIBUTES = (Private, ); }; };
EBA75C46275EC61A00D6D31C /* PushCrypto.h in Headers */ = {isa = PBXBuildFile; fileRef = EBA75C42275EBDAB00D6D31C /* PushCrypto.h */; settings = {ATTRIBUTES = (Private, ); }; };
EBA75C47275EC62100D6D31C /* PushMessageCrypto.h in Headers */ = {isa = PBXBuildFile; fileRef = EBA75C40275EBDAA00D6D31C /* PushMessageCrypto.h */; settings = {ATTRIBUTES = (Private, ); }; };
EBB9738127100671007732EF /* PushManager.h in Headers */ = {isa = PBXBuildFile; fileRef = EBB9738027100654007732EF /* PushManager.h */; };
@@ -17705,6 +17706,8 @@
EB3C29B22729C36E00FB65B4 /* PushSubscriptionChangeEventInit.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PushSubscriptionChangeEventInit.idl; sourceTree = "<group>"; };
EB3C29B32729C36E00FB65B4 /* PushSubscriptionChangeEvent.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PushSubscriptionChangeEvent.idl; sourceTree = "<group>"; };
EB3C29B42729C36E00FB65B4 /* PushSubscriptionChangeEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PushSubscriptionChangeEvent.h; sourceTree = "<group>"; };
+ EB9AD8C827646E9000D893A4 /* PushDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PushDatabase.h; sourceTree = "<group>"; };
+ EB9AD8CA27646E9100D893A4 /* PushDatabase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PushDatabase.cpp; sourceTree = "<group>"; };
EBA75C3E275EBDAA00D6D31C /* PushMessageCrypto.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = PushMessageCrypto.cpp; sourceTree = "<group>"; };
EBA75C40275EBDAA00D6D31C /* PushMessageCrypto.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PushMessageCrypto.h; sourceTree = "<group>"; };
EBA75C41275EBDAB00D6D31C /* PushCrypto.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = PushCrypto.cpp; sourceTree = "<group>"; };
@@ -21211,6 +21214,8 @@
EBA75C44275EC56000D6D31C /* cocoa */,
EBA75C41275EBDAB00D6D31C /* PushCrypto.cpp */,
EBA75C42275EBDAB00D6D31C /* PushCrypto.h */,
+ EB9AD8CA27646E9100D893A4 /* PushDatabase.cpp */,
+ EB9AD8C827646E9000D893A4 /* PushDatabase.h */,
EB0FB6FD270D0AE800F7810D /* PushEncryptionKeyName.h */,
EB0FB700270D0AEA00F7810D /* PushEncryptionKeyName.idl */,
418FCBBB2706E4F600F96ECA /* PushEvent.cpp */,
@@ -36665,6 +36670,7 @@
0081FF0016B0A2D3008AAA7A /* PublicSuffix.h in Headers */,
10FB084B14E15C7E00A3DB98 /* PublicURLManager.h in Headers */,
EBA75C46275EC61A00D6D31C /* PushCrypto.h in Headers */,
+ EB9AD8CB27646E9400D893A4 /* PushDatabase.h in Headers */,
EB0FB708270D0B1000F7810D /* PushEncryptionKeyName.h in Headers */,
418FCBC12706E4FB00F96ECA /* PushEvent.h in Headers */,
418FCBC22706E50100F96ECA /* PushEventInit.h in Headers */,
@@ -36677,6 +36683,7 @@
EB3C29B72729C38C00FB65B4 /* PushSubscriptionChangeEventInit.h in Headers */,
EB28ED442717AC11005F0393 /* PushSubscriptionData.h in Headers */,
EBE095E5277D14DA00804D61 /* PushSubscriptionIdentifier.h in Headers */,
+ EBE095E5277D14DA00804D61 /* PushSubscriptionIdentifier.h in Headers */,
EB0FB70A270D0B1B00F7810D /* PushSubscriptionJSON.h in Headers */,
EB0FB70C270D0B2900F7810D /* PushSubscriptionOptions.h in Headers */,
EB0FB70D270D0B2E00F7810D /* PushSubscriptionOptionsInit.h in Headers */,
Modified: trunk/Source/WebCore/platform/Logging.h (289138 => 289139)
--- trunk/Source/WebCore/platform/Logging.h 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/platform/Logging.h 2022-02-04 23:21:32 UTC (rev 289139)
@@ -96,6 +96,7 @@
M(PrivateClickMeasurement) \
M(Process) \
M(Progress) \
+ M(Push) \
M(RemoteInspector) \
M(RequestAnimationFrame) \
M(ResourceLoading) \
Modified: trunk/Source/WebCore/platform/sql/SQLiteDatabase.cpp (289138 => 289139)
--- trunk/Source/WebCore/platform/sql/SQLiteDatabase.cpp 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/platform/sql/SQLiteDatabase.cpp 2022-02-04 23:21:32 UTC (rev 289139)
@@ -88,6 +88,11 @@
close();
}
+const char* SQLiteDatabase::inMemoryPath()
+{
+ return ":memory:";
+}
+
bool SQLiteDatabase::open(const String& filename, OpenMode openMode)
{
initializeSQLiteIfNecessary();
@@ -148,14 +153,16 @@
LOG_ERROR("SQLite database could not set temp_store to memory");
}
- if (openMode != OpenMode::ReadOnly)
- useWALJournalMode();
+ if (filename != inMemoryPath()) {
+ if (openMode != OpenMode::ReadOnly)
+ useWALJournalMode();
- auto shmFileName = makeString(filename, "-shm"_s);
- if (FileSystem::fileExists(shmFileName)) {
- if (!FileSystem::isSafeToUseMemoryMapForPath(shmFileName)) {
- RELEASE_LOG_FAULT(SQLDatabase, "Opened an SQLite database with a Class A -shm file. This may trigger a crash when the user locks the device. (%s)", shmFileName.latin1().data());
- FileSystem::makeSafeToUseMemoryMapForPath(shmFileName);
+ auto shmFileName = makeString(filename, "-shm"_s);
+ if (FileSystem::fileExists(shmFileName)) {
+ if (!FileSystem::isSafeToUseMemoryMapForPath(shmFileName)) {
+ RELEASE_LOG_FAULT(SQLDatabase, "Opened an SQLite database with a Class A -shm file. This may trigger a crash when the user locks the device. (%s)", shmFileName.latin1().data());
+ FileSystem::makeSafeToUseMemoryMapForPath(shmFileName);
+ }
}
}
Modified: trunk/Source/WebCore/platform/sql/SQLiteDatabase.h (289138 => 289139)
--- trunk/Source/WebCore/platform/sql/SQLiteDatabase.h 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Source/WebCore/platform/sql/SQLiteDatabase.h 2022-02-04 23:21:32 UTC (rev 289139)
@@ -56,6 +56,8 @@
WEBCORE_EXPORT SQLiteDatabase();
WEBCORE_EXPORT ~SQLiteDatabase();
+ WEBCORE_EXPORT static const char* inMemoryPath();
+
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate };
WEBCORE_EXPORT bool open(const String& filename, OpenMode = OpenMode::ReadWriteCreate);
bool isOpen() const { return m_db; }
Modified: trunk/Tools/ChangeLog (289138 => 289139)
--- trunk/Tools/ChangeLog 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Tools/ChangeLog 2022-02-04 23:21:32 UTC (rev 289139)
@@ -1,3 +1,24 @@
+2022-02-04 Ben Nham <[email protected]>
+
+ Add PushDatabase
+ https://bugs.webkit.org/show_bug.cgi?id=234194
+
+ Reviewed by Brady Eidson.
+
+ * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+ * TestWebKitAPI/Tests/WebCore/PushDatabase.cpp: Added.
+ (TestWebKitAPI::getTopicsByWakeStateSync):
+ (TestWebKitAPI::PushDatabaseTest::insertRecord):
+ (TestWebKitAPI::PushDatabaseTest::removeRecordByRowIdentifier):
+ (TestWebKitAPI::PushDatabaseTest::getRecordByTopic):
+ (TestWebKitAPI::PushDatabaseTest::getRecordByBundleIdentifierAndScope):
+ (TestWebKitAPI::PushDatabaseTest::getRowIdentifiers):
+ (TestWebKitAPI::PushDatabaseTest::getTopicsByWakeState):
+ (TestWebKitAPI::operator==):
+ (TestWebKitAPI::TEST_F):
+ (TestWebKitAPI::makeTemporaryDatabasePath):
+ (TestWebKitAPI::TEST):
+
2022-02-04 Commit Queue <[email protected]>
Unreviewed, reverting r289067.
Modified: trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj (289138 => 289139)
--- trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj 2022-02-04 22:49:24 UTC (rev 289138)
+++ trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj 2022-02-04 23:21:32 UTC (rev 289139)
@@ -1004,6 +1004,7 @@
E5AA42F2259128AE00410A3D /* UserInterfaceIdiomUpdate.mm in Sources */ = {isa = PBXBuildFile; fileRef = E5AA42F1259128AE00410A3D /* UserInterfaceIdiomUpdate.mm */; };
E5AA8D1D25151CC60051CC45 /* DateInputTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = E5AA8D1C25151CC60051CC45 /* DateInputTests.mm */; };
EB230D41245E813F00C66AD1 /* IDBCheckpointWAL.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = EB230D3D245E722E00C66AD1 /* IDBCheckpointWAL.html */; };
+ EB9AD8C727646E7400D893A4 /* PushDatabase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = EB9AD8C627646E7300D893A4 /* PushDatabase.cpp */; };
EBA75C49275ED7C700D6D31C /* PushMessageCrypto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = EBA75C48275ED7BE00D6D31C /* PushMessageCrypto.cpp */; };
ECA680CE1E68CC0900731D20 /* StringUtilities.mm in Sources */ = {isa = PBXBuildFile; fileRef = ECA680CD1E68CC0900731D20 /* StringUtilities.mm */; };
F4010B8024DA24AC00A876E2 /* NavigationSwipeTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F4010B7F24DA24AC00A876E2 /* NavigationSwipeTests.mm */; };
@@ -2973,6 +2974,7 @@
E5AA8D1C25151CC60051CC45 /* DateInputTests.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = DateInputTests.mm; sourceTree = "<group>"; };
EB230D3D245E722E00C66AD1 /* IDBCheckpointWAL.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = IDBCheckpointWAL.html; sourceTree = "<group>"; };
EB230D3E245E726300C66AD1 /* IDBCheckpointWAL.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = IDBCheckpointWAL.mm; sourceTree = "<group>"; };
+ EB9AD8C627646E7300D893A4 /* PushDatabase.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PushDatabase.cpp; sourceTree = "<group>"; };
EBA75C48275ED7BE00D6D31C /* PushMessageCrypto.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = PushMessageCrypto.cpp; sourceTree = "<group>"; };
EC79F168BE454E579E417B05 /* Markable.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Markable.cpp; sourceTree = "<group>"; };
ECA680CD1E68CC0900731D20 /* StringUtilities.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = StringUtilities.mm; sourceTree = "<group>"; };
@@ -3784,6 +3786,7 @@
AA96CAB421C7DB4200FD2F97 /* ParsedContentType.cpp */,
6B0A07F621FA9C2B00D57391 /* PrivateClickMeasurement.cpp */,
041A1E33216FFDBC00789E0A /* PublicSuffix.cpp */,
+ EB9AD8C627646E7300D893A4 /* PushDatabase.cpp */,
EBA75C48275ED7BE00D6D31C /* PushMessageCrypto.cpp */,
6B4E861B2220A5520022F389 /* RegistrableDomain.cpp */,
F418BE141F71B7DC001970E6 /* RoundedRectTests.cpp */,
@@ -5701,6 +5704,7 @@
4647B1261EBA3B850041D7EF /* ProcessDidTerminate.cpp in Sources */,
FEC2A85624CEB65F00ADBC35 /* PropertySlot.cpp in Sources */,
041A1E34216FFDBC00789E0A /* PublicSuffix.cpp in Sources */,
+ EB9AD8C727646E7400D893A4 /* PushDatabase.cpp in Sources */,
EBA75C49275ED7C700D6D31C /* PushMessageCrypto.cpp in Sources */,
6B4E861C2220A5520022F389 /* RegistrableDomain.cpp in Sources */,
7CCE7F0D1A411AE600447C4C /* ReloadPageAfterCrash.cpp in Sources */,
Added: trunk/Tools/TestWebKitAPI/Tests/WebCore/PushDatabase.cpp (0 => 289139)
--- trunk/Tools/TestWebKitAPI/Tests/WebCore/PushDatabase.cpp (rev 0)
+++ trunk/Tools/TestWebKitAPI/Tests/WebCore/PushDatabase.cpp 2022-02-04 23:21:32 UTC (rev 289139)
@@ -0,0 +1,386 @@
+/*
+ * Copyright (C) 2022 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "Utilities.h"
+#include <WebCore/PushDatabase.h>
+#include <WebCore/SQLiteDatabase.h>
+#include <wtf/FileSystem.h>
+
+#if ENABLE(SERVICE_WORKER)
+
+using namespace WebCore;
+
+namespace TestWebKitAPI {
+
+static PushDatabase::PushWakeStateToTopicMap getTopicsByWakeStateSync(PushDatabase& database)
+{
+ bool done = false;
+ PushDatabase::PushWakeStateToTopicMap getResult;
+
+ database.getTopicsByWakeState([&done, &getResult](PushDatabase::PushWakeStateToTopicMap&& result) {
+ getResult = WTFMove(result);
+ done = true;
+ });
+ Util::run(&done);
+
+ return getResult;
+}
+
+class PushDatabaseTest : public testing::Test {
+public:
+ std::unique_ptr<PushDatabase> db;
+
+ PushRecord record1 {
+ PushSubscriptionIdentifier(),
+ "com.apple.Safari"_s,
+ "https://www.apple.com"_s,
+ "https://www.apple.com/mac"_s,
+ "https://pushEndpoint1"_s,
+ "topic1"_s,
+ { 0, 1 },
+ { 1, 2 },
+ { 2, 3 },
+ { 4, 5 },
+ convertSecondsToEpochTimeStamp(1643350000),
+ PushWakeState::Opportunistic
+ };
+ PushRecord record2 {
+ PushSubscriptionIdentifier(),
+ "com.apple.webapp"_s,
+ "https://www.apple.com"_s,
+ "https://www.apple.com/iphone"_s,
+ "https://pushEndpoint2"_s,
+ "topic2"_s,
+ { 5, 6 },
+ { 6, 7 },
+ { 7, 8 },
+ { 8, 9 }
+ };
+ PushRecord record3 {
+ PushSubscriptionIdentifier(),
+ "com.apple.Safari"_s,
+ "https://www.apple.com"_s,
+ "https://www.apple.com/iphone"_s,
+ "https://pushEndpoint3"_s,
+ "topic3"_s,
+ { 9, 10 },
+ { 10, 11 },
+ { 11, 12 },
+ { 12, 13 }
+ };
+
+ std::optional<PushRecord> insertResult1;
+ std::optional<PushRecord> insertResult2;
+ std::optional<PushRecord> insertResult3;
+
+ std::optional<PushRecord> insertRecord(const PushRecord& record)
+ {
+ bool done = false;
+ std::optional<PushRecord> insertResult;
+
+ db->insertRecord(record, [&done, &insertResult](std::optional<PushRecord>&& result) {
+ insertResult = WTFMove(result);
+ done = true;
+ });
+ Util::run(&done);
+
+ return insertResult;
+ }
+
+ bool removeRecordByRowIdentifier(uint64_t rowIdentifier)
+ {
+ bool done = false;
+ bool removeResult = false;
+
+ db->removeRecordByIdentifier(makeObjectIdentifier<PushSubscriptionIdentifierType>(rowIdentifier), [&done, &removeResult](bool result) {
+ removeResult = result;
+ done = true;
+ });
+ Util::run(&done);
+
+ return removeResult;
+ }
+
+ std::optional<PushRecord> getRecordByTopic(const String& topic)
+ {
+ bool done = false;
+ std::optional<PushRecord> getResult;
+
+ db->getRecordByTopic(topic, [&done, &getResult](std::optional<PushRecord>&& result) {
+ getResult = WTFMove(result);
+ done = true;
+ });
+ Util::run(&done);
+
+ return getResult;
+ }
+
+ std::optional<PushRecord> getRecordByBundleIdentifierAndScope(const String& bundleID, const String& scope)
+ {
+ bool done = false;
+ std::optional<PushRecord> getResult;
+
+ db->getRecordByBundleIdentifierAndScope(bundleID, scope, [&done, &getResult](std::optional<PushRecord>&& result) {
+ getResult = WTFMove(result);
+ done = true;
+ });
+ Util::run(&done);
+
+ return getResult;
+ }
+
+ HashSet<uint64_t> getRowIdentifiers()
+ {
+ bool done = false;
+ HashSet<uint64_t> rowIdentifiers;
+
+ db->getIdentifiers([&done, &rowIdentifiers](HashSet<PushSubscriptionIdentifier>&& identifiers) {
+ for (auto identifier : identifiers)
+ rowIdentifiers.add(identifier.toUInt64());
+ done = true;
+ });
+ Util::run(&done);
+
+ return rowIdentifiers;
+ }
+
+ PushDatabase::PushWakeStateToTopicMap getTopicsByWakeState()
+ {
+ return getTopicsByWakeStateSync(*db);
+ }
+
+ void SetUp() final
+ {
+ bool done = false;
+ PushDatabase::create(SQLiteDatabase::inMemoryPath(), [this, &done](std::unique_ptr<PushDatabase>&& database) {
+ db = WTFMove(database);
+ done = true;
+ });
+ Util::run(&done);
+
+ ASSERT_TRUE(db);
+ ASSERT_TRUE(insertResult1 = insertRecord(record1));
+ ASSERT_TRUE(insertResult2 = insertRecord(record2));
+ ASSERT_TRUE(insertResult3 = insertRecord(record3));
+ }
+};
+
+static bool operator==(const PushRecord& a, const PushRecord& b)
+{
+ return a.identifier == b.identifier
+ && a.bundleID == b.bundleID
+ && a.securityOrigin == b.securityOrigin
+ && a.scope == b.scope
+ && a.endpoint == b.endpoint
+ && a.topic == b.topic
+ && a.serverVAPIDPublicKey == b.serverVAPIDPublicKey
+ && a.clientPublicKey == b.clientPublicKey
+ && a.clientPrivateKey == b.clientPrivateKey
+ && a.sharedAuthSecret == b.sharedAuthSecret
+ && a.expirationTime == b.expirationTime
+ && a.wakeState == b.wakeState;
+}
+
+TEST_F(PushDatabaseTest, InsertRecord)
+{
+ auto expectedRecord1 = record1;
+ expectedRecord1.identifier = makeObjectIdentifier<PushSubscriptionIdentifierType>(1);
+ EXPECT_TRUE(expectedRecord1 == *insertResult1);
+
+ auto expectedRecord2 = record2;
+ expectedRecord2.identifier = makeObjectIdentifier<PushSubscriptionIdentifierType>(2);
+ EXPECT_TRUE(expectedRecord2 == *insertResult2);
+
+ // Since record3 is in the same SubscriptionSet as record1, it should
+ // inherit record1's wake state.
+ auto expectedRecord3 = record3;
+ expectedRecord3.identifier = makeObjectIdentifier<PushSubscriptionIdentifierType>(3);
+ expectedRecord3.wakeState = expectedRecord1.wakeState;
+ EXPECT_TRUE(expectedRecord3 == *insertResult3);
+
+ // Inserting a record with the same (bundleID, scope) as record 1 should fail.
+ PushRecord record4 = record1;
+ record4.endpoint = "https://www.webkit.org"_s;
+ EXPECT_FALSE(insertRecord(WTFMove(record4)));
+
+ EXPECT_EQ(getRowIdentifiers(), (HashSet<uint64_t> { 1, 2, 3 }));
+}
+
+TEST_F(PushDatabaseTest, RemoveRecord)
+{
+ EXPECT_TRUE(removeRecordByRowIdentifier(1));
+ EXPECT_FALSE(removeRecordByRowIdentifier(1));
+ EXPECT_EQ(getRowIdentifiers(), (HashSet<uint64_t> { 2, 3 }));
+}
+
+TEST_F(PushDatabaseTest, GetRecordByTopic)
+{
+ auto result1 = getRecordByTopic(record1.topic);
+ ASSERT_TRUE(result1);
+ EXPECT_TRUE(*result1 == *insertResult1);
+
+ auto result2 = getRecordByTopic("foo"_s);
+ EXPECT_FALSE(result2);
+}
+
+TEST_F(PushDatabaseTest, GetRecordByBundleIdentifierAndScope)
+{
+ auto result1 = getRecordByBundleIdentifierAndScope(record1.bundleID, record1.scope);
+ ASSERT_TRUE(result1);
+ EXPECT_TRUE(*result1 == *insertResult1);
+
+ auto result2 = getRecordByBundleIdentifierAndScope(record1.bundleID, "bar"_s);
+ EXPECT_FALSE(result2);
+
+ auto result3 = getRecordByBundleIdentifierAndScope("foo"_s, "bar"_s);
+ EXPECT_FALSE(result3);
+}
+
+TEST_F(PushDatabaseTest, GetTopicsByWakeState)
+{
+ HashMap<String, PushWakeState> expected {
+ { "topic1", PushWakeState::Opportunistic },
+ { "topic2", PushWakeState::Waking },
+ { "topic3", PushWakeState::Opportunistic }
+ };
+ HashMap<String, PushWakeState> actual;
+
+ for (const auto& [wakeState, topics] : getTopicsByWakeState()) {
+ for (const auto& topic : topics)
+ actual.add(topic, wakeState);
+ }
+
+ EXPECT_EQ(expected, actual);
+}
+
+static String makeTemporaryDatabasePath()
+{
+ FileSystem::PlatformFileHandle handle;
+ auto path = FileSystem::openTemporaryFile("PushDatabase", handle, ".db");
+ FileSystem::closeFile(handle);
+ return path;
+}
+
+TEST(PushDatabase, ManyInFlightOps)
+{
+ auto path = makeTemporaryDatabasePath();
+ constexpr unsigned recordCount = 256;
+
+ {
+ std::unique_ptr<PushDatabase> createResult;
+ bool done = false;
+ PushDatabase::create(path, [&createResult, &done](std::unique_ptr<PushDatabase>&& database) {
+ createResult = WTFMove(database);
+ done = true;
+ });
+ Util::run(&done);
+ ASSERT_TRUE(createResult);
+
+ auto& database = *createResult;
+ char scope[64] { };
+ char topic[64] { };
+ PushRecord record {
+ PushSubscriptionIdentifier(),
+ "com.apple.Safari"_s,
+ "https://www.webkit.org"_s,
+ { },
+ "https://pushEndpoint1"_s,
+ { },
+ { 0, 1 },
+ { 1, 2 },
+ { 2, 3 },
+ { 4, 5 },
+ convertSecondsToEpochTimeStamp(1643350000),
+ PushWakeState::Waking
+ };
+
+ for (unsigned i = 0; i < recordCount; i++) {
+ snprintf(scope, sizeof(scope), "http://www.webkit.org/test/%d", i);
+ snprintf(topic, sizeof(topic), "topic_%d", i);
+ record.scope = scope;
+ record.topic = topic;
+
+ database.insertRecord(record, [](auto&& result) {
+ ASSERT_TRUE(result);
+ });
+ }
+ }
+
+ {
+ std::unique_ptr<PushDatabase> createResult;
+ bool done = false;
+ PushDatabase::create(path, [&createResult, &done](std::unique_ptr<PushDatabase>&& database) {
+ createResult = WTFMove(database);
+ done = true;
+ });
+ Util::run(&done);
+ ASSERT_TRUE(createResult);
+
+ auto getResult = getTopicsByWakeStateSync(*createResult);
+ auto topics = getResult.take(PushWakeState::Waking);
+ EXPECT_EQ(topics.size(), recordCount);
+ }
+}
+
+TEST(PushDatabase, StartsFromScratchOnDowngrade)
+{
+ auto path = makeTemporaryDatabasePath();
+
+ {
+ SQLiteDatabase db;
+ db.open(path);
+ ASSERT_TRUE(db.executeCommand("PRAGMA user_version = 100000"_s));
+ }
+
+ {
+ std::unique_ptr<PushDatabase> createResult;
+ bool done = false;
+ PushDatabase::create(path, [&createResult, &done](std::unique_ptr<PushDatabase>&& database) {
+ createResult = WTFMove(database);
+ done = true;
+ });
+ Util::run(&done);
+ ASSERT_TRUE(createResult);
+ }
+
+ {
+ SQLiteDatabase db;
+ db.open(path);
+ {
+ int version = 0;
+ auto sql = db.prepareStatement("PRAGMA user_version"_s);
+ if (sql && sql->step() == SQLITE_ROW)
+ version = sql->columnInt(0);
+ EXPECT_GT(version, 0);
+ EXPECT_LT(version, 100000);
+ }
+ }
+}
+
+} // namespace TestWebKitAPI
+
+#endif // ENABLE(SERVICE_WORKER)
+