perf(remote): reuse the verified release archive for SSH installs (#6288)

The first SSH install recompressed the unpacked server with fast gzip before uploading it. The release download now keeps its gzip next to the cached binary, and the SSH install sends that archive when it decodes to exactly the selected binary (size and BLAKE3 hash); custom binaries and missing or mismatched archives fall back to the existing upload. Container and WSL installs are unchanged. For the Linux arm64 payload this sends about 51 MB instead of 66 MB.

Fixes #6283

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-28 07:44:18 +08:00
1 джерело b9d0e28f7a
коміт 3a3b2e424a
7 files changed
+108 -27

No files matched your search

Створено
+1
Переглянути файл
@@ -5003,6 +5003,7 @@ dependencies = [
name = "ide-tools"
version = "0.1.54"
dependencies = [
"blake3",
"flate2",
"hex",
"http",
+10 -1
Переглянути файл
@@ -340,7 +340,16 @@ impl Session {
use std::io::Write as _;
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
gz.write_all(data)?;
let packed = gz.finish()?;
self.put_gzip_with_progress(remote, &gz.finish()?, progress).await
}
/// Sends an already compressed gzip stream; the remote file contains the decoded bytes.
pub async fn put_gzip_with_progress(
&self,
remote: &str,
packed: &[u8],
progress: &(dyn Fn(f64) + Send + Sync),
) -> IdeResult<()> {
let q = crate::shell::quote;
let dir = crate::sftp::parent(remote).unwrap_or("/");
let command = format!("mkdir -p {} && gzip -dc > {}", q(dir), q(remote));
+1
Переглянути файл
@@ -16,6 +16,7 @@ http = "1"
hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] }
tracing.workspace = true
which = "8"
blake3.workspace = true
flate2 = "1"
tar = "0.4"
zip.workspace = true
+57
Переглянути файл
@@ -5,6 +5,7 @@ use crate::process::Http;
use crate::{InstallEvent, fetch_verified, sources};
use ide_core::CancellationToken;
use ide_core::{IdeError, IdeResult};
use std::io::Read;
use std::path::{Path, PathBuf};
const RELEASES: &str = "https://github.com/l0ng-ai/openidea/releases/download";
@@ -65,18 +66,42 @@ pub fn fetch(
let unpacked = staging.join("openidea-server");
let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(&archive)?);
std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?;
drop(gz);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&unpacked, std::fs::Permissions::from_mode(0o755))?;
}
std::fs::rename(&unpacked, &dest)?;
// The executable is the cache entry; keeping the archive only optimizes SSH uploads.
let _ = std::fs::rename(archive, dest.with_extension("gz"));
Ok(dest.clone())
})();
let _ = std::fs::remove_dir_all(&staging);
result
}
/// The cached release gzip, if it unpacks to the selected server binary.
pub fn matching_archive(binary: &Path, expected: blake3::Hash) -> Option<Vec<u8>> {
let archive = binary.with_extension("gz");
let binary_size = binary.metadata().ok()?.len();
let meta = archive.metadata().ok()?;
if !meta.is_file() || meta.len() >= binary_size {
return None;
}
let mut packed = Vec::with_capacity(meta.len().try_into().ok()?);
std::fs::File::open(archive).ok()?.take(binary_size).read_to_end(&mut packed).ok()?;
if packed.len() as u64 >= binary_size {
return None;
}
// The receiver decodes every gzip member. Read one byte past the expected size
// so a correct-sized stream still has its trailer and any remaining input checked.
let gzip = flate2::read::MultiGzDecoder::new(packed.as_slice());
let mut hash = blake3::Hasher::new();
let decoded_size = std::io::copy(&mut gzip.take(binary_size.checked_add(1)?), &mut hash).ok()?;
(decoded_size == binary_size && hash.finalize() == expected).then_some(packed)
}
fn tempfile_dir(parent: &Path) -> IdeResult<PathBuf> {
// Unique per call: two windows of this process may download at once.
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
@@ -98,6 +123,38 @@ mod tests {
assert_eq!(p, Path::new("/data/server/1.2.3/linux-aarch64/openidea-server"));
}
#[test]
fn cached_archive_must_decode_to_the_selected_build() {
use std::io::Write as _;
let pack = |bytes: &[u8]| {
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
gzip.write_all(bytes).unwrap();
gzip.finish().unwrap()
};
let tmp = tempfile::tempdir().unwrap();
let binary = tmp.path().join("openidea-server");
let archive = binary.with_extension("gz");
let payload = [b'a'; 4096];
let expected = blake3::hash(&payload);
std::fs::write(&binary, payload).unwrap();
assert!(matching_archive(&binary, expected).is_none());
let gzip = pack(&payload);
std::fs::write(&archive, &gzip).unwrap();
assert_eq!(matching_archive(&binary, expected), Some(gzip.clone()));
let extra_member = pack(b"extra output");
for invalid in [
pack(&[b'b'; 4096]),
gzip[..gzip.len() - 1].to_vec(),
[gzip.as_slice(), &extra_member].concat(),
[gzip.as_slice(), b"trailing junk"].concat(),
] {
std::fs::write(&archive, &invalid).unwrap();
assert!(matching_archive(&binary, expected).is_none());
}
}
#[test]
fn unsupported_hosts_are_refused_without_downloading() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -134,7 +134,7 @@ async fn ensure_server(
}
let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
LocalServer::Binary { path, build, .. } => (path, build),
};
if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) {
return Ok(bin.clone());
+37 -24
Переглянути файл
@@ -521,8 +521,8 @@ fn server_path(path: &str) -> bool {
/// What [`local_server`] settled on.
pub(crate) enum LocalServer {
/// A server binary on this machine and its [`build_id`].
Binary(std::path::PathBuf, String),
/// A server binary on this machine. Release downloads may have a reusable archive.
Binary { path: std::path::PathBuf, build: String, release_hash: Option<blake3::Hash> },
/// No binary available (offline): this build of the version already on the host.
Installed(String),
}
@@ -538,10 +538,10 @@ pub(crate) async fn local_server(
) -> IdeResult<LocalServer> {
// This version's server: this build, or the release download (kept per version, so an
// upgraded app never reuses an older one).
let local = match local_server_binary(os, arch) {
Some(local) => local,
let (local, release) = match local_server_binary(os, arch) {
Some(local) => (local, false),
None => match download_server(state, version, os, arch, progress).await {
Ok(local) => local,
Ok(local) => (local, true),
// Offline: any build of this version already on the host will do, then a server put
// in the old unversioned place by hand.
Err(e) => {
@@ -564,7 +564,7 @@ pub(crate) async fn local_server(
e.message,
local.display()
);
local
(local, false)
}
None => {
return Err(IdeError::unavailable(format!(
@@ -581,13 +581,14 @@ pub(crate) async fn local_server(
},
};
// One folder per build, so a rebuilt server of the same version is installed again.
let build = tokio::task::spawn_blocking({
let hash = tokio::task::spawn_blocking({
let local = local.clone();
move || build_id(&local)
move || binary_hash(&local)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
Ok(LocalServer::Binary(local, build))
let build = hash.to_hex()[..16].to_owned();
Ok(LocalServer::Binary { path: local, build, release_hash: release.then_some(hash) })
}
/// Makes sure this version of the server is installed on the host; returns its path.
@@ -604,10 +605,11 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
let mut lines = probe.lines().map(str::trim).filter(|l| !l.is_empty());
let (os, arch) = platform(lines.next().unwrap_or_default());
let installed: Vec<String> = lines.map(str::to_owned).collect();
let (local, build) = match local_server(state, version, &os, &arch, &installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
};
let (local, build, release_hash) =
match local_server(state, version, &os, &arch, &installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary { path, build, release_hash } => (path, build, release_hash),
};
if let Some(bin) = installed.iter().find(|b| b.ends_with(&format!("/{build}/openidea-server"))) {
return Ok(bin.to_string());
}
@@ -624,9 +626,20 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
);
let started = std::time::Instant::now();
progress(RemoteStage::Uploading, Some(0.0));
session
.put_with_progress(&tmp, &tokio::fs::read(&local).await?, &|f| progress(RemoteStage::Uploading, Some(f)))
.await?;
let archive = if let Some(hash) = release_hash {
let local = local.clone();
tokio::task::spawn_blocking(move || ide_tools::server::matching_archive(&local, hash))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
} else {
None
};
let report = |f| progress(RemoteStage::Uploading, Some(f));
if let Some(archive) = archive {
session.put_gzip_with_progress(&tmp, &archive, &report).await?;
} else {
session.put_with_progress(&tmp, &tokio::fs::read(&local).await?, &report).await?;
}
tracing::info!("installed openidea-server on {} in {:?}", session.label(), started.elapsed());
let q = ide_ssh::shell::quote;
// Older builds of this version go (a running one keeps its open file).
@@ -646,21 +659,21 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A
Ok(remote_bin)
}
/// A short content hash of the server binary (cached per path, size and time).
fn build_id(path: &std::path::Path) -> IdeResult<String> {
static CACHE: Mutex<Option<(std::path::PathBuf, u64, std::time::SystemTime, String)>> = Mutex::new(None);
/// The content hash of the server binary (cached per path, size and time).
fn binary_hash(path: &std::path::Path) -> IdeResult<blake3::Hash> {
static CACHE: Mutex<Option<(std::path::PathBuf, u64, std::time::SystemTime, blake3::Hash)>> = Mutex::new(None);
let meta = std::fs::metadata(path)?;
let modified = meta.modified()?;
if let Some((p, len, time, id)) = &*CACHE.lock()
if let Some((p, len, time, hash)) = &*CACHE.lock()
&& p == path
&& *len == meta.len()
&& *time == modified
{
return Ok(id.clone());
return Ok(*hash);
}
let id = blake3::hash(&std::fs::read(path)?).to_hex()[..16].to_owned();
*CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, id.clone()));
Ok(id)
let hash = blake3::Hasher::new().update_reader(std::fs::File::open(path)?)?.finalize();
*CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, hash));
Ok(hash)
}
/// File › Remote Development: opens `path` on `target` (an SSH host, a WSL distribution, or a
+1 -1
Переглянути файл
@@ -230,7 +230,7 @@ pub(crate) async fn ensure_server(
}
let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? {
LocalServer::Installed(bin) => return Ok(bin),
LocalServer::Binary(local, build) => (local, build),
LocalServer::Binary { path, build, .. } => (path, build),
};
if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) {
return Ok(bin.clone());