Skip to content

Commit

Permalink
[fuchsia] Clean up WebEngineBrowserContext implementation.
Browse files Browse the repository at this point in the history
Add explicit incognito and persistent profile create functions to the
WebEngineBrowserContext class.

Bug: 1163073
Change-Id: Ie30ddce3f8bad934dd530b0dfb79f44b4aaf87a5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2825887
Commit-Queue: Wez <wez@chromium.org>
Reviewed-by: David Dorwin <ddorwin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#873688}
  • Loading branch information
Wez authored and Chromium LUCI CQ committed Apr 19, 2021
1 parent d67966d commit 2f7820b
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 122 deletions.
79 changes: 23 additions & 56 deletions fuchsia/engine/browser/web_engine_browser_context.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
#include "base/files/file_util.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/path_service.h"
#include "base/system/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/keyed_service/core/simple_key_map.h"
Expand All @@ -23,52 +22,13 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "fuchsia/engine/browser/web_engine_net_log_observer.h"
#include "fuchsia/engine/browser/web_engine_permission_delegate.h"
#include "fuchsia/engine/switches.h"
#include "media/capabilities/in_memory_video_decode_stats_db_impl.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "services/network/public/cpp/network_switches.h"

namespace {

// Determines whether a data directory is configured, and returns its path.
// Passes the quota, if specified, for SysInfo to report as total disk space.
// TODO(crbug.com/1010222): Remove this check for the presence of /data, and
// instead rely upon the "incognito" switch.
base::FilePath InitializeDataDirectoryAndQuotaFromCommandLine() {
base::FilePath data_directory_path;
CHECK(base::PathService::Get(base::DIR_APP_DATA, &data_directory_path));

// Enumerating the root namespace for the presence of the /data directory
// avoids the need for scoped blocking, as PathExists would require.
fdio_flat_namespace_t* flat_root_namespace = nullptr;
zx_status_t status = fdio_ns_export_root(&flat_root_namespace);
ZX_CHECK(status == ZX_OK, status);
bool have_data_directory = false;
for (size_t i = 0; i < flat_root_namespace->count; ++i) {
if (data_directory_path.value().data() == flat_root_namespace->path[i]) {
have_data_directory = true;
break;
}
}
fdio_ns_free_flat_ns(flat_root_namespace);
if (!have_data_directory)
return base::FilePath();

const auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kDataQuotaBytes)) {
// Configure SysInfo to use the specified quota as the total-disk-space
// for the |data_dir_path_|.
uint64_t quota_bytes = 0;
CHECK(base::StringToUint64(
command_line->GetSwitchValueASCII(switches::kDataQuotaBytes),
&quota_bytes));
base::SysInfo::SetAmountOfTotalDiskSpace(data_directory_path, quota_bytes);
}

return data_directory_path;
}

std::unique_ptr<WebEngineNetLogObserver> CreateNetLogObserver() {
std::unique_ptr<WebEngineNetLogObserver> result;

Expand All @@ -95,20 +55,17 @@ class WebEngineBrowserContext::ResourceContext
DISALLOW_COPY_AND_ASSIGN(ResourceContext);
};

