#ifndef COMPONENTS_SERVICES_HEAP_PROFILING_CONNECTION_MANAGER_H_
#define COMPONENTS_SERVICES_HEAP_PROFILING_CONNECTION_MANAGER_H_
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include "base/containers/flat_map.h"
#include "base/functional/callback_forward.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "components/services/heap_profiling/allocation.h"
#include "components/services/heap_profiling/public/mojom/heap_profiling_service.mojom.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom.h"
namespace heap_profiling {
struct ExportParams;
using VmRegions =
base::flat_map<base::ProcessId,
std::vector<memory_instrumentation::mojom::VmRegionPtr>>;
class ConnectionManager {
using AddressToStringMap = std::unordered_map<uint64_t, std::string>;
using CompleteCallback = base::OnceClosure;
using ContextMap = std::map<std::string, int>;
using DumpProcessesForTracingCallback = memory_instrumentation::mojom::
HeapProfiler::DumpProcessesForTracingCallback;
public:
ConnectionManager();
ConnectionManager(const ConnectionManager&) = delete;
ConnectionManager& operator=(const ConnectionManager&) = delete;
~ConnectionManager();
void DumpProcessesForTracing(bool strip_path_from_mapped_files,
bool write_proto,
DumpProcessesForTracingCallback callback,
VmRegions vm_regions);
void OnNewConnection(base::ProcessId pid,
mojo::PendingRemote<mojom::ProfilingClient> client,
mojom::ProcessType process_type,
mojom::ProfilingParamsPtr params,
mojom::ProfilingService::AddProfilingClientCallback
started_profiling_closure);
std::vector<base::ProcessId> GetConnectionPids();
std::vector<base::ProcessId> GetConnectionPidsThatNeedVmRegions();
private:
struct Connection;
struct DumpProcessesForTracingTracking;
void HeapProfileRetrieved(
scoped_refptr<DumpProcessesForTracingTracking> tracking,
base::ProcessId pid,
mojom::ProcessType process_type,
bool strip_path_from_mapped_files,
uint32_t sampling_rate,
mojom::HeapProfilePtr profile);
bool ConvertProfileToExportParams(mojom::HeapProfilePtr profile,
uint32_t sampling_rate,
ExportParams* out_params);
void OnConnectionComplete(base::ProcessId pid);
void OnProfilingStarted(base::ProcessId pid);
void ReportMetrics();
size_t next_id_ = 1;
base::flat_map<base::ProcessId, std::unique_ptr<Connection>> connections_;
base::Lock connections_lock_;
base::RepeatingTimer metrics_timer_;
base::WeakPtrFactory<ConnectionManager> weak_factory_{this};
};
}
#endif