fune/toolkit/components/backgroundtasks/BackgroundTasksRunner.cpp
Kagami Sascha Rosylight d20dd96f8f Bug 1791675 - Part 4: Make sure purgeHTTPCache runs after shutdown r=webdriver-reviewers,necko-reviewers,valentin,nalexander,whimboo
This adds BackgroundTasksRunner utility class as a generic way to properly run background tasks. A few argument for not extending existing BackgroundTasksUtils:

1. Simply because the existing use case is in C++.
2. I have another use case from JSM and thus I'll ultimately convert this an XPCOM component. And `CacheFileIOManager::DispatchPurgeTask` cannot get a JSM-written XPCOM instance which is required to be main-thread only.

Depends on D157998

Differential Revision: https://phabricator.services.mozilla.com/D157757
2022-11-08 15:42:24 +00:00

83 lines
2.3 KiB
C++

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/BackgroundTasksRunner.h"
#include "base/process_util.h"
#include "mozilla/StaticPrefs_toolkit.h"
#include "nsIFile.h"
#ifdef XP_WIN
# include "mozilla/AssembleCmdLine.h"
#endif
namespace mozilla {
nsresult BackgroundTasksRunner::RunInDetachedProcess(
const nsACString& aTaskName, const nsTArray<nsCString>& aArgs) {
nsCOMPtr<nsIFile> lf;
nsresult rv = XRE_GetBinaryPath(getter_AddRefs(lf));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString exePath;
#if !defined(XP_WIN)
rv = lf->GetNativePath(exePath);
#else
rv = lf->GetNativeTarget(exePath);
#endif
NS_ENSURE_SUCCESS(rv, rv);
base::LaunchOptions options;
#ifdef XP_WIN
options.start_independent = true;
nsTArray<const char*> argv = {exePath.Data(), "--backgroundtask",
aTaskName.Data()};
for (const nsCString& str : aArgs) {
argv.AppendElement(str.get());
}
argv.AppendElement(nullptr);
wchar_t* assembledCmdLine = nullptr;
if (assembleCmdLine(argv.Elements(), &assembledCmdLine, CP_UTF8) == -1) {
return NS_ERROR_FAILURE;
}
if (!base::LaunchApp(assembledCmdLine, options, nullptr)) {
return NS_ERROR_FAILURE;
}
#else
std::vector<std::string> argv = {exePath.Data(), "--backgroundtask",
aTaskName.Data()};
for (const nsCString& str : aArgs) {
argv.push_back(str.get());
}
if (!base::LaunchApp(argv, options, nullptr)) {
return NS_ERROR_FAILURE;
}
#endif
return NS_OK;
}
nsresult BackgroundTasksRunner::RemoveDirectoryInDetachedProcess(
const nsCString& aParentDirPath, const nsCString& aChildDirName,
const nsCString& aSecondsToWait, const nsCString& aOtherFoldersSuffix) {
nsTArray<nsCString> argv = {aParentDirPath, aChildDirName, aSecondsToWait,
aOtherFoldersSuffix};
uint32_t testingSleepMs =
StaticPrefs::toolkit_background_tasks_remove_directory_testing_sleep_ms();
if (testingSleepMs > 0) {
argv.AppendElement("--test-sleep");
nsAutoCString sleep;
sleep.AppendInt(testingSleepMs);
argv.AppendElement(sleep);
}
return RunInDetachedProcess("removeDirectory"_ns, argv);
}
} // namespace mozilla