WebEngineBrowserContext::WebEngineBrowserContext(bool force_incognito)
: net_log_observer_(CreateNetLogObserver()),
resource_context_(new ResourceContext()) {
if (!force_incognito) {
data_dir_path_ = InitializeDataDirectoryAndQuotaFromCommandLine();
}

simple_factory_key_ =
std::make_unique<SimpleFactoryKey>(GetPath(), IsOffTheRecord());
SimpleKeyMap::GetInstance()->Associate(this, simple_factory_key_.get());
// static
std::unique_ptr<WebEngineBrowserContext>
WebEngineBrowserContext::CreatePersistent(base::FilePath data_directory) {
return base::WrapUnique(
new WebEngineBrowserContext(std::move(data_directory)));
}

// TODO(crbug.com/1181156): Should apply any persisted isolated origins here.
// However, since WebEngine does not persist any, that would currently be a
// no-op.
// static
std::unique_ptr<WebEngineBrowserContext>
WebEngineBrowserContext::CreateIncognito() {
return base::WrapUnique(new WebEngineBrowserContext({}));
}

WebEngineBrowserContext::~WebEngineBrowserContext() {
Expand Down Expand Up @@ -176,9 +133,7 @@ WebEngineBrowserContext::GetSSLHostStateDelegate() {

content::PermissionControllerDelegate*
WebEngineBrowserContext::GetPermissionControllerDelegate() {
if (!permission_delegate_)
permission_delegate_ = std::make_unique<WebEnginePermissionDelegate>();
return permission_delegate_.get();
return &permission_delegate_;
}

content::ClientHintsControllerDelegate*
Expand Down Expand Up @@ -215,3 +170,15 @@ WebEngineBrowserContext::CreateVideoDecodePerfHistory() {
nullptr /* seed_db_provider */),
media::learning::FeatureProviderFactoryCB());
}

WebEngineBrowserContext::WebEngineBrowserContext(base::FilePath data_directory)
: data_dir_path_(std::move(data_directory)),
net_log_observer_(CreateNetLogObserver()),
simple_factory_key_(GetPath(), IsOffTheRecord()),
resource_context_(std::make_unique<ResourceContext>()) {
SimpleKeyMap::GetInstance()->Associate(this, &simple_factory_key_);

// TODO(crbug.com/1181156): Should apply any persisted isolated origins here.
// However, since WebEngine does not persist any, that would currently be a
// no-op.
}
64 changes: 35 additions & 29 deletions fuchsia/engine/browser/web_engine_browser_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,55 +8,61 @@
#include <memory>

#include "base/files/file_path.h"
#include "base/macros.h"
#include "components/keyed_service/core/simple_factory_key.h"
#include "content/public/browser/browser_context.h"
#include "fuchsia/engine/browser/web_engine_permission_delegate.h"

class WebEngineNetLogObserver;
class WebEnginePermissionDelegate;

class WebEngineBrowserContext : public content::BrowserContext {
public:
// |force_incognito|: If set, then this BrowserContext will run in incognito
// mode even if /data is available.
explicit WebEngineBrowserContext(bool force_incognito);
~WebEngineBrowserContext() override;
// Creates a browser context that persists cookies, LocalStorage, etc, in
// the specified |data_directory|.
static std::unique_ptr<WebEngineBrowserContext> CreatePersistent(
base::FilePath data_directory);

// Creates a browser context with no support for persistent data.
static std::unique_ptr<WebEngineBrowserContext> CreateIncognito();

~WebEngineBrowserContext() final;

WebEngineBrowserContext(const WebEngineBrowserContext&) = delete;
WebEngineBrowserContext& operator=(const WebEngineBrowserContext&) = delete;

// BrowserContext implementation.
std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
const base::FilePath& partition_path) override;
base::FilePath GetPath() override;
bool IsOffTheRecord() override;
content::ResourceContext* GetResourceContext() override;
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
content::BrowserPluginGuestManager* GetGuestManager() override;
storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override;
content::PushMessagingService* GetPushMessagingService() override;
content::StorageNotificationService* GetStorageNotificationService() override;
content::SSLHostStateDelegate* GetSSLHostStateDelegate() override;
const base::FilePath& partition_path) final;
base::FilePath GetPath() final;
bool IsOffTheRecord() final;
content::ResourceContext* GetResourceContext() final;
content::DownloadManagerDelegate* GetDownloadManagerDelegate() final;
content::BrowserPluginGuestManager* GetGuestManager() final;
storage::SpecialStoragePolicy* GetSpecialStoragePolicy() final;
content::PushMessagingService* GetPushMessagingService() final;
content::StorageNotificationService* GetStorageNotificationService() final;
content::SSLHostStateDelegate* GetSSLHostStateDelegate() final;
content::PermissionControllerDelegate* GetPermissionControllerDelegate()
override;
final;
content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate()
override;
content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override;
content::BackgroundSyncController* GetBackgroundSyncController() override;
content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate()
override;
final;
content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() final;
content::BackgroundSyncController* GetBackgroundSyncController() final;
content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate() final;
std::unique_ptr<media::VideoDecodePerfHistory> CreateVideoDecodePerfHistory()
override;
final;

