Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "logos-devnet"
version = "0.9.0"
version = "0.9.1"
edition = "2024"
rust-version = "1.89"
description = "A local LEZ chain for Logos development: one command to start it, fund accounts and deploy programs"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ cargo install --locked logos-devnet
Or take a binary from the [latest release](https://github.com/drptbl/logos-devnet/releases/latest), built for macOS (`aarch64-apple-darwin`, `x86_64-apple-darwin`) and Linux (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, static, so any distribution), and check it against its `.sha256`:

```bash
v=v0.9.0 t=aarch64-apple-darwin
v=v0.9.1 t=aarch64-apple-darwin
curl -fsSL --remote-name-all https://github.com/drptbl/logos-devnet/releases/download/$v/logos-devnet-$v-$t.tar.gz{,.sha256}
shasum -a 256 -c logos-devnet-$v-$t.tar.gz.sha256 \
&& tar -xzf logos-devnet-$v-$t.tar.gz \
Expand Down Expand Up @@ -279,7 +279,7 @@ With `--json`, a command prints one JSON document and nothing else on stdout. No
The repo is a GitHub Action. On a Linux runner it installs `logos-devnet`, starts the devnet from your project file and exports the env into the job:

```yaml
- uses: drptbl/logos-devnet@v0.9.0
- uses: drptbl/logos-devnet@v0.9.1
with:
args: --max-txs-per-block 100 # optional, more options for up
- run: cargo test # LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE are set
Expand Down
2 changes: 1 addition & 1 deletion examples/github-actions/devnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
# Installs logos-devnet, starts the devnet from logos-devnet.toml, and exports its env
# (LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE).
- id: devnet
uses: drptbl/logos-devnet@v0.9.0
uses: drptbl/logos-devnet@v0.9.1
- run: cargo test
- name: The devnet's logs
if: failure()
Expand Down
116 changes: 114 additions & 2 deletions src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,66 @@ pub fn check_url(url: &str) -> Result<()> {
Ok(())
}

/// How old a download in progress is when no process still writes it: curl's few tries of
/// 10 minutes each, and a package download, are done well within a day.
const STALE_PART: std::time::Duration = std::time::Duration::from_secs(24 * 3600);

/// Where this process downloads `name` before it takes its place: `.part-<token>-<name>`, with
/// the process id and the time in the token. Every home shares the download directory, so the
/// name is this run's own, even when a process id comes round again.
pub fn part_name(name: &str) -> String {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
format!(".part-{}x{nanos}-{name}", std::process::id())
}

/// Whether `name` is one `part_name` made. Kept files never start with `.`.
fn is_part(name: &str) -> bool {
name.strip_prefix(".part-")
.and_then(|rest| rest.split_once('-'))
.is_some_and(|(token, file)| {
!token.is_empty()
&& token.bytes().all(|b| b.is_ascii_alphanumeric())
&& !file.is_empty()
})
}

/// When `path` last changed: for a directory, the newest of it and what it holds, since writing
/// a file in it leaves the directory's own time alone.
fn last_modified(path: &Path) -> Option<std::time::SystemTime> {
let own = std::fs::symlink_metadata(path)
.and_then(|m| m.modified())
.ok()?;
let inside = std::fs::read_dir(path)
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.metadata().and_then(|m| m.modified()).ok());
inside.chain([own]).max()
}

/// Deletes downloads in progress in `dir` that a crashed or killed process left behind: every
/// home shares the directory, so they would pile up. One that fails to go stays.
pub fn remove_stale_parts(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let stale = is_part(&entry.file_name().to_string_lossy())
&& last_modified(&entry.path())
.is_some_and(|t| t.elapsed().is_ok_and(|age| age > STALE_PART));
if !stale {
continue;
}
// A symlink is removed, never followed.
let _ = match entry.file_type() {
Ok(kind) if kind.is_dir() => std::fs::remove_dir_all(entry.path()),
_ => std::fs::remove_file(entry.path()),
};
}
}

