diff --git a/Cargo.lock b/Cargo.lock index 748ff88..c2913fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -473,7 +473,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "logos-devnet" -version = "0.8.0" +version = "0.9.0" dependencies = [ "anyhow", "bs58", diff --git a/Cargo.toml b/Cargo.toml index 58dfd20..d5d09e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "logos-devnet" -version = "0.8.0" +version = "0.9.0" edition = "2024" rust-version = "1.89" description = "A local LEZ chain for Logos development: one command to start it, fund accounts and deploy programs" diff --git a/README.md b/README.md index 020e932..5c2ebac 100644 --- a/README.md +++ b/README.md @@ -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.8.0 t=aarch64-apple-darwin +v=v0.9.0 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 \ @@ -40,8 +40,8 @@ source ~/.logos-devnet/env # LOGOS_DEVNET_SEQUENCER, LOG | `up` | Starts the devnet, or resumes it, and makes it match your `logos-devnet.toml`. Takes `--docker` or `--native`, `--lez ` (a v0.3 tag), `--port`, `--block-time`, `--max-txs-per-block`, `--dev-mode` and `--log-filter`, and remembers them. `--rebuild` builds the image or binaries again. | | `down` | Stops it. The chain is kept. | | `reset` | Deletes the chain and starts a new one, every account group funded at genesis. Takes the same options as `up`. | -| `status` | What runs, the chain head, the faucet, programs, account groups, sessions, the messaging hub and local storage. | -| `doctor` | Checks the project file, Docker and the image (or git and cargo with `--native`), whether the chain takes the project's settings, the `[programs]` files, the port, the hub's ports, the faucet, `curl` for programs from a release and, when sessions or the hub need it, `logosctl`, and says how to fix what fails. | +| `status` | What runs, the chain head, the faucet, programs, account groups, sessions (and which stopped while the chain runs), the messaging hub and local storage. | +| `doctor` | Checks the project file, Docker and the image (or git and cargo with `--native`), whether the chain takes the project's settings, the `[programs]` files, the port, the hub's ports, the faucet, sessions that stopped while the chain runs, `curl` for programs from a release and, when sessions or the hub need it, `logosctl`, and says how to fix what fails. | | `fund [amount]` | Sends lepta from the faucet to a public account, 10B by default. | | `deploy [--mutable]` | Deploys a program, from its `.bin` (what `cargo risczero build` makes, not the bare ELF), and adds `LOGOS_PROGRAM_` and `LOGOS_PROGRAM__HEX` to the env file. Names are lower-case letters, digits and `-`. With `--mutable`, a new build updates it in place. | | `wallet-config ` | Writes a `wallet_config.json` pointing at the devnet into a new wallet directory. | @@ -50,9 +50,10 @@ source ~/.logos-devnet/env # LOGOS_DEVNET_SEQUENCER, LOG | `tx [--wait] [--timeout ]` | Shows which block holds a transaction, by its 64-hex hash. `--wait` waits until one does, instead of a `sleep`, and fails after 60 s. | | `account ` | Shows an account's balance, nonce and data, and its id in base58 and hex. Takes `Public/`, base58, hex as `lez_core` prints it, or a deployed program's name. | | `logs [-f] [--session \| --hub]` | Prints the sequencer's log, or a session's or the hub's daemon log, with its modules' output. | -| `session new [--module ]` | Makes a `logosctl` session with a funded devnet wallet, see below. | +| `logs --all` | Prints every log in turn: the sequencer's, each session's and the hub's, for a CI step after a failed test. | +| `session new [--module ]` | Makes a `logosctl` session with a funded devnet wallet, see below. `--module chat_module@0.3.0` installs that version. | | `session ls`, `session env `, `session rm ` | Lists sessions, prints one's env to `source`, deletes one. | -| `session restart ` | Restarts a session's daemon and loads its modules again, keeping its packages, keys and funded wallet: a fresh start for a module that keeps state while loaded, safer than `logosctl module reload`. Calls in flight fail, and modules an app loaded itself need loading again. | +| `session restart ...` | Restarts each session's daemon in turn and loads its modules again, keeping its packages, keys and funded wallet: a fresh start for a module that keeps state while loaded, safer than `logosctl module reload`. Calls in flight fail, and modules an app loaded itself need loading again. | | `accounts new --count [--amount ]` | Makes a group of funded accounts, see below. | | `accounts ls` | Lists account groups. | | `messaging rm` | Stops the messaging hub and deletes it, see below. | @@ -93,16 +94,16 @@ count = 100 amount = 5_000_000_000 # lepta each, 10B when left out [sessions.alice] # a logosctl session, as session new -modules = ["chat_module"] +modules = ["chat_module"] # or "chat_module@0.3.0" for that version [messaging] # a local messaging hub, see Messaging ``` -A program can come from a release instead of a path: `up` downloads its `url` once, with `curl`, into the home, and deploys it only if its SHA-256 is the `sha256` given (as `shasum -a 256` prints it). +A program can come from a release instead of a path: `up` downloads its `url` once, with `curl`, into `~/.logos-devnet/downloads`, which every home shares, and deploys it only if its SHA-256 is the `sha256` given (as `shasum -a 256` prints it). -`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. `up` checks the whole file before it touches the devnet. +`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. Modules come from the catalog at its latest version, `lez_core` at `0.5.1`, unless the file names one: `chat_module@0.3.0`. A session keeps the versions it was made with, so `up` refuses another version for an existing one: `session rm` it, and `up` makes it again. A pin on what it installed unpinned is checked against the version its daemon reports, and recorded when it matches. `up` checks the whole file before it touches the devnet. -Projects share one devnet, `~/.logos-devnet` on port 3040, unless the file sets `home`, e.g. `home = ".logos-devnet"`, for a devnet of the project's own. Give it `[devnet] port = 0` too: it takes a free port on the first `up` and keeps it, so it runs next to other devnets, and `logos-devnet env` shows it. With a fixed `port` in the file, `--port` applies for that run, and the next `up` goes back to the file's port. With `port = 0`, `--port` is remembered. On a shared devnet, a `[devnet]` section that disagrees with the running chain is refused rather than restarting the chain under the other projects: `down` and `up` apply it, or `reset` for `lez` and `dev_mode`, which only a new chain takes. A `reset` there funds every project's account groups again, and each project's next `up` deploys its programs on the new chain. +Projects share one devnet, `~/.logos-devnet` on port 3040, unless the file sets `home`, e.g. `home = ".logos-devnet"`, for a devnet of the project's own. Downloads stay shared. Give it `[devnet] port = 0` too: it takes a free port on the first `up` and keeps it, so it runs next to other devnets, and `logos-devnet env` shows it. With a fixed `port` in the file, `--port` applies for that run, and the next `up` goes back to the file's port. With `port = 0`, `--port` is remembered. On a shared devnet, a `[devnet]` section that disagrees with the running chain is refused rather than restarting the chain under the other projects: `down` and `up` apply it, or `reset` for `lez` and `dev_mode`, which only a new chain takes. A `reset` there funds every project's account groups again, and each project's next `up` deploys its programs on the new chain. ## Many accounts @@ -248,7 +249,7 @@ Everything is in `~/.logos-devnet` (or `LOGOS_DEVNET_HOME`): | `sessions/` | one directory per session: its `logosctl` home, its daemon's `HOME` with its storage, wallet and `session.json` | | `accounts/` | one directory per account group: its wallet and `accounts.json` | | `programs.json` | the binary hash each program was deployed from | -| `downloads/` | program binaries the project file names by URL, by SHA-256, and in `packages/` the module packages every daemon installs from, downloaded once and checked against the catalog's SHA-256 | +| `downloads/` | program binaries the project file names by URL, by SHA-256, and in `packages/` the module packages every daemon installs from, downloaded once and checked against the catalog's SHA-256. Every home uses the one in `~/.logos-devnet`, so a project's own home or a worktree's doesn't download them again. One left in another home from before v0.9.0 can be deleted | | `messaging/` | the hub, for `[messaging]` and `[storage]`: its `logosctl` home, its daemon's `HOME`, message store, ports and node keys in `hub.json` | | `lock` | held while a command changes the devnet, so two projects sharing the home take turns | @@ -260,7 +261,7 @@ With `--json`, a command prints one JSON document and nothing else on stdout. No | Command | Fields | | --- | --- | -| `up`, `reset`, `status` | `lez`, `runtime`, `sequencer` (`url`, `running`, `runtime_answered`, `block`, `max_txs_per_block`, `block_time`, `dev_mode`), `faucet` (`account`, `balance`), `programs`, `account_groups`, `sessions`, `messaging` (`running`, `delivery_node`, `discovery_node`, `delivery`, `discovery`, or `null` without a hub), `storage` (`running`, or `null` until a project asks for `[storage]`), `env_file` | +| `up`, `reset`, `status` | `lez`, `runtime`, `sequencer` (`url`, `running`, `runtime_answered`, `block`, `max_txs_per_block`, `block_time`, `dev_mode`), `faucet` (`account`, `balance`), `programs`, `account_groups`, `sessions`, `sessions_stopped` (sessions whose daemon stopped while the chain runs), `messaging` (`running`, `delivery_node`, `discovery_node`, `delivery`, `discovery`, or `null` without a hub), `storage` (`running`, or `null` until a project asks for `[storage]`), `env_file` | | `deploy` | `name`, `id`, `hex`, `var`, `deployed_now`, `updated` | | `fund` | `account`, `balance` | | `tx` | `hash`, `block` (or `null` while no block holds it) | @@ -278,12 +279,12 @@ 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.8.0 +- uses: drptbl/logos-devnet@v0.9.0 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 - if: failure() - run: logos-devnet logs # the sequencer's log, when a test fails + run: logos-devnet logs --all # the sequencer's, sessions' and hub's logs, when a test fails ``` Inputs: `version` (default: the release tag you use the action at, or, pinned to a commit, the release that commit's `Cargo.toml` names), `config`, `working-directory`, `args` (space-separated, without shell quoting. Set the home with `LOGOS_DEVNET_HOME`, not `--home`), `start: "false"` to only install, which also works on macOS runners, and `logosctl-version` (default `0.3.2`). When the project file has sessions, `[messaging]` or `[storage]` and no `logosctl` is on `PATH`, the action installs that release of the Logos Core CLI, checked against its SHA-256. Output: `sequencer`. When `up` itself fails, the action prints the sequencer's log, each session's and the hub's. Starting the devnet needs a Linux runner, for Docker. diff --git a/examples/github-actions/devnet.yml b/examples/github-actions/devnet.yml index 1f8c2da..350ee29 100644 --- a/examples/github-actions/devnet.yml +++ b/examples/github-actions/devnet.yml @@ -21,8 +21,8 @@ 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.8.0 + uses: drptbl/logos-devnet@v0.9.0 - run: cargo test - - name: The sequencer's log + - name: The devnet's logs if: failure() - run: logos-devnet logs + run: logos-devnet logs --all diff --git a/skills/logos-devnet/SKILL.md b/skills/logos-devnet/SKILL.md index 637247b..1a03c5e 100644 --- a/skills/logos-devnet/SKILL.md +++ b/skills/logos-devnet/SKILL.md @@ -9,7 +9,7 @@ description: logos-devnet runs a local LEZ (Logos Execution Zone) chain. Use whe ## Before you start -- **logos-devnet 0.8.0 or newer**: `logos-devnet --version`. Install it with `cargo install --locked logos-devnet`, or a binary from https://github.com/drptbl/logos-devnet/releases/latest (macOS and Linux). +- **logos-devnet 0.9.0 or newer**: `logos-devnet --version`. Install it with `cargo install --locked logos-devnet`, or a binary from https://github.com/drptbl/logos-devnet/releases/latest (macOS and Linux). - **Docker**: OrbStack, Docker Desktop or Colima, running. `logos-devnet doctor` says when it isn't. - **`logosctl`**, the Logos Core CLI, on `PATH`, only for sessions, `[messaging]` and `[storage]`: a release from https://github.com/logos-co/logos-logoscore-cli/releases. - **LEZ programs** you deploy are built with `cargo risczero build`, which makes the `.bin` the devnet takes. @@ -29,6 +29,7 @@ Pass `--json` to every command: on success stdout holds one JSON document, and n [accounts.users] count = 20 # funded at genesis, 10B lepta each [sessions.alice] # a logosctl session with a funded wallet + modules = ["chat_module@0.3.0"] # catalog modules, a version pinned so CI doesn't drift ``` Program, group and session names are lower-case letters, digits and `-`. A project-local home is state, not source: add `.logos-devnet/` to `.gitignore`. 2. `logos-devnet doctor --json`, from the project's directory so it checks the file's settings: Docker, the ports, the chain, `logosctl`, and that each `[programs]` file is a built program. Done when `.ok` is true. Each failed check carries a `detail`, and a `fix` when the detail doesn't already say what to do. @@ -41,7 +42,7 @@ Pass `--json` to every command: on success stdout holds one JSON document, and n - `LOGOS_DEVNET_SESSION_`: a session's `LOGOSCTL_CONFIG_DIR`, with `_WALLET`, `_ACCOUNT` (`Public/`) and `_ACCOUNT_HEX` (what `lez_core` takes), for a test driving several sessions. - `RISC0_DEV_MODE`: `1` or `0`, matching the chain. - With `[messaging]`: `LOGOS_DEVNET_DELIVERY_CONFIG`, the `delivery_module.createNode` config of a node that uses the local hub, `LOGOS_DEVNET_DELIVERY_ENTRY_NODE`, `LOGOS_DEVNET_DISCOVERY_BOOTSTRAP`, a `libp2p_module` bootstrap node, and `LOGOS_DEVNET_DISCOVERY_CONFIG`, its node's config. -5. `logos-devnet status --json` shows what runs: chain head, faucet, programs, groups, sessions, the hub and storage. `.sequencer.runtime_answered` is false when Docker didn't answer within 10 s: Docker is stuck, so restart it rather than running `up`. +5. `logos-devnet status --json` shows what runs: chain head, faucet, programs, groups, sessions, the hub and storage. `.sessions_stopped` names sessions whose daemon stopped while the chain runs: `up` starts them again. When something fails, `logos-devnet logs --all` prints the sequencer's, every session's and the hub's log. `.sequencer.runtime_answered` is false when Docker didn't answer within 10 s: Docker is stuck, so restart it rather than running `up`. 6. Check the chain instead of sleeping: - `logos-devnet tx --wait ` returns once a block holds the transaction (`lez_core`'s `tx_hash`), with the block in `--json`'s `.block`, and fails after `--timeout` (60 s). - `logos-devnet account ` shows an account's balance, nonce and data. It takes `Public/`, base58, the 64-hex form `lez_core` uses, or a deployed program's name, and prints both forms. @@ -57,7 +58,7 @@ Pass `--json` to every command: on success stdout holds one JSON document, and n - **Messaging.** An empty `[messaging]` table runs a local hub: a delivery node and a discovery bootstrap on `127.0.0.1`, so messages and service lookups skip the public fleet. Sessions with `delivery_module` or `libp2p_module` loaded (`chat_module` loads the first) get nodes on the hub from `up`; outside a session, create the app's nodes from `LOGOS_DEVNET_DELIVERY_CONFIG` and `LOGOS_DEVNET_DISCOVERY_CONFIG` first in its daemon: the first `createNode` picks the network. `chat_module` still reaches a public key registry. `status --json` shows whether each hub node runs, in `.messaging.delivery_node` and `.messaging.discovery_node`, and `messaging rm` deletes the hub: a project that asks for one gets a new hub, with new addresses, on its next `up`. - **Storage.** Each session runs a storage node of its own, on `127.0.0.1` and in no network. An empty `[storage]` table connects the sessions through a node in the hub, so one session downloads by CID what another uploaded. Sessions need nothing passed in. - **Calling the modules.** To send or receive messages, advertise or look up a service, or upload and download a file from a session, read [modules.md](modules.md): `delivery_module`, `libp2p_module` and `storage_module` take arguments in an order and form their errors don't explain. -- **Sessions** need `logosctl` on `PATH`. `logos-devnet session restart ` gives one a fresh daemon in seconds, keeping its wallet: use it where a module keeps state while loaded (libp2p_module 1.1.0 advertises one service per load) instead of `logosctl module reload`. They suit apps that talk to Logos through `logosctl` and `lez_core`. Before calling `lez_core` yourself, read [lez_core.md](lez_core.md): it takes ids and amounts in forms its errors don't explain. +- **Sessions** need `logosctl` on `PATH`. `logos-devnet session restart ...` gives each a fresh daemon in seconds, keeping its wallet: use it where a module keeps state while loaded (libp2p_module 1.1.0 advertises one service per load) instead of `logosctl module reload`. They suit apps that talk to Logos through `logosctl` and `lez_core`. Before calling `lez_core` yourself, read [lez_core.md](lez_core.md): it takes ids and amounts in forms its errors don't explain. ## Reset @@ -78,6 +79,7 @@ Each refusal changes nothing. `up` prefixes a program's refusal with `program on 127.0.0.1 is taken` | `up --port `, remembered unless the file sets a fixed `port`. A new project home with `[devnet] port = 0` takes a free one on its first `up`. | | `sessions and the messaging hub need logosctl` | Install the Logos Core CLI, or remove the sessions and `[messaging]`. | | `port on 127.0.0.1, which the messaging hub keeps, is taken` | Stop what holds it, or `messaging rm` and `up` for new ports and peer ids. | +| `the session has , not ` | A session keeps the versions it was made with: `session rm `, then `up` makes it again. | | `not a RISC Zero program binary` | Deploy the guest's `.bin` from `cargo risczero build`, not its ELF. | | `no Docker daemon answers` | Start Docker (OrbStack, Docker Desktop or Colima). | | `no block within` / `the sequencer stopped while starting` | Read `logos-devnet logs`. | diff --git a/src/devnet.rs b/src/devnet.rs index ce7f829..cafa35b 100644 --- a/src/devnet.rs +++ b/src/devnet.rs @@ -747,21 +747,50 @@ impl Devnet { funded } - /// Restarts a session's daemon and brings it back as `up` does: a fresh start for modules - /// that keep state while loaded, e.g. `libp2p_module`, which advertises one service per load. - /// Its packages, keys and funded wallet stay. - pub fn session_restart(&self, name: &str) -> Result { - let session = self.existing_session(name)?; + /// Restarts each of `names`' daemons, in order, and brings it back as `up` does: a fresh + /// start for modules that keep state while loaded, e.g. `libp2p_module`, which advertises one + /// service per load. Their packages, keys and funded wallets stay. Every name is checked + /// first, so a typo restarts none. + pub fn session_restart(&self, names: &[String]) -> Result { + let sessions = names + .iter() + .map(|name| self.existing_session(name)) + .collect::>>()?; self.require_running()?; - // A session that can't come back stays as it is. - session.info()?; - session.logosctl().stop()?; - self.resume_session(&session, false)?; - Ok(Done { - message: format!( - "Restarted session {name}: its modules are loaded and its wallet open." + for session in &sessions { + // A session that can't come back stays as it is. + session.info()?; + session.logosctl().stop()?; + self.resume_session(session, false) + .with_context(|| format!("restarting session {}", session.name))?; + } + let message = match names { + [name] => { + format!("Restarted session {name}: its modules are loaded and its wallet open.") + } + names => format!( + "Restarted sessions {}: their modules are loaded and their wallets open.", + names.join(", ") ), - }) + }; + Ok(Done { message }) + } + + /// The sessions whose daemon stopped while the chain runs, which `up` starts again. After + /// `down` every daemon is stopped, and without logosctl none can be asked: neither is news. + pub fn stopped_sessions(&self, chain_running: bool) -> Vec { + if !chain_running || !session::logosctl_on_path() { + return Vec::new(); + } + self.sessions_not_running() + } + + fn sessions_not_running(&self) -> Vec { + self.sessions() + .into_iter() + .filter(|s| !s.logosctl().running()) + .map(|s| s.name) + .collect() } /// The sessions, or none (with a note) when their directory can't be read. @@ -948,6 +977,7 @@ impl Devnet { programs, account_groups: self.group_summaries().unwrap_or_default(), sessions: self.sessions().into_iter().map(|s| s.name).collect(), + sessions_stopped: self.stopped_sessions(running), messaging: self.hub_status(), storage: self.storage_status(), env_file: env.map(|_| self.home.env_file()), @@ -1074,11 +1104,16 @@ impl Devnet { /// the ones added. fn add_session_modules(&self, session: &Session, extra: &[String]) -> Result> { let mut info = session.info()?; - let missing = session::missing_modules(&info.modules, extra)?; + let ctl = session.logosctl(); + let had = info.modules.clone(); + let missing = + session::missing_modules(&mut info.modules, extra, |m| ctl.installed_version(m))?; + if info.modules != had { + session.save_info(&info)?; + } if missing.is_empty() { return Ok(missing); } - let ctl = session.logosctl(); if session.start_daemon(&ctl, self.settings.dev_mode, &self.session_storage())? { // A daemon that started now has nothing loaded: bring the session back first. ctl.resume( @@ -1452,30 +1487,47 @@ impl Devnet { pub fn logs(&self, follow: bool, session: Option<&str>, hub: bool) -> Result<()> { let daemon = match session { Some(name) => self.existing_session(name)?.logosctl_dir(), - None if hub => { - if !self.home.messaging_dir().exists() { - bail!( - "this devnet has no hub: a project's [messaging] or [storage] starts one" - ); - } - self.home.messaging_dir().join("logosctl") - } + None if hub => self.hub_logosctl_dir().context( + "this devnet has no hub: a project's [messaging] or [storage] starts one", + )?, None => return self.runtime.logs(follow), }; - let log = daemon.join("logs").join("daemon.log"); - if !log.exists() { - bail!( - "{} doesn't exist yet: the daemon hasn't started", - log.display() - ); + tail(&daemon_log(&daemon), follow) + } + + /// Prints the last lines of every log in turn, each under a `==> <==` line: the + /// sequencer's, each session's and the hub's, for a CI step that runs when a test fails. A + /// log that can't be shown says why and the next one follows. + pub fn logs_all(&self) -> Result<()> { + println!("==> sequencer <=="); + if let Err(e) = self.runtime.logs(false) { + println!("{e:#}"); } - let mut cmd = std::process::Command::new("tail"); - cmd.args(["-n", "200"]); - if follow { - // By name, so it keeps following after a daemon restart starts a new log. - cmd.arg("-F"); + for (label, log) in self.daemon_logs() { + println!("\n==> {label} <=="); + if let Err(e) = tail(&log, false) { + println!("{e:#}"); + } } - crate::runtime::run_attached(cmd.arg(&log)) + Ok(()) + } + + /// Each logosctl daemon's log, sessions first, then the hub's when there is one. + fn daemon_logs(&self) -> Vec<(String, PathBuf)> { + let sessions = self + .sessions() + .into_iter() + .map(|s| (format!("session {}", s.name), daemon_log(&s.logosctl_dir()))); + let hub = self + .hub_logosctl_dir() + .map(|dir| ("hub".to_owned(), daemon_log(&dir))); + sessions.chain(hub).collect() + } + + /// The hub's logosctl config directory, when the devnet has a hub. + fn hub_logosctl_dir(&self) -> Option { + let hub = self.home.messaging_dir(); + hub.exists().then(|| hub.join("logosctl")) } /// Writes `/wallet_config.json` for a project's own wallet (`lez_core` or the LEZ @@ -1751,6 +1803,28 @@ fn labelled(list: &str, label: &str) -> Option { .find_map(first_public_id) } +/// A logosctl daemon's log, in its config directory. +fn daemon_log(logosctl_dir: &Path) -> PathBuf { + logosctl_dir.join("logs").join("daemon.log") +} + +/// Prints `log`'s last 200 lines, and follows it with `follow`. +fn tail(log: &Path, follow: bool) -> Result<()> { + if !log.exists() { + bail!( + "{} doesn't exist yet: the daemon hasn't started", + log.display() + ); + } + let mut cmd = std::process::Command::new("tail"); + cmd.args(["-n", "200"]); + if follow { + // By name, so it keeps following after a daemon restart starts a new log. + cmd.arg("-F"); + } + crate::runtime::run_attached(cmd.arg(log)) +} + #[cfg(test)] mod tests { use super::*; @@ -1810,11 +1884,16 @@ mod tests { fn restarts_only_a_session_on_a_running_devnet() { let dir = tempfile::tempdir().unwrap(); let devnet = devnet_in(&dir.path().join("home")); - let err = devnet.session_restart("nobody").unwrap_err(); + let err = devnet.session_restart(&["nobody".into()]).unwrap_err(); assert!(err.to_string().contains("no session nobody"), "{err}"); std::fs::create_dir_all(devnet.home.sessions_dir().join("alice")).unwrap(); - let err = devnet.session_restart("alice").unwrap_err(); + let err = devnet.session_restart(&["alice".into()]).unwrap_err(); assert!(err.to_string().contains("not running"), "{err}"); + // Every name is checked before any session restarts. + let err = devnet + .session_restart(&["alice".into(), "nobody".into()]) + .unwrap_err(); + assert!(err.to_string().contains("no session nobody"), "{err}"); } #[test] @@ -1885,6 +1964,37 @@ mod tests { assert!(started.elapsed() < Duration::from_secs(5)); } + #[test] + fn names_sessions_whose_daemon_is_stopped() { + let dir = tempfile::tempdir().unwrap(); + let devnet = devnet_in(&dir.path().join("home")); + assert!(devnet.sessions_not_running().is_empty()); + for name in ["bob", "alice"] { + std::fs::create_dir_all(devnet.home.sessions_dir().join(name)).unwrap(); + } + assert_eq!(devnet.sessions_not_running(), ["alice", "bob"]); + // After `down`, a stopped daemon is no news. + assert!(devnet.stopped_sessions(false).is_empty()); + } + + #[test] + fn all_logs_cover_every_session_and_the_hub() { + let dir = tempfile::tempdir().unwrap(); + let devnet = devnet_in(&dir.path().join("home")); + assert!(devnet.daemon_logs().is_empty()); + for name in ["bob", "alice"] { + std::fs::create_dir_all(devnet.home.sessions_dir().join(name)).unwrap(); + } + std::fs::create_dir_all(devnet.home.messaging_dir()).unwrap(); + let logs = devnet.daemon_logs(); + let labels: Vec<&str> = logs.iter().map(|(label, _)| label.as_str()).collect(); + assert_eq!(labels, ["session alice", "session bob", "hub"]); + assert_eq!( + logs[2].1, + devnet.home.messaging_dir().join("logosctl/logs/daemon.log") + ); + } + #[test] fn logs_name_what_they_cant_show() { let dir = tempfile::tempdir().unwrap(); @@ -2254,6 +2364,7 @@ mod tests { programs: vec![], account_groups: vec![], sessions: vec![], + sessions_stopped: vec![], messaging: None, storage: None, env_file: None, diff --git a/src/doctor.rs b/src/doctor.rs index d82dd02..12fc207 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -133,6 +133,15 @@ pub fn run(devnet: &Devnet, project_error: Option<&anyhow::Error>) -> Doctor { ) }); + let stopped = devnet.stopped_sessions(running); + if !stopped.is_empty() { + checks.push(fail( + "sessions", + format!("{} stopped while the chain runs", stopped.join(", ")), + "`logos-devnet up` starts them", + )); + } + if running { checks.push(match devnet.faucet_balance() { Some(b) if b > 0 => pass("faucet", format!("{b} lepta")), diff --git a/src/fetch.rs b/src/fetch.rs index e2d6d1b..1cc5bbf 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -1,5 +1,5 @@ //! Program binaries the project file names by URL, e.g. a program's GitHub release: downloaded -//! once into the home with `curl`, and kept only when their SHA-256 is the one the file names. +//! once with `curl`, and kept only when their SHA-256 is the one the file names. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -30,14 +30,15 @@ pub fn check_url(url: &str) -> Result<()> { } /// The file at `url` whose SHA-256 is `sha256`, kept in `dir`: downloaded the first time, and -/// from then on read from `dir`. +/// 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. pub fn cached(dir: &Path, url: &str, sha256: &str) -> Result { let path = dir.join(format!("{sha256}.bin")); if std::fs::read(&path).is_ok_and(|bytes| sha256_hex(&bytes) == sha256) { return Ok(path); } std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; - let part = dir.join(format!("{sha256}.part")); + let part = dir.join(format!("{sha256}.part-{}", std::process::id())); eprintln!("Downloading {url}..."); let status = Command::new("curl") .args([ @@ -149,6 +150,19 @@ pub(crate) mod tests { assert_eq!(std::fs::read(path).unwrap(), body); } + #[test] + fn leaves_another_process_download_alone() { + // Homes share one download directory, so another `up` may be downloading the same file. + let dir = tempfile::tempdir().unwrap(); + let body: &[u8] = b"a program"; + let sha = sha256_hex(body); + let theirs = dir.path().join(format!("{sha}.part")); + 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 takes_a_sha256_as_shasum_prints_it() { assert!(check_sha256(&sha256_hex(b"x")).is_ok()); diff --git a/src/home.rs b/src/home.rs index 1a67fe0..753b6ac 100644 --- a/src/home.rs +++ b/src/home.rs @@ -11,7 +11,8 @@ //! sessions/ throwaway logosctl sessions with devnet wallets (see session) //! accounts/ account groups: many funded keys for tests (see groups) //! programs.json the binary hash each program was deployed from -//! downloads/ program binaries the project file names by URL, and module packages +//! downloads/ program binaries the project file names by URL, and module packages. Every +//! home uses the one in `~/.logos-devnet` (see `with_shared_downloads`) //! messaging/ the local messaging hub, when a project asks for one (see messaging) //! lock held by the command changing the home, so two take turns //! ``` @@ -127,6 +128,7 @@ impl Settings { #[derive(Debug, Clone)] pub struct Home { root: PathBuf, + downloads: PathBuf, } impl Home { @@ -139,7 +141,24 @@ impl Home { Some(path) => resolve(&path)?, None => default_root()?, }; - Ok(Self { root }) + let downloads = root.join("downloads"); + Ok(Self { root, downloads }) + } + + /// This home, downloading into `~/.logos-devnet/downloads` like every other home, so a + /// project's own home or a worktree's doesn't download the same files again. Each file is + /// checked against its SHA-256 before use, whichever home put it there. Without `HOME`, or + /// when that directory can't be made, the home keeps its own. + pub fn with_shared_downloads(self) -> Self { + let shared = default_root().map(|root| root.join("downloads")); + match shared { + Ok(dir) if std::fs::create_dir_all(&dir).is_ok() => self.with_downloads(dir), + _ => self, + } + } + + fn with_downloads(self, downloads: PathBuf) -> Self { + Self { downloads, ..self } } pub fn root(&self) -> &Path { @@ -223,10 +242,10 @@ impl Home { } /// Program binaries downloaded from a URL, named by their SHA-256. pub fn downloads_dir(&self) -> PathBuf { - self.root.join("downloads") + self.downloads.clone() } /// Module packages from the catalog, `-.lgx`, downloaded once for every - /// daemon of the devnet. + /// daemon. pub fn packages_dir(&self) -> PathBuf { self.downloads_dir().join("packages") } @@ -386,6 +405,17 @@ mod tests { assert!(!home.chain_dev_mode()); } + #[test] + fn homes_can_share_one_download_directory() { + let dir = tempfile::tempdir().unwrap(); + let home = Home::locate(Some(dir.path().join("a"))).unwrap(); + assert_eq!(home.downloads_dir(), home.root().join("downloads")); + let shared = dir.path().join("shared"); + let home = home.with_downloads(shared.clone()); + assert_eq!(home.downloads_dir(), shared); + assert_eq!(home.packages_dir(), shared.join("packages")); + } + #[test] fn one_command_at_a_time_holds_the_home() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/main.rs b/src/main.rs index c4a91f3..79217e2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -111,10 +111,13 @@ enum Command { /// Show an account: balance, nonce and data, its id in base58 and hex. Takes /// `Public/`, base58, hex or a deployed program's name. Account { account: String }, - /// Print the sequencer's log, or a session's or the hub's. + /// Print the sequencer's log, or a session's or the hub's, or all of them. Logs { - #[arg(short, long)] + #[arg(short, long, conflicts_with = "all")] follow: bool, + /// Every log in turn: the sequencer's, each session's and the hub's. + #[arg(long, conflicts_with_all = ["session", "hub"])] + all: bool, /// A session's logosctl daemon log, with its modules' output. #[arg(long, conflicts_with = "hub")] session: Option, @@ -157,7 +160,8 @@ enum SessionCommand { /// Make a session: its own logosctl daemon with lez_core and a funded devnet wallet. New { name: String, - /// Another module to install from the catalog, e.g. `chat_module`. Repeatable. + /// Another module to install from the catalog, e.g. `chat_module`, or + /// `chat_module@0.3.0` for that version. Repeatable. #[arg(long = "module")] modules: Vec, /// Lepta to fund the session's account with. @@ -170,9 +174,12 @@ enum SessionCommand { Env { name: String }, /// Stop a session's daemon and delete it, wallet and all. Rm { name: String }, - /// Restart a session's daemon and load its modules again, wallet and keys kept: a fresh + /// Restart sessions' daemons and load their modules again, wallets and keys kept: a fresh /// start for modules that keep state while loaded. - Restart { name: String }, + Restart { + #[arg(required = true)] + names: Vec, + }, } impl Command { @@ -215,7 +222,7 @@ fn main() -> Result<()> { let home = cli .home .or_else(|| project.as_ref().and_then(|p| p.home.clone())); - let home = Home::locate(home)?; + let home = Home::locate(home)?.with_shared_downloads(); let _lock = cli .command .changes_devnet() @@ -263,10 +270,12 @@ fn main() -> Result<()> { json, ), Command::Account { account } => emit(&devnet.account(&account)?, json), + Command::Logs { all: true, .. } => devnet.logs_all(), Command::Logs { follow, session, hub, + .. } => devnet.logs(follow, session.as_deref(), hub), Command::Session(command) => match command { SessionCommand::New { @@ -277,7 +286,7 @@ fn main() -> Result<()> { SessionCommand::Ls => emit(&devnet.session_list()?, json), SessionCommand::Env { name } => emit(&devnet.session_env(&name)?, json), SessionCommand::Rm { name } => emit(&devnet.session_rm(&name)?, json), - SessionCommand::Restart { name } => emit(&devnet.session_restart(&name)?, json), + SessionCommand::Restart { names } => emit(&devnet.session_restart(&names)?, json), }, Command::Messaging(MessagingCommand::Rm) => emit(&devnet.messaging_rm()?, json), } diff --git a/src/project.rs b/src/project.rs index c318a8b..706eb0d 100644 --- a/src/project.rs +++ b/src/project.rs @@ -17,7 +17,7 @@ //! amount = 10_000_000_000 //! //! [sessions.alice] # a logosctl session, as `session new` -//! modules = ["chat_module"] +//! modules = ["chat_module"] # or "chat_module@0.3.0" for that version //! ``` use std::collections::BTreeMap; diff --git a/src/report.rs b/src/report.rs index ff35ae4..6609653 100644 --- a/src/report.rs +++ b/src/report.rs @@ -31,6 +31,8 @@ pub struct Status { pub programs: Vec, pub account_groups: Vec, pub sessions: Vec, + /// Sessions whose daemon is stopped while the chain runs: `up` starts them again. + pub sessions_stopped: Vec, /// The local messaging hub, when the devnet has one. pub messaging: Option, /// The hub's storage node, when a project asked for local storage. @@ -226,6 +228,14 @@ impl Report for Status { if !self.sessions.is_empty() { out += &format!("sessions {}\n", self.sessions.join(", ")); } + if !self.sessions_stopped.is_empty() { + let one = self.sessions_stopped.len() == 1; + out += &format!( + " {} stopped. `logos-devnet up` starts {}\n", + self.sessions_stopped.join(", "), + if one { "it" } else { "them" }, + ); + } if let Some(m) = &self.messaging { let down: Vec<&str> = [ (m.delivery_node, "delivery"), @@ -408,7 +418,8 @@ mod tests { faucet: None, programs: vec![], account_groups: vec![], - sessions: vec![], + sessions: vec!["alice".into(), "bob".into()], + sessions_stopped: vec!["bob".into()], messaging: Some(Messaging { running: true, delivery_node: true, @@ -430,6 +441,7 @@ mod tests { "programs", "account_groups", "sessions", + "sessions_stopped", "messaging", "env_file", ] { @@ -452,6 +464,13 @@ mod tests { status.human() ); assert_eq!(json["messaging"]["discovery_node"], false); + assert!( + status.human().contains( + "sessions alice, bob\n bob stopped. `logos-devnet up` starts it\n" + ), + "{}", + status.human() + ); } #[test] @@ -472,6 +491,7 @@ mod tests { programs: vec![], account_groups: vec![], sessions: vec![], + sessions_stopped: vec![], messaging: None, storage: None, env_file: None, diff --git a/src/session.rs b/src/session.rs index ce7d5d8..9b03dc0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -178,29 +178,97 @@ pub fn list(dir: &Path) -> Result> { } /// The modules `extra` adds (as `modules_with` takes them) that a session with `have` lacks, in -/// order. A module left out of `extra` is not removed. -pub fn missing_modules(have: &[String], extra: &[String]) -> Result> { - Ok(modules_with(extra)? - .into_iter() - .filter(|module| !have.contains(module)) - .collect()) +/// order. A module left out of `extra` is not removed. A session keeps the version it +/// installed: asking for another one is refused, since only a new session takes it. A pin on a +/// module the session installed unpinned is checked against `installed`, the version its daemon +/// reports, and recorded in `have` when it matches. +pub fn missing_modules( + have: &mut [String], + extra: &[String], + installed: impl Fn(&str) -> Result>, +) -> Result> { + let wanted = modules_with(extra)?; + let mut missing = Vec::new(); + let mut pinned = Vec::new(); + for module in wanted { + let (name, Some(version)) = split_module(&module) else { + if !have.iter().any(|h| split_module(h).0 == module) { + missing.push(module); + } + continue; + }; + let Some(at) = have.iter().position(|h| split_module(h).0 == name) else { + missing.push(module); + continue; + }; + let had = match pinned_version(&have[at]) { + Some(had) => had.to_owned(), + None => installed(name)?.unwrap_or_default(), + }; + if had != version { + bail!( + "the session has {name} {had}, not {version}: `logos-devnet session rm` it, and \ + `up` makes it again with {module}" + ); + } + pinned.push((at, module.clone())); + } + // Recorded only once every pin checks out, so a refusal changes nothing. + for (at, module) in pinned { + have[at] = module; + } + Ok(missing) } -/// The modules a session installs: `lez_core`, then the extras in order, without repeats. +/// The modules a session installs: `lez_core`, then the extras in order, one per name. A +/// version given for a name replaces the one before. pub fn modules_with(extra: &[String]) -> Result> { let mut modules = vec![LEZ_CORE.to_owned()]; for module in extra { check_module(module)?; - if !modules.contains(module) { - modules.push(module.clone()); + let (name, version) = split_module(module); + match modules.iter().position(|m| split_module(m).0 == name) { + Some(i) if version.is_some() => modules[i] = module.clone(), + Some(_) => {} + None => modules.push(module.clone()), } } Ok(modules) } -/// A catalog module name: letters, digits, `_` and `-`, starting with a letter or digit, so a -/// name can't reach logosctl as a flag. -fn check_module(name: &str) -> Result<()> { +/// A module as a session lists it, `name` or `name@version`: its name and the version asked for. +fn split_module(module: &str) -> (&str, Option<&str>) { + match module.split_once('@') { + Some((name, version)) => (name, Some(version)), + None => (module, None), + } +} + +/// The version `install` takes for `module`: the one it names, else `lez_core`'s pin, else the +/// catalog's latest (`None`). +fn pinned_version(module: &str) -> Option<&str> { + match split_module(module) { + (_, Some(version)) => Some(version), + (LEZ_CORE, None) => Some(LEZ_CORE_VERSION), + _ => None, + } +} + +/// A catalog module, `name` or `name@version`, with a version a package version, so neither +/// can reach logosctl as a flag. +fn check_module(module: &str) -> Result<()> { + let (name, version) = split_module(module); + check_module_name(name)?; + if let Some(version) = version + && !version_ok(version) + { + bail!("not a package version: {module:?}, e.g. chat_module@0.3.0"); + } + Ok(()) +} + +/// A catalog module name: letters, digits, `_` and `-`, starting with a letter or digit. +fn check_module_name(name: &str) -> Result<()> { let ok = name .chars() .next() @@ -349,7 +417,8 @@ impl Logosctl { } /// Installs `modules` from the catalog, unsigned ones included (`lez_core` is unsigned). - /// `lez_core` is pinned to `LEZ_CORE_VERSION`, the others are the catalog's latest. Each + /// Each at the version it names (`name@version`), else `lez_core` at `LEZ_CORE_VERSION` and + /// the others at the catalog's latest. Each /// package a module needs, dependencies included, is downloaded once into `packages` and /// installed from there, so the next daemon that needs it doesn't download it again. pub fn install(&self, modules: &[String], packages: &Path) -> Result<()> { @@ -365,9 +434,9 @@ impl Logosctl { /// Installs what `package install ` would, package by package, from `packages`. fn install_one(&self, module: &str, packages: &Path) -> Result<()> { - let mut plan = vec!["package", "install", module]; - if module == LEZ_CORE { - plan.extend(["--version", LEZ_CORE_VERSION]); + let mut plan = vec!["package", "install", split_module(module).0]; + if let Some(version) = pinned_version(module) { + plan.extend(["--version", version]); } plan.push("--dry-run"); let plan = self.run(&plan)?; @@ -380,7 +449,7 @@ impl Logosctl { else { continue; }; - check_module(name)?; + check_module_name(name)?; check_version(version)?; let file = self.cached_package(name, version, packages)?; self.run(&["package", "install", &path_text(&file), "--yes"])?; @@ -439,6 +508,18 @@ impl Logosctl { .map(str::to_ascii_lowercase)) } + /// The version of `module` installed in the daemon, if it is. + pub fn installed_version(&self, module: &str) -> Result> { + let listed = self.run(&["package", "ls"])?; + Ok(listed + .as_array() + .into_iter() + .flatten() + .find(|m| m["name"] == module) + .and_then(|m| m["version"].as_str()) + .map(str::to_owned)) + } + /// The modules loaded in the daemon, declared or loaded for another one. pub fn loaded_modules(&self) -> Result> { let listed = self.run(&["module", "ls"])?; @@ -456,7 +537,8 @@ impl Logosctl { /// Loads the `modules` that aren't loaded yet. pub fn load(&self, modules: &[String]) -> Result<()> { let listed = self.run(&["module", "ls"])?; - for module in modules.iter().filter(|m| !module_loaded(&listed, m)) { + let names = modules.iter().map(|m| split_module(m).0); + for module in names.filter(|m| !module_loaded(&listed, m)) { self.run(&["module", "load", module]) .with_context(|| format!("loading {module}"))?; } @@ -561,17 +643,20 @@ fn install_hint(e: anyhow::Error) -> anyhow::Error { /// A package version as the catalog gives it, e.g. `0.5.1`: it reaches logosctl's argv and a /// file name, so never a flag or a path. fn check_version(version: &str) -> Result<()> { - let ok = version + if !version_ok(version) { + bail!("the catalog gave an odd version: {version}"); + } + Ok(()) +} + +fn version_ok(version: &str) -> bool { + version .chars() .next() .is_some_and(|c| c.is_ascii_alphanumeric()) && version .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')); - if !ok { - bail!("the catalog gave an odd version: {version}"); - } - Ok(()) + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')) } /// `logosctl call`'s arguments, each of `args` as a string. @@ -733,20 +818,79 @@ esac"#, ) } + /// `missing_modules` on a copy of `have`, with `installed` as what the daemon reports: + /// the modules missing, or the error, and `have` afterwards. + fn reconcile( + have: &[&str], + extra: &[&str], + installed: Option<&str>, + ) -> (Result>, Vec) { + let mut have: Vec = have.iter().map(|m| (*m).to_owned()).collect(); + let extra: Vec = extra.iter().map(|m| (*m).to_owned()).collect(); + let missing = missing_modules(&mut have, &extra, |_| Ok(installed.map(str::to_owned))); + (missing, have) + } + #[test] fn finds_the_modules_a_session_lacks() { - let have = ["lez_core".to_owned(), "chat_module".to_owned()]; - let wanted = |extra: &[&str]| { - let extra: Vec = extra.iter().map(|m| (*m).to_owned()).collect(); - missing_modules(&have, &extra).unwrap() - }; + let have = ["lez_core", "chat_module"]; + let wanted = |extra: &[&str]| reconcile(&have, extra, None).0.unwrap(); assert!(wanted(&["chat_module"]).is_empty()); assert_eq!( wanted(&["chat_module", "storage_module"]), ["storage_module"] ); assert!(wanted(&[]).is_empty(), "a module left out stays installed"); - assert!(missing_modules(&have, &["Bad Name".to_owned()]).is_err()); + assert!(reconcile(&have, &["Bad Name"], None).0.is_err()); + assert_eq!(wanted(&["storage_module@1.0.0"]), ["storage_module@1.0.0"]); + } + + #[test] + fn a_session_keeps_the_version_it_installed() { + let have = ["lez_core", "chat_module@0.3.0"]; + let missing = |extra: &str| reconcile(&have, &[extra], None).0; + assert!(missing("chat_module@0.3.0").unwrap().is_empty()); + assert!(missing("chat_module").unwrap().is_empty()); + assert!( + missing("lez_core@0.5.1").unwrap().is_empty(), + "lez_core's pin" + ); + // Another version would need the session made again: say so, rather than ignore it. + let err = missing("chat_module@0.4.0").unwrap_err(); + assert!(format!("{err:#}").contains("session rm"), "{err:#}"); + } + + #[test] + fn a_pin_on_what_a_session_installed_unpinned_asks_the_daemon() { + let have = ["lez_core", "chat_module"]; + // The version it installed then: the pin is recorded, nothing installs. + let (missing, after) = reconcile(&have, &["chat_module@0.3.0"], Some("0.3.0")); + assert!(missing.unwrap().is_empty()); + assert_eq!(after, ["lez_core", "chat_module@0.3.0"]); + // Another one: refused, and nothing recorded. + let (missing, after) = reconcile(&have, &["chat_module@0.4.0"], Some("0.3.0")); + let err = missing.unwrap_err(); + assert!( + format!("{err:#}").contains("has chat_module 0.3.0"), + "{err:#}" + ); + assert_eq!(after, have); + } + + #[test] + fn reads_a_module_version_from_the_daemon() { + let dir = tempfile::tempdir().unwrap(); + let ctl = fake_logosctl( + dir.path(), + r#"case "$2 $3" in + "package ls") echo '[{"name":"lez_core","version":"0.5.1"},{"name":"chat_module","version":"0.3.0"}]' ;; +esac"#, + ); + assert_eq!( + ctl.installed_version("chat_module").unwrap().as_deref(), + Some("0.3.0") + ); + assert_eq!(ctl.installed_version("storage_module").unwrap(), None); } #[test] @@ -1011,6 +1155,35 @@ esac"#, assert!(modules_with(&["--yes".into()]).is_err(), "never a flag"); } + #[test] + fn takes_a_module_at_a_version() { + let modules = modules_with(&["chat_module@0.2.0".into(), "lez_core@0.5.2".into()]).unwrap(); + assert_eq!(modules, ["lez_core@0.5.2", "chat_module@0.2.0"]); + for bad in [ + "chat_module@", + "chat_module@--yes", + "@0.2.0", + "chat_module@0.2/0", + ] { + assert!(modules_with(&[bad.into()]).is_err(), "{bad}"); + } + } + + #[test] + fn installs_a_module_at_its_version_and_loads_it_by_name() { + let dir = tempfile::tempdir().unwrap(); + let ctl = package_manager(dir.path(), None); + ctl.install(&["chat_module@0.3.0".into()], &dir.path().join("packages")) + .unwrap(); + ctl.load(&["chat_module@0.3.0".into()]).unwrap(); + let log = calls(dir.path()); + assert!( + log.contains("--json package install chat_module --version 0.3.0 --dry-run\n"), + "{log}" + ); + assert!(log.contains("module load chat_module\n"), "{log}"); + } + /// A logosctl whose catalog plans `lez_core` alone and `chat_module` with /// `delivery_module`, lists each package's SHA-256 as that of `-`, and /// whose downloads write `download` into the package file, by default what the catalog