Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
250 changes: 236 additions & 14 deletions src/server/master_server.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "server/master_server.h"

#include <algorithm>
#include <format>
#include <optional>
#include <string>
#include <type_traits>
Expand Down Expand Up @@ -132,6 +134,185 @@ void MasterServer::clear_diagnostics(const std::string& uri) {
peer.send_notification(params);
}

/// Serializable cache structures for cache.json persistence.
namespace {

struct CacheDepEntry {
std::string path;
std::uint64_t hash;
};

struct CachePCHEntry {
std::string filename;
std::string source_file;
std::uint64_t hash;
std::uint32_t bound;
std::int64_t build_at;
std::vector<CacheDepEntry> deps;
};

struct CachePCMEntry {
std::string filename;
std::string source_file;
std::string module_name;
std::int64_t build_at;
std::vector<CacheDepEntry> deps;
};

struct CacheData {
std::vector<CachePCHEntry> pch;
std::vector<CachePCMEntry> pcm;
};

} // namespace

void MasterServer::load_cache() {
if(config.cache_dir.empty())
return;

auto cache_path = path::join(config.cache_dir, "cache", "cache.json");
auto content = fs::read(cache_path);
if(!content) {
LOG_DEBUG("No cache.json found at {}", cache_path);
return;
}

CacheData data;
auto status = et::serde::json::from_json(*content, data);
if(!status) {
LOG_WARN("Failed to parse cache.json");
return;
}

for(auto& entry: data.pch) {
auto pch_path = path::join(config.cache_dir, "cache", "pch", entry.filename);
if(!llvm::sys::fs::exists(pch_path) || entry.source_file.empty())
continue;

DepsSnapshot deps;
deps.build_at = entry.build_at;
for(auto& dep: entry.deps) {
deps.path_ids.push_back(path_pool.intern(dep.path));
deps.hashes.push_back(dep.hash);
}

auto path_id = path_pool.intern(entry.source_file);
auto& st = pch_states[path_id];
st.path = pch_path;
st.hash = entry.hash;
st.bound = entry.bound;
st.deps = std::move(deps);

LOG_DEBUG("Loaded cached PCH: {} -> {}", entry.source_file, pch_path);
}

for(auto& entry: data.pcm) {
auto pcm_path = path::join(config.cache_dir, "cache", "pcm", entry.filename);
if(!llvm::sys::fs::exists(pcm_path) || entry.source_file.empty())
continue;

DepsSnapshot deps;
deps.build_at = entry.build_at;
for(auto& dep: entry.deps) {
deps.path_ids.push_back(path_pool.intern(dep.path));
deps.hashes.push_back(dep.hash);
}

auto path_id = path_pool.intern(entry.source_file);
pcm_states[path_id] = {pcm_path, std::move(deps)};
pcm_paths[path_id] = pcm_path;

LOG_DEBUG("Loaded cached PCM: {} (module {}) -> {}",
entry.source_file,
entry.module_name,
pcm_path);
}

LOG_INFO("Loaded cache.json: {} PCH entries, {} PCM entries",
pch_states.size(),
pcm_states.size());
}

void MasterServer::save_cache() {
if(config.cache_dir.empty())
return;

CacheData data;

for(auto& [path_id, st]: pch_states) {
if(st.path.empty())
continue;

CachePCHEntry entry;
entry.filename = std::string(path::filename(st.path));
entry.source_file = std::string(path_pool.resolve(path_id));
entry.hash = st.hash;
entry.bound = st.bound;
entry.build_at = st.deps.build_at;
for(std::size_t i = 0; i < st.deps.path_ids.size(); ++i) {
entry.deps.push_back(
{std::string(path_pool.resolve(st.deps.path_ids[i])), st.deps.hashes[i]});
}
data.pch.push_back(std::move(entry));
}

for(auto& [path_id, st]: pcm_states) {
if(st.path.empty())
continue;

CachePCMEntry entry;
entry.filename = std::string(path::filename(st.path));
entry.source_file = std::string(path_pool.resolve(path_id));
auto mod_it = path_to_module.find(path_id);
entry.module_name = mod_it != path_to_module.end() ? mod_it->second : "";
entry.build_at = st.deps.build_at;
for(std::size_t i = 0; i < st.deps.path_ids.size(); ++i) {
entry.deps.push_back(
{std::string(path_pool.resolve(st.deps.path_ids[i])), st.deps.hashes[i]});
}
data.pcm.push_back(std::move(entry));
}

auto json_str = et::serde::json::to_json(data);
if(!json_str) {
LOG_WARN("Failed to serialize cache.json");
return;
}

auto cache_path = path::join(config.cache_dir, "cache", "cache.json");
auto write_result = fs::write(cache_path, *json_str);
if(!write_result) {
LOG_WARN("Failed to write cache.json: {}", write_result.error().message());
}
}