/// The file at `url` whose SHA-256 is `sha256`, kept in `dir`: downloaded the first time, and
/// from then on read from `dir`. Several homes share `dir`, so a download lands under a name of
/// this process's own and is renamed into place.
Expand All @@ -38,7 +98,8 @@ pub fn cached(dir: &Path, url: &str, sha256: &str) -> Result<PathBuf> {
return Ok(path);
}
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
let part = dir.join(format!("{sha256}.part-{}", std::process::id()));
remove_stale_parts(dir);
let part = dir.join(part_name(&format!("{sha256}.bin")));
eprintln!("Downloading {url}...");
let status = Command::new("curl")
.args([
Expand Down Expand Up @@ -156,13 +217,64 @@ pub(crate) mod tests {
let dir = tempfile::tempdir().unwrap();
let body: &[u8] = b"a program";
let sha = sha256_hex(body);
let theirs = dir.path().join(format!("{sha}.part"));
let theirs = dir.path().join(format!(".part-1-{sha}.bin"));
std::fs::create_dir(&theirs).unwrap();
let path = cached(dir.path(), &serve("200 OK", body, 1), &sha).unwrap();
assert_eq!(std::fs::read(path).unwrap(), body);
assert!(theirs.is_dir(), "the other download was touched");
}

#[test]
fn removes_downloads_a_crash_left_behind() {
let dir = tempfile::tempdir().unwrap();
let day_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(25 * 3600);
let old_file = dir.path().join(format!(".part-1-{}.bin", "a".repeat(64)));
let old_dir = dir.path().join(".part-2-lez_core-0.5.1.lgx");
let fresh = dir.path().join(format!(".part-3-{}.bin", "b".repeat(64)));
let kept = dir.path().join(format!("{}.bin", "c".repeat(64)));
// A version may hold `.part-`: the package keeps its place.
let odd = dir.path().join("lez_core-0.5.1.part-2.lgx");
// A package still downloading: its directory is old, the file in it is not.
let live = dir.path().join(".part-4-chat_module-0.3.0.lgx");
std::fs::create_dir(&live).unwrap();
std::fs::write(live.join("chat_module-0.3.0.lgx"), "downloading").unwrap();
std::fs::write(&old_file, "half").unwrap();
std::fs::create_dir(&old_dir).unwrap();
std::fs::write(&fresh, "downloading").unwrap();
std::fs::write(&kept, "a program").unwrap();
std::fs::write(&odd, "a package").unwrap();
for path in [&old_file, &kept, &odd] {
std::fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(day_ago)
.unwrap();
}
for dir in [&old_dir, &live] {
std::fs::File::open(dir)
.unwrap()
.set_modified(day_ago)
.unwrap();
}
remove_stale_parts(dir.path());
assert!(live.exists(), "a download still writing");
assert!(!old_file.exists() && !old_dir.exists());
assert!(fresh.exists(), "another process may be downloading it");
assert!(kept.exists() && odd.exists(), "only downloads in progress");
// A download cleans up on its way.
std::fs::write(&old_file, "half").unwrap();
std::fs::File::options()
.write(true)
.open(&old_file)
.unwrap()
.set_modified(day_ago)
.unwrap();
let body: &[u8] = b"a program";
cached(dir.path(), &serve("200 OK", body, 1), &sha256_hex(body)).unwrap();
assert!(!old_file.exists());
}

#[test]
fn takes_a_sha256_as_shasum_prints_it() {
assert!(check_sha256(&sha256_hex(b"x")).is_ok());
Expand Down
121 changes: 88 additions & 33 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,49 +451,56 @@ impl Logosctl {
};
check_module_name(name)?;
check_version(version)?;
let file = self.cached_package(name, version, packages)?;
self.run(&["package", "install", &path_text(&file), "--yes"])?;
self.install_package(name, version, packages)?;
}
Ok(())
}

/// `<packages>/<name>-<version>.lgx`, checked against the catalog's SHA-256: a file that
/// doesn't match is downloaded again. A download lands in a directory of its own first, so
/// an interrupted one never takes the file's place.
fn cached_package(&self, name: &str, version: &str, packages: &Path) -> Result<PathBuf> {
/// Installs `name` at `version`, from `<packages>/<name>-<version>.lgx` when it matches the
/// catalog's SHA-256, else from a new download, which is kept there once it matches. Every
/// home shares `packages`, so what's installed is this process's own: a hard link to the
/// kept file, checked after it's made, since another home may rename a file into its place
/// but never changes one, or the download, in a directory of its own. A package the catalog
/// gives no SHA-256 for is never kept, since nothing could check it.
fn install_package(&self, name: &str, version: &str, packages: &Path) -> Result<()> {
let file_name = format!("{name}-{version}.lgx");
let file = packages.join(&file_name);
let kept = packages.join(&file_name);
let sha256 = self.catalog_sha256(name, version)?;
let matches = |path: &Path| match &sha256 {
Some(wanted) => crate::binary::file_sha256(path).is_ok_and(|got| &got == wanted),
None => path.exists(),
let checked = |path: &Path| {
sha256.as_ref().is_some_and(|wanted| {
crate::binary::file_sha256(path).is_ok_and(|got| &got == wanted)
})
};
if matches(&file) {
return Ok(file);
}
let part = packages.join(format!(".part-{}-{file_name}", std::process::id()));
crate::fetch::remove_stale_parts(packages);
let part = packages.join(crate::fetch::part_name(&file_name));
std::fs::create_dir_all(&part).with_context(|| format!("creating {}", part.display()))?;
let downloaded = part.join(&file_name);
let fetched = self
.run(&[
"package",
"download",
name,
"--version",
version,
"-o",
&path_text(&part),
])
.and_then(|_| {
if !matches(&downloaded) {
let mine = part.join(&file_name);
let installed = (|| {
let reused = std::fs::hard_link(&kept, &mine).is_ok() && checked(&mine);
if !reused {
let _ = std::fs::remove_file(&mine);
self.run(&[
"package",
"download",
name,
"--version",
version,
"-o",
&path_text(&part),
])?;
if sha256.is_some() && !checked(&mine) {
bail!("{name} {version} downloaded, but not with the catalog's SHA-256");
}
std::fs::rename(&downloaded, &file)
.with_context(|| format!("keeping {}", file.display()))
});
}
self.run(&["package", "install", &path_text(&mine), "--yes"])?;
if !reused && sha256.is_some() {
std::fs::rename(&mine, &kept)
.with_context(|| format!("keeping {}", kept.display()))?;
}
Ok(())
})();
let _ = std::fs::remove_dir_all(&part);
fetched?;
Ok(file)
installed
}

/// The SHA-256 the catalog gives for `name`'s package at `version`, when it gives one.
Expand Down Expand Up @@ -1250,7 +1257,13 @@ esac"#
"delivery_module-0.3.3",
] {
let file = packages.join(format!("{package}.lgx"));
assert!(first.contains(&format!("package install {} --yes", file.display())));
assert!(file.exists(), "{package} is kept");
let mine = format!("/{package}.lgx --yes");
assert!(
first.contains(&format!("package install {}/.part-", packages.display()))
&& first.contains(&mine),
"installed from this process's own copy: {first}"
);
}
// Another daemon, the same devnet: everything comes from the files.
std::fs::remove_file(dir.path().join("calls.log")).unwrap();
Expand Down Expand Up @@ -1294,6 +1307,48 @@ esac"#
);
}

#[test]
fn installs_a_package_the_catalog_gives_no_sha256_for_from_its_own_download() {
let dir = tempfile::tempdir().unwrap();
let packages = dir.path().join("packages");
std::fs::create_dir_all(&packages).unwrap();
// Another home put it in the shared directory, and nothing can check it.
let planted = packages.join("lez_core-0.5.1.lgx");
std::fs::write(&planted, "planted").unwrap();
// A download a crashed process left a day ago.
let left = packages.join(".part-1-lez_core-0.5.1.lgx");
std::fs::create_dir(&left).unwrap();
let day_ago = std::time::SystemTime::now() - Duration::from_secs(25 * 3600);
std::fs::File::open(&left)
.unwrap()
.set_modified(day_ago)
.unwrap();
let ctl = fake_logosctl(
dir.path(),
r#"case "$2 $3 $4" in
"package install lez_core") echo '{"changes":[{"name":"lez_core","toVersion":"0.5.1"}]}' ;;
"package show lez_core") echo '{"versions":[{"manifest":{"version":"0.5.1"}}]}' ;;
"package download "*) printf fresh > "$8/$4-$6.lgx"; echo '{"status":"ok"}' ;;
*) echo '{"status":"ok"}' ;;
esac"#,
);
ctl.install(&["lez_core".into()], &packages).unwrap();
let log = calls(dir.path());
assert!(log.contains("package download lez_core"), "{log}");
assert!(
log.contains(&format!("package install {}/.part-", packages.display())),
"installed from its own download: {log}"
);
assert!(
!log.contains(&format!("install {} ", planted.display())),
"{log}"
);
assert_eq!(std::fs::read_to_string(&planted).unwrap(), "planted");
assert!(!left.exists(), "the crash's download is cleaned up");
let parts = std::fs::read_dir(&packages).unwrap().count();
assert_eq!(parts, 1, "nothing of this download is kept");
}

#[test]
fn takes_only_plain_versions() {
assert!(check_version("0.5.1").is_ok());
Expand Down
Loading