private:
// Contains URLRequestContextGetter required for resource loading.
class ResourceContext;

base::FilePath data_dir_path_;
explicit WebEngineBrowserContext(base::FilePath data_dir_path);

std::unique_ptr<WebEngineNetLogObserver> net_log_observer_;
std::unique_ptr<SimpleFactoryKey> simple_factory_key_;
std::unique_ptr<ResourceContext> resource_context_;
std::unique_ptr<WebEnginePermissionDelegate> permission_delegate_;
const base::FilePath data_dir_path_;

DISALLOW_COPY_AND_ASSIGN(WebEngineBrowserContext);
const std::unique_ptr<WebEngineNetLogObserver> net_log_observer_;
SimpleFactoryKey simple_factory_key_;
WebEnginePermissionDelegate permission_delegate_;
std::unique_ptr<ResourceContext> resource_context_;
};

#endif // FUCHSIA_ENGINE_BROWSER_WEB_ENGINE_BROWSER_CONTEXT_H_
100 changes: 63 additions & 37 deletions fuchsia/engine/browser/web_engine_browser_main_parts.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/important_file_writer_cleaner.h"
#include "base/fuchsia/file_utils.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/fuchsia/intl_profile_watcher.h"
#include "base/fuchsia/process_context.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/system/sys_info.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/gpu_data_manager.h"
Expand Down Expand Up @@ -88,44 +90,24 @@ void WebEngineBrowserMainParts::PostEarlyInitialization() {

int WebEngineBrowserMainParts::PreMainMessageLoopRun() {
DCHECK(!screen_);
DCHECK_EQ(context_bindings_.size(), 0u);

// Watch for changes to the user's locale setting.
intl_profile_watcher_ = std::make_unique<base::FuchsiaIntlProfileWatcher>(
base::BindRepeating(&WebEngineBrowserMainParts::OnIntlProfileChanged,
base::Unretained(this)));

screen_ = std::make_unique<aura::ScreenOzone>();
display::Screen::SetScreenInstance(screen_.get());
const auto* command_line = base::CommandLine::ForCurrentProcess();

// If Vulkan is not enabled then disable hardware acceleration. Otherwise gpu
// process will be restarted several times trying to initialize GL before
// falling back to software compositing.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseVulkan)) {
if (!command_line->HasSwitch(switches::kUseVulkan)) {
content::GpuDataManager* gpu_data_manager =
content::GpuDataManager::GetInstance();
DCHECK(gpu_data_manager);
gpu_data_manager->DisableHardwareAcceleration();
}

DCHECK_EQ(context_bindings_.size(), 0u);

devtools_controller_ = WebEngineDevToolsController::CreateFromCommandLine(
*base::CommandLine::ForCurrentProcess());
devtools_controller_ =
WebEngineDevToolsController::CreateFromCommandLine(*command_line);

// TODO(crbug.com/1163073): Update tests to make a service connection to the
// Context and remove this workaround.
if (*g_test_request)
HandleContextRequest(std::move(*g_test_request));

// Publish the fuchsia.web.Context service, and allow exactly one connection.
base::ComponentContextForProcess()->outgoing()->AddPublicService(
fidl::InterfaceRequestHandler<fuchsia::web::Context>(fit::bind_member(
this, &WebEngineBrowserMainParts::HandleContextRequest)),
"fuchsia.web.Context");

if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseLegacyMetricsService)) {
if (command_line->HasSwitch(switches::kUseLegacyMetricsService)) {
legacy_metrics_client_ =
std::make_unique<cr_fuchsia::LegacyMetricsClient>();

Expand All @@ -137,6 +119,31 @@ int WebEngineBrowserMainParts::PreMainMessageLoopRun() {
legacy_metrics_client_->Start(kMetricsReportingInterval);
}

// Configure SysInfo to report total/free space under "/data" based on the
// requested soft-quota, if any. This only affects persistent instances.
if (command_line->HasSwitch(switches::kDataQuotaBytes)) {
// Setting quota on "/data" is benign in incognito contexts, but indicates
// that the client probably mis-configured this instance.
DCHECK(command_line->HasSwitch(switches::kIncognito))
<< "data_quota_bytes set for incognito instance.";

uint64_t quota_bytes = 0;
CHECK(base::StringToUint64(
command_line->GetSwitchValueASCII(switches::kDataQuotaBytes),
&quota_bytes));
base::SysInfo::SetAmountOfTotalDiskSpace(
base::FilePath(base::kPersistedDataDirectoryPath), quota_bytes);
}

// Watch for changes to the user's locale setting.
intl_profile_watcher_ = std::make_unique<base::FuchsiaIntlProfileWatcher>(
base::BindRepeating(&WebEngineBrowserMainParts::OnIntlProfileChanged,
base::Unretained(this)));

// Configure Ozone with an Aura implementation of the Screen abstraction.
screen_ = std::make_unique<aura::ScreenOzone>();
display::Screen::SetScreenInstance(screen_.get());

// Create the MediaResourceProviderService at startup rather than on-demand,
// to allow it to perform potentially expensive startup work in the
// background.
Expand All @@ -148,6 +155,24 @@ int WebEngineBrowserMainParts::PreMainMessageLoopRun() {
// level.
content::RenderFrameHost::AllowInjectingJavaScript();

// Make sure temporary files associated with this process are cleaned up.
base::ImportantFileWriterCleaner::GetInstance().Start();

// Publish the fuchsia.web.Context service, and allow exactly one connection.
base::ComponentContextForProcess()->outgoing()->AddPublicService(
fidl::InterfaceRequestHandler<fuchsia::web::Context>(fit::bind_member(
this, &WebEngineBrowserMainParts::HandleContextRequest)));

// Now that all services have been published, it is safe to start processing
// requests to the service directory.
base::ComponentContextForProcess()->outgoing()->ServeFromStartupInfo();

// TODO(crbug.com/1163073): Update tests to make a service connection to the
// Context and remove this workaround.
if (*g_test_request)
HandleContextRequest(std::move(*g_test_request));

// In browser tests |ui_task| runs the "body" of each test.
if (parameters_.ui_task) {
// Since the main loop won't run, there is nothing to quit.
quit_closure_ = base::DoNothing::Once();
Expand All @@ -157,13 +182,6 @@ int WebEngineBrowserMainParts::PreMainMessageLoopRun() {
run_message_loop_ = false;
}

// Make sure temporary files associated with this process are cleaned up.
base::ImportantFileWriterCleaner::GetInstance().Start();

// Now that all services have been published, it is safe to start processing
// requests to the service directory.
base::ComponentContextForProcess()->outgoing()->ServeFromStartupInfo();

return content::RESULT_CODE_NORMAL_EXIT;
}

Expand Down Expand Up @@ -207,10 +225,18 @@ void WebEngineBrowserMainParts::HandleContextRequest(
return;
}

// Create the Context and configure channel-disconnect to teardown
// the WebEngine instance.
auto browser_context = std::make_unique<WebEngineBrowserContext>(
base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kIncognito));
// Create the BrowserContext for the fuchsia.web.Context, with persistence
// configured as requested via the command-line.
std::unique_ptr<WebEngineBrowserContext> browser_context;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kIncognito)) {
browser_context = WebEngineBrowserContext::CreateIncognito();
} else {
browser_context = WebEngineBrowserContext::CreatePersistent(
base::FilePath(base::kPersistedDataDirectoryPath));
}

// Create the fuchsia.web.Context implementation using the BrowserContext and
// configure it to terminate the process when the client goes away.
context_bindings_.AddBinding(
std::make_unique<ContextImpl>(std::move(browser_context),
devtools_controller_.get()),
Expand Down
3 changes: 3 additions & 0 deletions fuchsia/engine/browser/web_engine_browser_main_parts.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ class WEB_ENGINE_EXPORT WebEngineBrowserMainParts
ContextImpl* context_for_test() const;

private:
// Receives requests for the fuchsia.web.Context capability.
void HandleContextRequest(
fidl::InterfaceRequest<fuchsia::web::Context> request);

// Notified if the system timezone, language, settings change.
void OnIntlProfileChanged(const fuchsia::intl::Profile& profile);

content::ContentBrowserClient* const browser_client_;
Expand Down

0 comments on commit 2f7820b

Please sign in to comment.