void MasterServer::cleanup_cache(int max_age_days) {
if(config.cache_dir.empty())
return;

auto now = std::chrono::system_clock::now();
auto max_age = std::chrono::hours(max_age_days * 24);

for(auto* subdir: {"cache/pch", "cache/pcm"}) {
auto dir = path::join(config.cache_dir, subdir);
std::error_code ec;
for(auto it = llvm::sys::fs::directory_iterator(dir, ec);
!ec && it != llvm::sys::fs::directory_iterator();
it.increment(ec)) {
llvm::sys::fs::file_status status;
if(auto stat_ec = llvm::sys::fs::status(it->path(), status))
continue;

auto mtime = status.getLastModificationTime();
auto age = now - mtime;
if(age > max_age) {
llvm::sys::fs::remove(it->path());
LOG_DEBUG("Cleaned up stale cache file: {}", it->path());
}
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

et::task<> MasterServer::load_workspace() {
if(workspace_root.empty())
co_return;
Expand All @@ -144,6 +325,19 @@ et::task<> MasterServer::load_workspace() {
} else {
LOG_INFO("Cache directory: {}", config.cache_dir);
}

// Create cache/pch/ and cache/pcm/ subdirectories
for(auto* subdir: {"cache/pch", "cache/pcm"}) {
auto dir = path::join(config.cache_dir, subdir);
auto ec2 = llvm::sys::fs::create_directories(dir);
if(ec2) {
LOG_WARN("Failed to create {}: {}", dir, ec2.message());
}
}

// Load persistent cache and clean up stale files.
load_cache();
cleanup_cache();
}

// Search for compile_commands.json
Expand Down Expand Up @@ -270,18 +464,37 @@ et::task<> MasterServer::load_workspace() {
}

auto file_path = std::string(path_pool.resolve(path_id));

// Compute deterministic content-addressed PCM path.
// Replace ':' with '-' in module name for filesystem safety.
auto safe_module_name = mod_it->second;
std::ranges::replace(safe_module_name, ':', '-');
auto args_hash = llvm::xxh3_64bits(llvm::StringRef(file_path));
auto pcm_filename = std::format("{}-{:016x}.pcm", safe_module_name, args_hash);
auto pcm_path = path::join(config.cache_dir, "cache", "pcm", pcm_filename);

// Check if cached PCM is still valid.
if(auto pcm_it = pcm_states.find(path_id); pcm_it != pcm_states.end()) {
if(!pcm_it->second.path.empty() && llvm::sys::fs::exists(pcm_it->second.path) &&
!deps_changed(path_pool, pcm_it->second.deps)) {
pcm_paths[path_id] = pcm_it->second.path;
co_return true;
}
}

worker::BuildPCMParams pcm_params;
pcm_params.file = file_path;
if(!fill_compile_args(file_path, pcm_params.directory, pcm_params.arguments)) {
co_return false;
}
pcm_params.module_name = mod_it->second;
pcm_params.output_path = pcm_path;

// Clang needs ALL transitive PCM deps, not just direct imports.
for(auto& [pid, pcm_path]: pcm_paths) {
for(auto& [pid, existing_pcm_path]: pcm_paths) {
auto dep_mod_it = path_to_module.find(pid);
if(dep_mod_it != path_to_module.end()) {
pcm_params.pcms[dep_mod_it->second] = pcm_path;
pcm_params.pcms[dep_mod_it->second] = existing_pcm_path;
}
}

Expand All @@ -294,7 +507,13 @@ et::task<> MasterServer::load_workspace() {
}

pcm_paths[path_id] = result.value().pcm_path;
pcm_states[path_id] = {result.value().pcm_path,
capture_deps_snapshot(path_pool, result.value().deps)};
LOG_INFO("Built PCM for module {}: {}", mod_it->second, result.value().pcm_path);

// Persist cache metadata after successful build.
save_cache();

co_return true;
};

Expand Down Expand Up @@ -327,16 +546,16 @@ et::task<bool> MasterServer::ensure_pch(std::uint32_t path_id,
auto bound = compute_preamble_bound(text);
if(bound == 0) {
// No preamble directives — PCH would be empty. Clear any stale entry.
auto it = pch_states.find(path_id);
if(it != pch_states.end()) {
fs::remove(it->second.path);
pch_states.erase(it);
}
pch_states.erase(path_id);
co_return true;
}

auto preamble_hash = llvm::xxh3_64bits(llvm::StringRef(text).substr(0, bound));

// Deterministic content-addressed PCH path.
auto pch_path =
path::join(config.cache_dir, "cache", "pch", std::format("{:016x}.pch", preamble_hash));

// Reuse existing PCH if preamble content and deps haven't changed.
if(auto it = pch_states.find(path_id); it != pch_states.end()) {
auto& st = it->second;
Expand All @@ -363,8 +582,9 @@ et::task<bool> MasterServer::ensure_pch(std::uint32_t path_id,
pch_params.arguments = arguments;
pch_params.content = text;
pch_params.preamble_bound = bound;
pch_params.output_path = pch_path;

LOG_DEBUG("Building PCH for {}, bound={}", path, bound);
LOG_DEBUG("Building PCH for {}, bound={}, output={}", path, bound, pch_path);

auto result = co_await pool.send_stateless(pch_params);

Expand All @@ -377,12 +597,9 @@ et::task<bool> MasterServer::ensure_pch(std::uint32_t path_id,
co_return false;
}

// Delete old PCH temp file before replacing.
// Update state — no need to delete old file; content-addressed names differ
// when content differs, and the 7-day cleanup handles orphaned files.
auto& st = pch_states[path_id];
if(!st.path.empty()) {
fs::remove(st.path);
}

st.path = result.value().pch_path;
st.bound = bound;
st.hash = preamble_hash;
Expand All @@ -391,6 +608,9 @@ et::task<bool> MasterServer::ensure_pch(std::uint32_t path_id,

LOG_INFO("PCH built for {}: {}", path, result.value().pch_path);

// Persist cache metadata after successful build.
save_cache();

completion->set();
co_return true;
}
Expand Down Expand Up @@ -1331,8 +1551,9 @@ void MasterServer::register_handlers() {
lifecycle = ServerLifecycle::Exited;
LOG_INFO("Exit notification received");

// Persist index state before stopping.
// Persist index and cache state before stopping.
save_index();
save_cache();

// Graceful shutdown: cancel compilations, stop workers, then stop loop
loop.schedule([this]() -> et::task<> {
Expand Down Expand Up @@ -1442,6 +1663,7 @@ void MasterServer::register_handlers() {
// Remove stale PCMs for all invalidated units.
for(auto dirty_id: dirtied) {
pcm_paths.erase(dirty_id);
pcm_states.erase(dirty_id);
}
// Mark ast_dirty for open documents that depend on the saved file.
for(auto dirty_id: dirtied) {
Expand Down
21 changes: 21 additions & 0 deletions src/server/master_server.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ struct PCHState {
std::shared_ptr<et::event> building;
};

/// Cached PCM state for a single module file.
struct PCMState {
/// Built PCM file path.
std::string path;

/// Dependency snapshot for staleness detection.
DepsSnapshot deps;
};

/// Information about a symbol at a given position.
struct SymbolInfo {
/// Unique hash identifying this symbol across the project.
Expand Down Expand Up @@ -155,6 +164,9 @@ class MasterServer {
/// path_id -> cached PCH state (path, preamble hash, deps, build event).
llvm::DenseMap<std::uint32_t, PCHState> pch_states;

/// path_id -> cached PCM state (path, deps).
llvm::DenseMap<std::uint32_t, PCMState> pcm_states;

// === Index state ===

/// Global symbol table and path mapping for the project.
Expand Down Expand Up @@ -240,6 +252,15 @@ class MasterServer {
/// Load index state from disk.
void load_index();

/// Load PCH/PCM cache metadata from cache.json.
void load_cache();

/// Save PCH/PCM cache metadata to cache.json.
void save_cache();

/// Clean up stale cache files older than max_age_days.
void cleanup_cache(int max_age_days = 7);

// === Feature request forwarding ===

using RawResult = et::task<et::serde::RawValue, et::ipc::Error>;
Expand Down
Loading
Loading