From e4af08ffc038d95ae33c5748ceb685cbdd2485cc Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 00:04:24 -0600 Subject: [PATCH] id: extract id-cli crate; facade becomes re-exports + main.rs (split step 7b, #4411) Move the application layer out of the facade: cli, commands, repl and server_config, plus the support modules only they use - local, meta_client, protocol, helpers, chat_presence, app_manifest, match_audit, peer_announcement, aliases, publications and publications_runtime - into crates/id-cli. The facade fileops test modules move too (they exercise id_sync::fileops through the LocalNode harness in local.rs); the facade fileops module is now the pure re-export. tests/aliases.rs narrows to id-cli/tests, naming the origin crates directly (id_cli, id_store, id_events, id_core). The facade keeps main.rs and re-exports every moved module at its historical id:: path, plus the root convenience layer (id::Cli, id::cmd_*, id::open_store, ...) re-pointed at id_cli. Root helpers the commands relied on moved into id-cli lib.rs (parse_stdin_items, read_input, export_blob, to_absolute); the facade re-exports them at id:: too. id-cli mirrors the facade feature gates the moved code uses (sandbox, world, ssh, web, dht) and carries its own axum under web; the facade no longer links axum directly. Relative-path casualties of the move are repaired: include_bytes! paths for the tic-tac-toe wasm and the roc-counter example, CARGO_MANIFEST_DIR joins for the README command-table tests and the checked-in app manifest, doctests now name id_cli. Verification (details in the PR): facade 973 passed / 0 failed (was 1651; the delta is the moved code and its tests), id-cli 677 passed / 0 failed plus 7 aliases tests, workspace members 3532 passed with only the two named pre-existing failures (#8354 frames; the web/dist manifest test that needs the bun build), suite B 988 passed / 1 failed (the pre-existing serve test, #9274). FUEL_BUDGETS byte-identical. --- pkgs/id/Cargo.lock | 45 +- pkgs/id/Cargo.toml | 18 +- pkgs/id/crates/id-cli/Cargo.toml | 57 ++ pkgs/id/{ => crates/id-cli}/src/aliases.rs | 8 +- .../{ => crates/id-cli}/src/app_manifest.rs | 2 +- .../{ => crates/id-cli}/src/chat_presence.rs | 20 +- pkgs/id/{ => crates/id-cli}/src/cli/claim.rs | 0 pkgs/id/{ => crates/id-cli}/src/cli/doc.rs | 0 pkgs/id/{ => crates/id-cli}/src/cli/groups.rs | 6 +- .../id-cli}/src/cli/match_audit.rs | 0 pkgs/id/{ => crates/id-cli}/src/cli/mod.rs | 2 +- pkgs/id/{ => crates/id-cli}/src/cli/tag.rs | 0 pkgs/id/{ => crates/id-cli}/src/cli/tests.rs | 4 +- pkgs/id/{ => crates/id-cli}/src/cli/world.rs | 2 +- .../src/cli/world_limits_args_tests.rs | 2 +- .../id-cli}/src/cli/writer_sets.rs | 0 .../{ => crates/id-cli}/src/commands/claim.rs | 6 +- .../id-cli}/src/commands/client.rs | 2 +- .../{ => crates/id-cli}/src/commands/doc.rs | 10 +- .../{ => crates/id-cli}/src/commands/find.rs | 6 +- .../{ => crates/id-cli}/src/commands/get.rs | 16 +- .../{ => crates/id-cli}/src/commands/group.rs | 14 +- .../id/{ => crates/id-cli}/src/commands/id.rs | 2 +- .../{ => crates/id-cli}/src/commands/key.rs | 2 +- .../{ => crates/id-cli}/src/commands/list.rs | 10 +- .../id-cli}/src/commands/match_audit.rs | 0 .../{ => crates/id-cli}/src/commands/mod.rs | 2 +- .../{ => crates/id-cli}/src/commands/peers.rs | 20 +- .../{ => crates/id-cli}/src/commands/put.rs | 14 +- .../{ => crates/id-cli}/src/commands/repl.rs | 22 +- .../{ => crates/id-cli}/src/commands/serve.rs | 270 ++++---- .../{ => crates/id-cli}/src/commands/tag.rs | 4 +- .../{ => crates/id-cli}/src/commands/text.rs | 8 +- .../{ => crates/id-cli}/src/commands/world.rs | 203 +++--- .../id-cli}/src/commands/writer_set.rs | 16 +- pkgs/id/crates/id-cli/src/fileops_tests.rs | 652 ++++++++++++++++++ pkgs/id/{ => crates/id-cli}/src/helpers.rs | 8 +- pkgs/id/crates/id-cli/src/lib.rs | 231 +++++++ pkgs/id/{ => crates/id-cli}/src/local.rs | 12 +- .../id/{ => crates/id-cli}/src/match_audit.rs | 12 +- .../id/{ => crates/id-cli}/src/meta_client.rs | 8 +- .../id-cli}/src/peer_announcement.rs | 2 +- pkgs/id/{ => crates/id-cli}/src/protocol.rs | 2 +- .../{ => crates/id-cli}/src/publications.rs | 4 +- .../id-cli}/src/publications_runtime.rs | 0 pkgs/id/{ => crates/id-cli}/src/repl/input.rs | 0 pkgs/id/{ => crates/id-cli}/src/repl/mod.rs | 0 .../id/{ => crates/id-cli}/src/repl/runner.rs | 0 .../id-cli}/src/server_config/mod.rs | 14 +- .../id-cli}/src/server_config/parse.rs | 34 +- .../id-cli}/src/server_config/provision.rs | 20 +- pkgs/id/{ => crates/id-cli}/tests/aliases.rs | 10 +- pkgs/id/crates/id-core/src/lib.rs | 33 + pkgs/id/src/fileops.rs | 648 ----------------- pkgs/id/src/lib.rs | 227 +----- 55 files changed, 1448 insertions(+), 1262 deletions(-) create mode 100644 pkgs/id/crates/id-cli/Cargo.toml rename pkgs/id/{ => crates/id-cli}/src/aliases.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/app_manifest.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/chat_presence.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/cli/claim.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/cli/doc.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/cli/groups.rs (97%) rename pkgs/id/{ => crates/id-cli}/src/cli/match_audit.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/cli/mod.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/cli/tag.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/cli/tests.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/cli/world.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/cli/world_limits_args_tests.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/cli/writer_sets.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/commands/claim.rs (96%) rename pkgs/id/{ => crates/id-cli}/src/commands/client.rs (97%) rename pkgs/id/{ => crates/id-cli}/src/commands/doc.rs (96%) rename pkgs/id/{ => crates/id-cli}/src/commands/find.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/commands/get.rs (96%) rename pkgs/id/{ => crates/id-cli}/src/commands/group.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/commands/id.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/commands/key.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/commands/list.rs (94%) rename pkgs/id/{ => crates/id-cli}/src/commands/match_audit.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/commands/mod.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/commands/peers.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/commands/put.rs (97%) rename pkgs/id/{ => crates/id-cli}/src/commands/repl.rs (98%) rename pkgs/id/{ => crates/id-cli}/src/commands/serve.rs (94%) rename pkgs/id/{ => crates/id-cli}/src/commands/tag.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/commands/text.rs (97%) rename pkgs/id/{ => crates/id-cli}/src/commands/world.rs (92%) rename pkgs/id/{ => crates/id-cli}/src/commands/writer_set.rs (92%) create mode 100644 pkgs/id/crates/id-cli/src/fileops_tests.rs rename pkgs/id/{ => crates/id-cli}/src/helpers.rs (99%) create mode 100644 pkgs/id/crates/id-cli/src/lib.rs rename pkgs/id/{ => crates/id-cli}/src/local.rs (96%) rename pkgs/id/{ => crates/id-cli}/src/match_audit.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/meta_client.rs (90%) rename pkgs/id/{ => crates/id-cli}/src/peer_announcement.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/protocol.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/publications.rs (99%) rename pkgs/id/{ => crates/id-cli}/src/publications_runtime.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/repl/input.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/repl/mod.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/repl/runner.rs (100%) rename pkgs/id/{ => crates/id-cli}/src/server_config/mod.rs (95%) rename pkgs/id/{ => crates/id-cli}/src/server_config/parse.rs (97%) rename pkgs/id/{ => crates/id-cli}/src/server_config/provision.rs (98%) rename pkgs/id/{ => crates/id-cli}/tests/aliases.rs (97%) diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 749fa1330d..e9fd67f4a6 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -3882,7 +3882,6 @@ version = "0.1.0" dependencies = [ "anyhow", "argon2", - "axum", "base64 0.22.1", "blake3", "cbor-core", @@ -3897,6 +3896,7 @@ dependencies = [ "futures-lite", "futures-util", "id-caps", + "id-cli", "id-core", "id-directory", "id-events", @@ -3959,6 +3959,49 @@ dependencies = [ "toml", ] +[[package]] +name = "id-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "blake3", + "clap", + "distributed-topic-tracker", + "ed25519-dalek 3.0.0", + "futures-lite", + "id-caps", + "id-core", + "id-directory", + "id-events", + "id-groups", + "id-store", + "id-sync", + "id-web", + "id-worlds", + "iroh", + "iroh-base", + "iroh-blobs", + "iroh-docs", + "iroh-gossip", + "iroh-mdns-address-lookup", + "libc", + "p2panda-core", + "postcard", + "proptest", + "rand 0.10.3", + "rpassword", + "rustyline", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "toml", + "tracing", + "zeroize", +] + [[package]] name = "id-core" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index e05475a56b..40a295a7df 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -16,14 +16,14 @@ categories = ["command-line-utilities", "network-programming"] # id-core sub-crate under crates/; this package is the workspace root. [workspace] -members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync", "crates/id-worlds", "crates/id-directory", "crates/id-web", "crates/id-native-shell"] +members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync", "crates/id-worlds", "crates/id-directory", "crates/id-web", "crates/id-native-shell", "crates/id-cli"] # The vendored crates stay OUT of the workspace: as path dependencies inside # this directory Cargo would otherwise treat them as members, and a member's # feature graph joins the lock resolve — p2panda-sync's `test_utils` feature # forwards to `p2panda-store/test_utils`, whose `sqlite` feature pulls sqlx # into Cargo.lock even though no build here enables it (see vendor/README.md). exclude = ["vendor/p2panda-sync", "vendor/p2panda-encryption"] -default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync", "crates/id-worlds", "crates/id-directory", "crates/id-web"] +default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync", "crates/id-worlds", "crates/id-directory", "crates/id-web", "crates/id-cli"] # ============================================================================= # Features @@ -31,19 +31,20 @@ default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", " [features] default = ["sandbox", "world"] -sandbox = ["world", "id-core/sandbox", "id-caps/sandbox", "id-worlds/sandbox"] +sandbox = ["world", "id-core/sandbox", "id-caps/sandbox", "id-worlds/sandbox", "id-cli/sandbox"] world = [ "id-core/world", + "id-cli/world", ] -ssh = ["world", "id-worlds/ssh"] +ssh = ["world", "id-worlds/ssh", "id-cli/ssh"] web = [ "world", - "dep:axum", "dep:id-web", "id-core/web", + "id-cli/web", ] # Mainline DHT address lookup (P7.3, decision 15). Off in the default build; src/dht.rs decides per server. -dht = ["id-sync/dht"] +dht = ["id-sync/dht", "id-cli/dht"] # Live-cluster binding for the currency PoC (#2289): the official TigerBeetle # Rust client, pinned to the harness server version (harness.rs). Off by # default so normal builds do not link the client native tb_client library. @@ -76,6 +77,10 @@ id-worlds = { path = "crates/id-worlds", default-features = false } # only the `web` feature links it, and src/lib.rs re-exports it as # `id::web` under that feature. id-web = { path = "crates/id-web", default-features = false, optional = true } +# Application layer extracted in step 7b of the crate split (#4411). +# Re-exported at their historical crate:: paths in src/lib.rs; the +# binary entry point (src/main.rs) stays in this package. +id-cli = { path = "crates/id-cli", default-features = false } # Directory-family modules extracted in step 6b of the crate split # (#4409). Re-exported at their historical crate:: paths in src/lib.rs. id-directory = { path = "crates/id-directory", default-features = false } @@ -132,7 +137,6 @@ unicode-segmentation = "1.13" unicode-width = "0.2" # Web feature dependencies (optional) -axum = { version = "0.8", features = ["ws", "multipart"], optional = true } argon2 = "0.6" chacha20poly1305 = "0.10" zeroize = "1" diff --git a/pkgs/id/crates/id-cli/Cargo.toml b/pkgs/id/crates/id-cli/Cargo.toml new file mode 100644 index 0000000000..197a4bc44c --- /dev/null +++ b/pkgs/id/crates/id-cli/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "id-cli" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +license = "MIT OR Apache-2.0" + +[features] +default = ["sandbox", "world"] +world = ["id-core/world"] +sandbox = ["world", "id-core/sandbox", "id-caps/sandbox", "id-worlds/sandbox"] +ssh = ["world", "id-worlds/ssh"] +web = ["world", "id-core/web", "dep:id-web", "dep:axum"] +dht = ["id-sync/dht"] + +[dependencies] +anyhow = "1" +id-caps = { path = "../id-caps", default-features = false } +id-core = { path = "../id-core", default-features = false } +id-directory = { path = "../id-directory", default-features = false } +id-events = { path = "../id-events", default-features = false } +id-groups = { path = "../id-groups", default-features = false } +id-store = { path = "../id-store", default-features = false } +id-sync = { path = "../id-sync", default-features = false } +id-web = { path = "../id-web", default-features = false, optional = true } +axum = { version = "0.8", features = ["ws", "multipart"], optional = true } +id-worlds = { path = "../id-worlds", default-features = false } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["full"] } +tracing = "0.1" +blake3 = "1" +clap = { version = "4", features = ["derive", "env"] } +distributed-topic-tracker = "0.3" +ed25519-dalek = { version = "3", features = ["rand_core"] } +futures-lite = "2" +iroh = "1" +iroh-base = "1" +iroh-blobs = "0.103" +iroh-docs = "0.101" +iroh-gossip = { version = "0.101", features = ["net"] } +iroh-mdns-address-lookup = "0.6" +libc = "0.2" +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" } +postcard = { version = "1", features = ["alloc"] } +rand = "0.10" +rpassword = "7" +rustyline = "18" +tempfile = "3" +thiserror = "2" +toml = "1" +zeroize = "1" + +[dev-dependencies] +id-core = { path = "../id-core", default-features = false, features = ["test-utils"] } +id-worlds = { path = "../id-worlds", default-features = false, features = ["test-utils"] } +proptest = "1.12" diff --git a/pkgs/id/src/aliases.rs b/pkgs/id/crates/id-cli/src/aliases.rs similarity index 98% rename from pkgs/id/src/aliases.rs rename to pkgs/id/crates/id-cli/src/aliases.rs index 8d6cb60858..7269a4a979 100644 --- a/pkgs/id/src/aliases.rs +++ b/pkgs/id/crates/id-cli/src/aliases.rs @@ -20,9 +20,9 @@ use std::collections::BTreeMap; use p2panda_core::Hash; -use crate::groups::Key; -use crate::tag_claims::Claim; -use crate::waiting::AuthorKey; +use id_events::groups::Key; +use id_store::tag_claims::Claim; +use id_core::waiting::AuthorKey; /// The tag name an alias claim carries. Its value is the alias text. pub const ALIAS_NAME: &str = "alias"; @@ -189,7 +189,7 @@ mod tests { subject, name: name.to_owned(), value: value.map(str::to_owned), - scope: crate::tag_claims::TagScope::Shared, + scope: id_store::tag_claims::TagScope::Shared, } } diff --git a/pkgs/id/src/app_manifest.rs b/pkgs/id/crates/id-cli/src/app_manifest.rs similarity index 99% rename from pkgs/id/src/app_manifest.rs rename to pkgs/id/crates/id-cli/src/app_manifest.rs index 5b7672b6b3..148bb08aab 100644 --- a/pkgs/id/src/app_manifest.rs +++ b/pkgs/id/crates/id-cli/src/app_manifest.rs @@ -668,7 +668,7 @@ route = "/tic-tac-toe" #[test] fn checked_in_tic_tac_toe_manifest_remains_valid() { - let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("apps/tic-tac-toe/app.toml"); + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../apps/tic-tac-toe/app.toml"); let source = fs::read_to_string(path).unwrap(); let manifest = parse_app_manifest(&source, "tic-tac-toe").unwrap(); assert_eq!(manifest.interfaces.web.unwrap().route, "/tic-tac-toe"); diff --git a/pkgs/id/src/chat_presence.rs b/pkgs/id/crates/id-cli/src/chat_presence.rs similarity index 98% rename from pkgs/id/src/chat_presence.rs rename to pkgs/id/crates/id-cli/src/chat_presence.rs index 9f947756a3..b0f46e1335 100644 --- a/pkgs/id/src/chat_presence.rs +++ b/pkgs/id/crates/id-cli/src/chat_presence.rs @@ -1,7 +1,7 @@ //! Chat presence: ephemeral TTL heartbeats and roster liveness (ID chat v1, #2809). //! //! Presence is a separately-scoped ephemeral protocol, distinct from chat messages -//! ([`crate::chat`]): a node periodically broadcasts a [`PresenceHeartbeat`] — +//! ([`id_store::chat`]): a node periodically broadcasts a [`PresenceHeartbeat`] — //! `{node, channels[], status, ts}` — over the already-wired gossip plane (see //! [`crate::commands::serve`]), and every receiver keeps the latest heartbeat per node in //! an in-memory [`PresenceTable`]. There are no leave messages: a node that stops @@ -20,7 +20,7 @@ //! entry point had no production caller and is removed; tests exercise the //! deterministic `update_at` core instead. The peer-announcement path is //! `SignedPeerAnnouncement::decode_frame` → -//! [`crate::discovery::PeerDiscovery::update`], both in the serve receiver +//! [`id_core::discovery::PeerDiscovery::update`], both in the serve receiver //! and the temporary table used by `commands::peers::discover_via_gossip`. //! //! `commands::peers::{query_local_peers, query_remote_peers, crawl_peers}` @@ -68,7 +68,7 @@ //! # Membership scoping //! //! A channel is a chat group (the channel's identity is its group [`Hash`], as in -//! [`crate::chat`]), and presence metadata is scoped to authorized channel members: +//! [`id_store::chat`]), and presence metadata is scoped to authorized channel members: //! //! - On receipt, [`PresenceTable::update_scoped`] filters a heartbeat's channels to //! those the *sender* is a member of (the caller's membership predicate), so a node @@ -90,7 +90,7 @@ //! # Roster //! //! The roster for a channel is the backing group's membership — the member set of the -//! group fold ([`crate::groups::GroupView`]) — annotated with last-seen liveness from +//! group fold ([`id_events::groups::GroupView`]) — annotated with last-seen liveness from //! the table: [`Liveness::Live`] when a heartbeat for that channel is within TTL, //! [`Liveness::Offline`] when the member was never seen or its heartbeat went stale. @@ -102,8 +102,8 @@ use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use p2panda_core::Hash; use serde::{Deserialize, Serialize}; -use crate::groups::GroupView; -use crate::waiting::AuthorKey; +use id_events::groups::GroupView; +use id_core::waiting::AuthorKey; /// How long a heartbeat keeps a node live, in seconds: 75, inside the 60–90 s band /// #2809 specifies. A node silent for longer than this reads as gone. @@ -284,7 +284,7 @@ struct Entry { /// Thread-safe in-memory table of the latest presence heartbeat per node. /// /// Cheaply cloneable (backed by `Arc`) and safe to share across async tasks, like -/// [`crate::discovery::PeerDiscovery`]. All state is ephemeral by construction: the +/// [`id_core::discovery::PeerDiscovery`]. All state is ephemeral by construction: the /// table is never persisted, journaled, synced, or replayed. #[derive(Debug, Clone, Default)] pub struct PresenceTable { @@ -319,7 +319,7 @@ impl PresenceTable { /// Records a heartbeat as of `now` (unix seconds), the deterministic core of /// [`update_scoped`](Self::update_scoped). /// - /// Three guards, mirroring [`crate::discovery::PeerDiscovery`]: + /// Three guards, mirroring [`id_core::discovery::PeerDiscovery`]: /// /// - **Freshness bound.** A heartbeat stamped older than [`PRESENCE_TTL_SECS`] /// relative to `now` is refused — replaying a captured heartbeat cannot keep a @@ -1049,7 +1049,7 @@ mod tests { // forgery (R = identity, S = 0) passes plain verify for any // message under it — only verify_strict keeps it out of the // presence authentication gate. - use crate::test_forgeries::{IDENTITY_KEY, identity_forgery}; + use id_core::test_forgeries::{IDENTITY_KEY, identity_forgery}; let chan = channel("general"); let mut hb = heartbeat(IDENTITY_KEY, vec![chan], 9_600); hb.signature = identity_forgery().to_vec(); @@ -1060,7 +1060,7 @@ mod tests { fn verify_rejects_a_non_canonical_s() { // #1386: a genuine signature mutated to S + L must be refused, // while the original verifies. - use crate::test_forgeries::with_non_canonical_s; + use id_core::test_forgeries::with_non_canonical_s; let chan = channel("general"); let alice_key = SigningKey::from_bytes(&[7u8; 32]); let alice = alice_key.verifying_key().to_bytes(); diff --git a/pkgs/id/src/cli/claim.rs b/pkgs/id/crates/id-cli/src/cli/claim.rs similarity index 100% rename from pkgs/id/src/cli/claim.rs rename to pkgs/id/crates/id-cli/src/cli/claim.rs diff --git a/pkgs/id/src/cli/doc.rs b/pkgs/id/crates/id-cli/src/cli/doc.rs similarity index 100% rename from pkgs/id/src/cli/doc.rs rename to pkgs/id/crates/id-cli/src/cli/doc.rs diff --git a/pkgs/id/src/cli/groups.rs b/pkgs/id/crates/id-cli/src/cli/groups.rs similarity index 97% rename from pkgs/id/src/cli/groups.rs rename to pkgs/id/crates/id-cli/src/cli/groups.rs index 8e7415caa7..81e0d8b0bf 100644 --- a/pkgs/id/src/cli/groups.rs +++ b/pkgs/id/crates/id-cli/src/cli/groups.rs @@ -3,9 +3,9 @@ use clap::{Args, Subcommand, ValueEnum}; -use crate::groups::Role; -use crate::groups::policy::Delegation; -use crate::groups::policy::SuccessorKind; +use id_events::groups::Role; +use id_events::groups::policy::Delegation; +use id_events::groups::policy::SuccessorKind; /// Subcommands for `id group`. Accounts and groups are 64 hex characters. #[derive(Subcommand, Debug)] diff --git a/pkgs/id/src/cli/match_audit.rs b/pkgs/id/crates/id-cli/src/cli/match_audit.rs similarity index 100% rename from pkgs/id/src/cli/match_audit.rs rename to pkgs/id/crates/id-cli/src/cli/match_audit.rs diff --git a/pkgs/id/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs similarity index 99% rename from pkgs/id/src/cli/mod.rs rename to pkgs/id/crates/id-cli/src/cli/mod.rs index 6306abdc3b..c8ecb79b53 100644 --- a/pkgs/id/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -130,7 +130,7 @@ pub use writer_sets::WriterSetCommand; /// # Example /// /// ```rust -/// use id::cli::Cli; +/// use id_cli::cli::Cli; /// use clap::Parser; /// /// // Parse command line arguments diff --git a/pkgs/id/src/cli/tag.rs b/pkgs/id/crates/id-cli/src/cli/tag.rs similarity index 100% rename from pkgs/id/src/cli/tag.rs rename to pkgs/id/crates/id-cli/src/cli/tag.rs diff --git a/pkgs/id/src/cli/tests.rs b/pkgs/id/crates/id-cli/src/cli/tests.rs similarity index 99% rename from pkgs/id/src/cli/tests.rs rename to pkgs/id/crates/id-cli/src/cli/tests.rs index 3601f2f32f..98db39a5f9 100644 --- a/pkgs/id/src/cli/tests.rs +++ b/pkgs/id/crates/id-cli/src/cli/tests.rs @@ -92,7 +92,7 @@ fn test_command_lists_cover_all_clap_subcommands() { "expected the full command set, got {names:?}" ); let source = include_str!("mod.rs"); - let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md")) + let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../README.md")) .expect("README readable"); check_command_lists( &names, @@ -109,7 +109,7 @@ fn test_command_lists_cover_all_clap_subcommands() { fn test_command_lists_reject_stale_entries() { let names = clap_subcommand_names(); let source = include_str!("mod.rs"); - let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md")) + let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../README.md")) .expect("README readable"); let mut doc_entries = module_doc_entries(source); diff --git a/pkgs/id/src/cli/world.rs b/pkgs/id/crates/id-cli/src/cli/world.rs similarity index 99% rename from pkgs/id/src/cli/world.rs rename to pkgs/id/crates/id-cli/src/cli/world.rs index 0fc3dceabf..0ba8b879eb 100644 --- a/pkgs/id/src/cli/world.rs +++ b/pkgs/id/crates/id-cli/src/cli/world.rs @@ -42,7 +42,7 @@ pub struct WorldRuntimeArgs { /// `id-core`'s `world_limits` and validates through this trait, which the /// CLI argument struct implements here in its own crate. #[cfg(feature = "world")] -impl crate::world_limits::WorldLimitArgs for WorldRuntimeArgs { +impl id_caps::world_limits::WorldLimitArgs for WorldRuntimeArgs { fn world_fuel(&self) -> u64 { self.world_fuel } diff --git a/pkgs/id/src/cli/world_limits_args_tests.rs b/pkgs/id/crates/id-cli/src/cli/world_limits_args_tests.rs similarity index 98% rename from pkgs/id/src/cli/world_limits_args_tests.rs rename to pkgs/id/crates/id-cli/src/cli/world_limits_args_tests.rs index acbf482c29..f64bd97d05 100644 --- a/pkgs/id/src/cli/world_limits_args_tests.rs +++ b/pkgs/id/crates/id-cli/src/cli/world_limits_args_tests.rs @@ -7,7 +7,7 @@ use anyhow::Result; use clap::Parser; use super::{Cli, Command, ServeArgs}; -use crate::world_limits::RuntimeLimits; +use id_caps::world_limits::RuntimeLimits; const KIB: u64 = 1024; const MIB: u64 = 1024 * KIB; diff --git a/pkgs/id/src/cli/writer_sets.rs b/pkgs/id/crates/id-cli/src/cli/writer_sets.rs similarity index 100% rename from pkgs/id/src/cli/writer_sets.rs rename to pkgs/id/crates/id-cli/src/cli/writer_sets.rs diff --git a/pkgs/id/src/commands/claim.rs b/pkgs/id/crates/id-cli/src/commands/claim.rs similarity index 96% rename from pkgs/id/src/commands/claim.rs rename to pkgs/id/crates/id-cli/src/commands/claim.rs index 1817da4fc0..cbfcce0778 100644 --- a/pkgs/id/src/commands/claim.rs +++ b/pkgs/id/crates/id-cli/src/commands/claim.rs @@ -1,7 +1,7 @@ //! `id claim`: set, clear, list, and search tag claims on any subject (P6.7c). //! //! This module parses the arguments, acts on the event store, and prints. The rules are the -//! library's ([`crate::local_events`], [`crate::tag_claims`]). +//! library's ([`id_events::local_events`], [`id_store::tag_claims`]). //! //! # Output //! @@ -19,8 +19,8 @@ use serde_json::{Value, json}; use crate::cli::{ClaimCommand, ClaimScope}; use crate::commands::doc::{open_events, print_action, print_rows}; use crate::commands::group::hex; -use crate::groups::log::hash_from_hex; -use crate::tag_claims::{Claim, TagScope}; +use id_groups::groups::log::hash_from_hex; +use id_store::tag_claims::{Claim, TagScope}; /// Prints a `set` line for a claim just recorded. pub(super) fn print_set(json: bool, subject: Hash, name: &str, value: Option<&str>, event: Hash) { diff --git a/pkgs/id/src/commands/client.rs b/pkgs/id/crates/id-cli/src/commands/client.rs similarity index 97% rename from pkgs/id/src/commands/client.rs rename to pkgs/id/crates/id-cli/src/commands/client.rs index 182fec5944..029c99bf08 100644 --- a/pkgs/id/src/commands/client.rs +++ b/pkgs/id/crates/id-cli/src/commands/client.rs @@ -10,7 +10,7 @@ //! # Usage //! //! ```rust,ignore -//! use id::commands::{get_serve_info, create_local_client_endpoint}; +//! use id_cli::commands::{get_serve_info, create_local_client_endpoint}; //! //! if let Some(serve_info) = get_serve_info().await { //! let (endpoint, addr) = create_local_client_endpoint(&serve_info).await?; diff --git a/pkgs/id/src/commands/doc.rs b/pkgs/id/crates/id-cli/src/commands/doc.rs similarity index 96% rename from pkgs/id/src/commands/doc.rs rename to pkgs/id/crates/id-cli/src/commands/doc.rs index a70587a340..bbbe803735 100644 --- a/pkgs/id/src/commands/doc.rs +++ b/pkgs/id/crates/id-cli/src/commands/doc.rs @@ -1,7 +1,7 @@ //! `id doc`: publish a file as a document, and list a document's events, frontier and history //! (P6.7c): parse the arguments, act on the event store, and print. //! -//! The rules are the library's ([`crate::local_events`]). This module only turns arguments into +//! The rules are the library's ([`id_events::local_events`]). This module only turns arguments into //! calls and results into lines or JSON. The store is the stand-in for sync, as the group log is. //! //! # Output @@ -20,8 +20,8 @@ use serde_json::{Value, json}; use crate::cli::DocCommand; use crate::commands::claim::print_set; use crate::commands::group::{hex, object, tokens}; -use crate::groups::log::hash_from_hex; -use crate::local_events::{DIR_NAME, Entry, LocalEvents}; +use id_groups::groups::log::hash_from_hex; +use id_events::local_events::{DIR_NAME, Entry, LocalEvents}; use crate::{KEY_FILE, load_or_create_keypair}; /// Opens the event store that the command reads and appends to, signed as this node. The store is @@ -186,8 +186,8 @@ pub async fn cmd_doc(path: Option, json: bool, command: DocCommand) -> #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; - use crate::documents::DocumentRef; - use crate::waiting::AuthorKey; + use id_store::documents::DocumentRef; + use id_core::waiting::AuthorKey; fn hash(byte: u8) -> Hash { Hash::from_bytes([byte; 32]) diff --git a/pkgs/id/src/commands/find.rs b/pkgs/id/crates/id-cli/src/commands/find.rs similarity index 99% rename from pkgs/id/src/commands/find.rs rename to pkgs/id/crates/id-cli/src/commands/find.rs index e962b56d97..659cf384a7 100644 --- a/pkgs/id/src/commands/find.rs +++ b/pkgs/id/crates/id-cli/src/commands/find.rs @@ -920,14 +920,14 @@ pub async fn cmd_find_matches( if let Some(node_str) = node { let node_id: EndpointId = node_str.parse()?; let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; - let endpoint = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let endpoint = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(client_key) .bind() .await?; - let meta_conn = crate::connectivity::connect(&endpoint, node_id, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(&endpoint, node_id, META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::Find { query: query.to_owned(), diff --git a/pkgs/id/src/commands/get.rs b/pkgs/id/crates/id-cli/src/commands/get.rs similarity index 96% rename from pkgs/id/src/commands/get.rs rename to pkgs/id/crates/id-cli/src/commands/get.rs index 19a0b62ff5..ce6baeaced 100644 --- a/pkgs/id/src/commands/get.rs +++ b/pkgs/id/crates/id-cli/src/commands/get.rs @@ -105,7 +105,7 @@ pub async fn cmd_gethash(hash_str: &str, output: &str) -> Result<()> { let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let blobs_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; store_handle .remote() .fetch(blobs_conn.clone(), hash) @@ -158,7 +158,7 @@ pub async fn cmd_get_local(name: &str, output: &str) -> Result<()> { let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let meta_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), META_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::Get { filename: name.to_owned(), @@ -182,7 +182,7 @@ pub async fn cmd_get_local(name: &str, output: &str) -> Result<()> { }; let blobs_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; store_handle .remote() .fetch(blobs_conn.clone(), hash) @@ -253,7 +253,7 @@ pub async fn cmd_get_one( let store_handle = store.as_store(); let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let blobs_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; match store_handle.remote().fetch(blobs_conn.clone(), hash).await { Ok(_) => { @@ -322,14 +322,14 @@ pub async fn cmd_get_one_remote( let store_handle = store.as_store(); let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; - let endpoint = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let endpoint = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(client_key) .bind() .await?; - let meta_conn = crate::connectivity::connect(&endpoint, server_node_id, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(&endpoint, server_node_id, META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::Get { filename: name.to_owned(), @@ -352,7 +352,7 @@ pub async fn cmd_get_one_remote( } }; - let blobs_conn = crate::connectivity::connect(&endpoint, server_node_id, BLOBS_ALPN).await?; + let blobs_conn = id_core::connectivity::connect(&endpoint, server_node_id, BLOBS_ALPN).await?; store_handle .remote() .fetch(blobs_conn.clone(), hash) diff --git a/pkgs/id/src/commands/group.rs b/pkgs/id/crates/id-cli/src/commands/group.rs similarity index 98% rename from pkgs/id/src/commands/group.rs rename to pkgs/id/crates/id-cli/src/commands/group.rs index 114d21cbd8..98cc02ead0 100644 --- a/pkgs/id/src/commands/group.rs +++ b/pkgs/id/crates/id-cli/src/commands/group.rs @@ -1,7 +1,7 @@ //! `id group`, `id delegate` and `id revoke` (P6.7a and P6.7b): parse the arguments, act on the group //! log, and print. //! -//! The rules are the fold's, and the actions are the library's ([`crate::groups::actions`]). This +//! The rules are the fold's, and the actions are the library's ([`id_events::groups::actions`]). This //! module only turns arguments into calls and results into lines or JSON. A refused action is an //! error, so the exit status says so. Its event stays in the log, as the author's record. //! @@ -19,15 +19,15 @@ use p2panda_core::Hash; use serde_json::{Map, Value, json}; use crate::cli::{DelegateArgs, GroupCommand, GroupRemoveMode, GroupTemplate, RevokeArgs}; -use crate::groups::actions::{Action, NewGroup}; -use crate::groups::log::{FILE_NAME, GroupLog, hash_from_hex, key_from_hex}; -use crate::groups::policy::{ +use id_groups::groups::actions::{Action, NewGroup}; +use id_groups::groups::log::{FILE_NAME, GroupLog, hash_from_hex, key_from_hex}; +use id_events::groups::policy::{ History, Join, OnMemberRemoved, Removal, RemoveMode, RemoveSuccessor, SuccessorKind, TransferOpts, }; -use crate::groups::warnings::{Evaluator, Observation, Warning, size_tier}; -use crate::groups::{Body, Delegate, GroupView, Key, MemberOp, Outcome}; -use crate::invites::Invitation; +use id_groups::groups::warnings::{Evaluator, Observation, Warning, size_tier}; +use id_events::groups::{Body, Delegate, GroupView, Key, MemberOp, Outcome}; +use id_directory::invites::Invitation; use crate::{KEY_FILE, load_or_create_keypair}; /// The log a command reads and appends to: `--groups-log`, or the default file in the data directory. diff --git a/pkgs/id/src/commands/id.rs b/pkgs/id/crates/id-cli/src/commands/id.rs similarity index 98% rename from pkgs/id/src/commands/id.rs rename to pkgs/id/crates/id-cli/src/commands/id.rs index 2c7e9160c8..0172e28a72 100644 --- a/pkgs/id/src/commands/id.rs +++ b/pkgs/id/crates/id-cli/src/commands/id.rs @@ -25,7 +25,7 @@ use anyhow::Result; use iroh_base::EndpointId; -use crate::store::load_or_create_keypair; +use id_store::store::load_or_create_keypair; use crate::{CLIENT_KEY_FILE, KEY_FILE}; /// Prints the node ID derived from the local keypair. diff --git a/pkgs/id/src/commands/key.rs b/pkgs/id/crates/id-cli/src/commands/key.rs similarity index 99% rename from pkgs/id/src/commands/key.rs rename to pkgs/id/crates/id-cli/src/commands/key.rs index 6ab012c51c..40482653ee 100644 --- a/pkgs/id/src/commands/key.rs +++ b/pkgs/id/crates/id-cli/src/commands/key.rs @@ -9,7 +9,7 @@ use zeroize::Zeroizing; use crate::cli::KeyCommand; use id_core::key_envelope; use id_core::seed_phrase; -use crate::store::load_or_create_keypair; +use id_store::store::load_or_create_keypair; use crate::{CLIENT_KEY_FILE, KEY_FILE}; const MIN_PASSPHRASE_BYTES: usize = 8; diff --git a/pkgs/id/src/commands/list.rs b/pkgs/id/crates/id-cli/src/commands/list.rs similarity index 94% rename from pkgs/id/src/commands/list.rs rename to pkgs/id/crates/id-cli/src/commands/list.rs index 7ea4b408f4..7bbc0b1002 100644 --- a/pkgs/id/src/commands/list.rs +++ b/pkgs/id/crates/id-cli/src/commands/list.rs @@ -35,7 +35,7 @@ use crate::commands::client::create_local_client_endpoint; use crate::commands::serve::get_serve_info; use crate::commands::text::list_tsv_row; use crate::protocol::{MetaRequest, MetaResponse}; -use crate::store::{load_or_create_keypair, open_store}; +use id_store::store::{load_or_create_keypair, open_store}; use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id}; /// Lists all stored files (local or remote). @@ -77,7 +77,7 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let meta_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), META_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::List)?; send.write_all(&req).await?; @@ -156,14 +156,14 @@ pub async fn cmd_list(node: Option, no_relay: bool) -> Result<()> { /// Same format as [`cmd_list`]. pub async fn cmd_list_remote(server_node_id: EndpointId, no_relay: bool) -> Result<()> { let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; - let endpoint = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let endpoint = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(client_key) .bind() .await?; - let meta_conn = crate::connectivity::connect(&endpoint, server_node_id, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(&endpoint, server_node_id, META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::List)?; send.write_all(&req).await?; diff --git a/pkgs/id/src/commands/match_audit.rs b/pkgs/id/crates/id-cli/src/commands/match_audit.rs similarity index 100% rename from pkgs/id/src/commands/match_audit.rs rename to pkgs/id/crates/id-cli/src/commands/match_audit.rs diff --git a/pkgs/id/src/commands/mod.rs b/pkgs/id/crates/id-cli/src/commands/mod.rs similarity index 98% rename from pkgs/id/src/commands/mod.rs rename to pkgs/id/crates/id-cli/src/commands/mod.rs index aac1b53756..89498753e5 100644 --- a/pkgs/id/src/commands/mod.rs +++ b/pkgs/id/crates/id-cli/src/commands/mod.rs @@ -43,7 +43,7 @@ //! # Examples //! //! ```rust,ignore -//! use id::commands::{cmd_put_local_file, cmd_get_local, cmd_list}; +//! use id_cli::commands::{cmd_put_local_file, cmd_get_local, cmd_list}; //! //! // Store a file //! cmd_put_local_file("./data.txt", Some("my-data".to_string())).await?; diff --git a/pkgs/id/src/commands/peers.rs b/pkgs/id/crates/id-cli/src/commands/peers.rs similarity index 98% rename from pkgs/id/src/commands/peers.rs rename to pkgs/id/crates/id-cli/src/commands/peers.rs index 4bace178b6..80b370166e 100644 --- a/pkgs/id/src/commands/peers.rs +++ b/pkgs/id/crates/id-cli/src/commands/peers.rs @@ -58,10 +58,10 @@ use anyhow::{Result, bail}; use iroh_base::EndpointId; use iroh_mdns_address_lookup::MdnsAddressLookup; -use crate::discovery::{PeerAnnouncement, PeerDiscovery, resolve_config}; +use id_core::discovery::{PeerAnnouncement, PeerDiscovery, resolve_config}; use crate::peer_announcement::SignedPeerAnnouncement; use crate::protocol::{AbuseCountersRow, AbusePolicyView, MetaRequest, MetaResponse}; -use crate::store::load_or_create_keypair; +use id_store::store::load_or_create_keypair; use crate::{CLIENT_KEY_FILE, META_ALPN, is_node_id}; use super::client::create_local_client_endpoint; @@ -326,7 +326,7 @@ async fn query_local_peers() -> Result> { let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let result = async { - let meta_conn = crate::connectivity::connect(&endpoint, endpoint_addr, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(&endpoint, endpoint_addr, META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::ListPeers)?; send.write_all(&req).await?; @@ -354,7 +354,7 @@ async fn query_local_abuse_counters() -> Result<(Vec, Option Vec { #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; - use crate::discovery::PeerDiscovery; + use id_core::discovery::PeerDiscovery; use iroh_base::SecretKey; #[tokio::test] diff --git a/pkgs/id/src/commands/put.rs b/pkgs/id/crates/id-cli/src/commands/put.rs similarity index 97% rename from pkgs/id/src/commands/put.rs rename to pkgs/id/crates/id-cli/src/commands/put.rs index e29ee6617c..675e24f63a 100644 --- a/pkgs/id/src/commands/put.rs +++ b/pkgs/id/crates/id-cli/src/commands/put.rs @@ -111,7 +111,7 @@ pub async fn push_and_name( name: &str, hash: Hash, ) -> Result<()> { - let blobs_conn = crate::connectivity::connect(endpoint, target.clone(), BLOBS_ALPN).await?; + let blobs_conn = id_core::connectivity::connect(endpoint, target.clone(), BLOBS_ALPN).await?; let push_request = PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()])); store .remote() @@ -123,19 +123,19 @@ pub async fn push_and_name( server's `--allow-node` or `.iroh-allowed`)", )?; - let meta_conn = crate::connectivity::connect(endpoint, target, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(endpoint, target, META_ALPN).await?; let req = MetaRequest::Put { filename: name.to_owned(), hash, }; - let outcome = crate::connectivity::within( + let outcome = id_core::connectivity::within( PUT_FINALIZATION_TIMEOUT, "registering the blob name", async { loop { match request_over(&meta_conn, &req).await? { MetaResponse::Error { message } - if crate::fileops::is_blob_missing_message(&message) => + if id_sync::fileops::is_blob_missing_message(&message) => { tokio::time::sleep(std::time::Duration::from_millis(250)).await; } @@ -231,7 +231,7 @@ pub async fn cmd_put_hash(source: &str) -> Result<()> { let (endpoint, endpoint_addr) = create_local_client_endpoint(&serve_info).await?; let blobs_conn = - crate::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; + id_core::connectivity::connect(&endpoint, endpoint_addr.clone(), BLOBS_ALPN).await?; let push_request = PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()])); store_handle @@ -348,8 +348,8 @@ pub async fn cmd_put_one_remote( let (hash, _guard) = add_raw(&store_handle, afs::read(&path_buf).await?).await?; let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; - let endpoint = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let endpoint = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(client_key) .bind() diff --git a/pkgs/id/src/commands/repl.rs b/pkgs/id/crates/id-cli/src/commands/repl.rs similarity index 98% rename from pkgs/id/src/commands/repl.rs rename to pkgs/id/crates/id-cli/src/commands/repl.rs index 2a84eac471..3924d6eb0c 100644 --- a/pkgs/id/src/commands/repl.rs +++ b/pkgs/id/crates/id-cli/src/commands/repl.rs @@ -93,7 +93,7 @@ use crate::commands::put::{add_raw, push_and_name}; use crate::commands::serve::get_serve_info; use crate::commands::tag::{self as tag, TagDisplayOptions}; use crate::commands::text::{list_tsv_row, plain_field}; -use crate::discovery::PeerAnnouncement; +use id_core::discovery::PeerAnnouncement; use crate::local::LocalNode; use crate::meta_client::{MetaRequester, expect_ok, read_capped_response, request_over}; use crate::{ @@ -248,7 +248,7 @@ impl ReplContext { let client_key = load_or_create_keypair(CLIENT_KEY_FILE).await?; let endpoint = - crate::connectivity::public_builder(crate::connectivity::RelayPolicy::N0) + id_core::connectivity::public_builder(id_core::connectivity::RelayPolicy::N0) .secret_key(client_key) .bind() .await?; @@ -358,7 +358,7 @@ impl ReplContext { { return Ok(meta_conn.as_ref().unwrap()); } - let conn = crate::connectivity::connect(endpoint, endpoint_addr.clone(), META_ALPN) + let conn = id_core::connectivity::connect(endpoint, endpoint_addr.clone(), META_ALPN) .await?; *meta_conn = Some(conn); Ok(meta_conn.as_ref().unwrap()) @@ -374,7 +374,7 @@ impl ReplContext { { return Ok(meta_conn.as_ref().unwrap()); } - let conn = crate::connectivity::connect(endpoint, *node_id, META_ALPN).await?; + let conn = id_core::connectivity::connect(endpoint, *node_id, META_ALPN).await?; *meta_conn = Some(conn); Ok(meta_conn.as_ref().unwrap()) } @@ -407,7 +407,7 @@ impl ReplContext { return Ok(blobs_conn.as_ref().unwrap()); } let conn = - crate::connectivity::connect(endpoint, endpoint_addr.clone(), BLOBS_ALPN) + id_core::connectivity::connect(endpoint, endpoint_addr.clone(), BLOBS_ALPN) .await?; *blobs_conn = Some(conn); Ok(blobs_conn.as_ref().unwrap()) @@ -423,7 +423,7 @@ impl ReplContext { { return Ok(blobs_conn.as_ref().unwrap()); } - let conn = crate::connectivity::connect(endpoint, *node_id, BLOBS_ALPN).await?; + let conn = id_core::connectivity::connect(endpoint, *node_id, BLOBS_ALPN).await?; *blobs_conn = Some(conn); Ok(blobs_conn.as_ref().unwrap()) } @@ -888,7 +888,7 @@ impl ReplContext { anyhow!("@NODE_ID requires a connected mode (use 'id repl' with a running serve)") })?; - let conn = crate::connectivity::connect(endpoint, node_id, META_ALPN).await?; + let conn = id_core::connectivity::connect(endpoint, node_id, META_ALPN).await?; let (mut send, mut recv) = conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::List)?; send.write_all(&req).await?; @@ -1011,7 +1011,7 @@ impl ReplContext { })?; let output = output.unwrap_or(name); - let meta_conn = crate::connectivity::connect(endpoint, node_id, META_ALPN).await?; + let meta_conn = id_core::connectivity::connect(endpoint, node_id, META_ALPN).await?; let (mut send, mut recv) = meta_conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::Get { filename: name.to_owned(), @@ -1024,7 +1024,7 @@ impl ReplContext { match resp { MetaResponse::Get { hash: Some(hash) } => { let blobs_conn = - crate::connectivity::connect(endpoint, node_id, BLOBS_ALPN).await?; + id_core::connectivity::connect(endpoint, node_id, BLOBS_ALPN).await?; let store_handle = self.store_handle(); store_handle.remote().fetch(blobs_conn, hash).await?; export_blob(&store_handle, hash, output).await?; @@ -1055,7 +1055,7 @@ impl ReplContext { anyhow!("@NODE_ID requires a connected mode (use 'id repl' with a running serve)") })?; - let conn = crate::connectivity::connect(endpoint, node_id, META_ALPN).await?; + let conn = id_core::connectivity::connect(endpoint, node_id, META_ALPN).await?; let (mut send, mut recv) = conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::Delete { filename: name.to_owned(), @@ -1137,7 +1137,7 @@ impl ReplContext { anyhow!("@NODE_ID requires a connected mode (use 'id repl' with a running serve)") })?; - let conn = crate::connectivity::connect(endpoint, node_id, META_ALPN).await?; + let conn = id_core::connectivity::connect(endpoint, node_id, META_ALPN).await?; let (mut send, mut recv) = conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::ListPeers)?; send.write_all(&req).await?; diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs similarity index 94% rename from pkgs/id/src/commands/serve.rs rename to pkgs/id/crates/id-cli/src/commands/serve.rs index 5f4510792a..a775c68b2d 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -75,18 +75,18 @@ use tracing::{debug, info, warn}; use crate::chat_presence::{ HEARTBEAT_INTERVAL, PresenceHeartbeat, PresenceTable, decode_frame, encode_frame, }; -use crate::discovery::{ +use id_core::discovery::{ ANNOUNCE_INTERVAL, PeerAnnouncement, PeerDiscovery, STALE_CHECK_INTERVAL, STALE_THRESHOLD, defaults, resolve_config, }; -use crate::groups::log::{FILE_NAME as GROUPS_FILE_NAME, GroupLog}; -use crate::groups::warnings::{Evaluator, Observation, Warning}; -use crate::groups::{Key as GroupKey, Projection}; +use id_groups::groups::log::{FILE_NAME as GROUPS_FILE_NAME, GroupLog}; +use id_groups::groups::warnings::{Evaluator, Observation, Warning}; +use id_events::groups::{Key as GroupKey, Projection}; use crate::peer_announcement::SignedPeerAnnouncement; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; -use crate::store::{load_or_create_keypair, open_store}; -use crate::tags::TagStore; -use crate::waiting::AuthorKey; +use id_store::store::{load_or_create_keypair, open_store}; +use id_store::tags::TagStore; +use id_core::waiting::AuthorKey; use crate::{KEY_FILE, META_ALPN, SERVE_LOCK, STORE_PATH}; /// Print a status line to stdout **without panicking** if stdout is gone. @@ -459,7 +459,7 @@ impl Default for WebContentTarget { impl WebContentTarget { /// Build a `Program` target, validating the world name against - /// the world-name rule ([`crate::world_hub::validate_world_name`]): + /// the world-name rule ([`id_worlds::world_hub::validate_world_name`]): /// a program target names a world, so it must be a name a world /// can bear -- 1 to 64 bytes of `a-z`, `0-9`, `-` and `_`, never /// a path segment. The stored name is the trimmed one. @@ -475,7 +475,7 @@ impl WebContentTarget { !world.is_empty(), "program target world name must not be empty (expected program:)" ); - crate::world_hub::validate_world_name(world).map_err(|e| { + id_worlds::world_hub::validate_world_name(world).map_err(|e| { anyhow::anyhow!("invalid program target world name {world:?}: {e}") })?; Ok(Self::Program(world.to_owned())) @@ -719,7 +719,7 @@ fn validate_world_options( "--world-module requires --world" ); #[cfg(feature = "world")] - crate::world_hub::validate_world_name(world_name)?; + id_worlds::world_hub::validate_world_name(world_name)?; ensure!( world_cap_policy == "deny" || world_cap_policy == "grant-on-use", "--world-cap-policy must be `deny` or `grant-on-use`" @@ -751,8 +751,8 @@ pub async fn build_access_policy( node_id: EndpointId, allow_node: &[String], open_writes: bool, -) -> Result { - use crate::access::{AccessPolicy, load_allowed_nodes}; +) -> Result { + use id_core::access::{AccessPolicy, load_allowed_nodes}; if open_writes { return Ok(AccessPolicy::open()); } @@ -788,7 +788,7 @@ pub fn world_dir(name: &str) -> PathBuf { fn resolve_compiler( roc_bin: Option, roc_platform: Option, -) -> Result> { +) -> Result> { let Some(platform) = roc_platform .or_else(|| std::env::var("ID_ROC_PLATFORM").ok().map(PathBuf::from)) .or_else(|| { @@ -805,7 +805,7 @@ fn resolve_compiler( let roc_bin = roc_bin .or_else(|| std::env::var("ID_ROC_BIN").ok()) .unwrap_or_else(|| "roc".to_owned()); - let compiler = crate::world_compile::Compiler::new(platform, roc_bin)?; + let compiler = id_worlds::world_compile::Compiler::new(platform, roc_bin)?; info!( platform = %compiler.platform_dir.display(), roc = %compiler.roc_bin, @@ -824,8 +824,8 @@ fn resolve_compiler( let lru_bytes = std::env::var("ID_WORLD_COMPILE_CACHE_LRU_BYTES") .ok() .and_then(|value| value.parse::().ok()) - .unwrap_or(crate::world_cache::DEFAULT_LRU_BYTES); - let cache = crate::world_cache::WorldCache::open(PathBuf::from(&cache_dir), lru_bytes)?; + .unwrap_or(id_worlds::world_cache::DEFAULT_LRU_BYTES); + let cache = id_worlds::world_cache::WorldCache::open(PathBuf::from(&cache_dir), lru_bytes)?; info!( cache_dir, lru_bytes, "world: shared compiled-world cache enabled" @@ -844,8 +844,8 @@ fn mail_sink( command: Option, smtp: Option, from: Option, -) -> Result>> { - use crate::directory_mail::{CommandSink, MailSink, OutboxSink, SmtpSink}; +) -> Result>> { + use id_directory::directory_mail::{CommandSink, MailSink, OutboxSink, SmtpSink}; use anyhow::Context as _; let sink: Arc = match (outbox, command, smtp) { (Some(dir), _, _) => Arc::new(OutboxSink::new(dir)), @@ -860,16 +860,16 @@ fn mail_sink( } /// The server's capability ceiling: the named capabilities, or the default -/// ceiling ([`crate::world_caps::default_ceiling_names`]) when no list is +/// ceiling ([`id_caps::world_caps::default_ceiling_names`]) when no list is /// given — providers whose manifest default is `Excluded` do not join a /// server by registration alone (#838). Like a world ceiling, it names /// capabilities; `*` is refused. #[cfg(feature = "world")] fn allowed_caps(names: Option<&[String]>) -> Result> { match names { - None => Ok(crate::world_caps::default_ceiling_names()), + None => Ok(id_caps::world_caps::default_ceiling_names()), Some(names) => { - crate::world_caps::validate_ceiling_names(names)?; + id_caps::world_caps::validate_ceiling_names(names)?; Ok(names.iter().cloned().collect()) } } @@ -886,17 +886,17 @@ struct ServeWorlds { default_module: Option, grant_on_use: bool, server_caps: std::collections::BTreeSet, - compiler: Option, + compiler: Option, native: bool, source_only: bool, trusted_module_keys: Vec<[u8; 32]>, - runtime: crate::world_limits::RuntimeLimits, - mail: Option>, + runtime: id_caps::world_limits::RuntimeLimits, + mail: Option>, } #[cfg(feature = "world")] -impl crate::world_hub::WorldOpener for ServeWorlds { - fn open<'a>(&'a self, name: &'a str, create: bool) -> crate::world_hub::OpenFuture<'a> { +impl id_worlds::world_hub::WorldOpener for ServeWorlds { + fn open<'a>(&'a self, name: &'a str, create: bool) -> id_worlds::world_hub::OpenFuture<'a> { Box::pin(async move { if !create && !self.exists(name) { return Ok(None); @@ -919,7 +919,7 @@ impl crate::world_hub::WorldOpener for ServeWorlds { .flatten() .filter(|entry| entry.path().join("journal.jsonl").is_file()) .filter_map(|entry| entry.file_name().into_string().ok()) - .filter(|name| crate::world_hub::validate_world_name(name).is_ok()) + .filter(|name| id_worlds::world_hub::validate_world_name(name).is_ok()) .collect(); names.sort(); names @@ -932,9 +932,9 @@ impl crate::world_hub::WorldOpener for ServeWorlds { #[cfg(feature = "world")] impl ServeWorlds { - async fn open_world(&self, name: &str) -> Result { - use crate::world::{WorldCore, WorldHandle, WorldLimits}; - use crate::world_session::WorldService; + async fn open_world(&self, name: &str) -> Result { + use id_worlds::world::{WorldCore, WorldHandle, WorldLimits}; + use id_worlds::world_session::WorldService; let limits = WorldLimits { checkpoint_every: self.checkpoint_every, @@ -964,7 +964,7 @@ impl ServeWorlds { let dir = world_dir(name); let namespace_file = (!self.ephemeral).then(|| dir.join("records.namespace")); let records = - crate::world_records::RecordsStore::open(&self.docs, namespace_file.as_deref()).await?; + id_worlds::world_records::RecordsStore::open(&self.docs, namespace_file.as_deref()).await?; info!( world = name, namespace = %records.namespace(), @@ -978,13 +978,13 @@ impl ServeWorlds { let service = if self.ephemeral { make(WorldHandle::spawn_with_device_manifest( WorldCore::new(name, limits)?, - Box::::default(), + Box::::default(), Some(WorldHandle::host_device_manifest()), )) .with_records_store(records) } else { let (service, report) = - crate::world_store::open_world(&dir, name, limits, runtime, make).await?; + id_worlds::world_store::open_world(&dir, name, limits, runtime, make).await?; status!( "world {name}: restored {} at sequence {} ({} input(s) replayed)", dir.display(), @@ -1025,17 +1025,17 @@ impl ServeWorlds { #[cfg(feature = "sandbox")] async fn install_default_module( &self, - service: &crate::world_session::WorldService, + service: &id_worlds::world_session::WorldService, path: &std::path::Path, ) -> Result<()> { let metadata = tokio::fs::metadata(path).await?; ensure!( usize::try_from(metadata.len()) - .is_ok_and(|len| len <= crate::world_session::MAX_WORLD_MODULE_BYTES), + .is_ok_and(|len| len <= id_worlds::world_session::MAX_WORLD_MODULE_BYTES), "world module exceeds the configured module size limit" ); let wasm = tokio::fs::read(path).await?; - let hash = crate::world_session::module_hash(&wasm); + let hash = id_worlds::world_session::module_hash(&wasm); if service.active_module_hash().await.as_deref() == Some(hash.as_str()) { info!(module = %path.display(), "world: module already active"); } else { @@ -1053,7 +1053,7 @@ impl ServeWorlds { #[allow(clippy::unused_async)] async fn install_default_module( &self, - _service: &crate::world_session::WorldService, + _service: &id_worlds::world_session::WorldService, _path: &std::path::Path, ) -> Result<()> { anyhow::bail!("--world-module requires a build with the `sandbox` feature"); @@ -1175,8 +1175,8 @@ pub fn start_server_config_persisted( ) -> Result { let config = crate::server_config::ServerConfig::load(path) .map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?; - let directory = crate::directory::Directory::open(&server_config_directory_path(groups_log))?; - let mut log = crate::groups::log::GroupLog::open(groups_log)?; + let directory = id_directory::directory::Directory::open(&server_config_directory_path(groups_log))?; + let mut log = id_groups::groups::log::GroupLog::open(groups_log)?; let already = log.events().len(); let mut provisioned = crate::server_config::Provisioned::from_parts(directory, log.events().to_vec()); @@ -1200,7 +1200,7 @@ pub fn start_server_config_persisted( /// server config provisions (#5119, PR #8356 review): slice 3 /// persists provisioning into the directory beside the groups log, /// but a durable world loads `.id-worlds//directory.jsonl` -/// ([`crate::world_store::open_world`]), so without this seed the +/// ([`id_worlds::world_store::open_world`]), so without this seed the /// live world's directory view treats configured keys as anonymous /// while startup reports them provisioned. The caller names the /// default world, the one serve opens at startup. Seeding is the @@ -1219,7 +1219,7 @@ pub fn seed_world_directory( dir: &Path, ) -> Result { std::fs::create_dir_all(dir)?; - let directory = crate::directory::Directory::open(&dir.join("directory.jsonl"))?; + let directory = id_directory::directory::Directory::open(&dir.join("directory.jsonl"))?; let mut provisioned = crate::server_config::Provisioned::from_parts(directory, Vec::new()); provisioned.apply_users(config).map_err(|error| { anyhow::anyhow!("server config world directory {}: {error}", dir.display()) @@ -1228,11 +1228,11 @@ pub fn seed_world_directory( /// The pull policy the live event-sync gate serves under (#5119): the server /// config's `[policy] pull_policy` when a config was loaded, else the code -/// default ([`crate::pull_policy::PullPolicy::Open`]), so a `serve` without +/// default ([`id_events::pull_policy::PullPolicy::Open`]), so a `serve` without /// `--server-config` behaves exactly as before. #[cfg(feature = "world")] -fn serve_pull_policy(started: Option<&StartedServerConfig>) -> crate::pull_policy::PullPolicy { - started.map_or(crate::pull_policy::PullPolicy::Open, |started| { +fn serve_pull_policy(started: Option<&StartedServerConfig>) -> id_events::pull_policy::PullPolicy { + started.map_or(id_events::pull_policy::PullPolicy::Open, |started| { started.config.pull_policy() }) } @@ -1240,11 +1240,11 @@ fn serve_pull_policy(started: Option<&StartedServerConfig>) -> crate::pull_polic /// The freshness window seitan admission serves under (#8487): the loaded /// server config's `[policy] freshness_window_seconds`, resolved through /// [`crate::server_config::ServerConfig::freshness`], when a config was -/// loaded, else [`crate::seitan::DEFAULT_WINDOW`] — so a `serve` without +/// loaded, else [`id_directory::seitan::DEFAULT_WINDOW`] — so a `serve` without /// `--server-config` behaves exactly as before. #[cfg(feature = "world")] fn serve_freshness_window(started: Option<&StartedServerConfig>) -> std::time::Duration { - started.map_or(crate::seitan::DEFAULT_WINDOW, |started| { + started.map_or(id_directory::seitan::DEFAULT_WINDOW, |started| { started.config.freshness().window() }) } @@ -1257,17 +1257,17 @@ fn serve_freshness_window(started: Option<&StartedServerConfig>) -> std::time::D /// production. #[cfg(feature = "world")] fn world_protocol_for( - hub: crate::world_hub::WorldHub, + hub: id_worlds::world_hub::WorldHub, local_node: [u8; 32], started: Option<&StartedServerConfig>, -) -> crate::world_net::WorldProtocol { +) -> id_worlds::world_net::WorldProtocol { match started { - Some(started) => crate::world_net::WorldProtocol::with_budgets( + Some(started) => id_worlds::world_net::WorldProtocol::with_budgets( hub, local_node, started.config.budgets().clone(), ), - None => crate::world_net::WorldProtocol::with_local_node(hub, local_node), + None => id_worlds::world_net::WorldProtocol::with_local_node(hub, local_node), } } @@ -1404,7 +1404,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { } #[cfg(not(feature = "world"))] { - crate::pull_policy::PullPolicy::Open + id_events::pull_policy::PullPolicy::Open } }; // #2145: resolve the web listener set once, before any startup work, @@ -1468,17 +1468,17 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let store = open_store(ephemeral).await?; let store_handle = store.as_store(); - let mut builder = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let mut builder = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(key.clone()); if !no_mdns { builder = builder.address_lookup(MdnsAddressLookup::builder()); } - let dht_policy = crate::dht::DhtPolicy::from_server(dht); + let dht_policy = id_sync::dht::DhtPolicy::from_server(dht); #[cfg(feature = "dht")] if dht_policy.is_on() { - builder = crate::dht::with_lookup(&dht_policy, builder, crate::dht::mainline()); + builder = id_sync::dht::with_lookup(&dht_policy, builder, id_sync::dht::mainline()); } #[cfg(not(feature = "dht"))] if dht_policy.is_on() { @@ -1501,16 +1501,16 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { if no_relay { info!("serve startup: relays disabled (--no-relay), skipping home-relay wait"); } else { - match crate::connectivity::await_home_relay( + match id_core::connectivity::await_home_relay( &endpoint, - crate::connectivity::HOME_RELAY_DEADLINE, + id_core::connectivity::HOME_RELAY_DEADLINE, ) .await { Ok(()) => info!("serve startup: home relay connected"), Err(e) => warn!( "serve startup: proceeding without a home relay after {:?}: {e:#}", - crate::connectivity::HOME_RELAY_DEADLINE, + id_core::connectivity::HOME_RELAY_DEADLINE, ), } } @@ -1551,7 +1551,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // allows them only from nodes the access policy lets write. let blobs = BlobsProtocol::new( &store_handle, - Some(crate::access::blobs_events(access.clone())), + Some(id_core::access::blobs_events(access.clone())), ); // The node's own event store, shared between the web layer and /id-range-sync/1 @@ -1564,10 +1564,10 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // it unconditionally would change the local CLI's access to the directory // while serve runs. #[cfg(feature = "web")] - let event_events: Option>> = if web { + let event_events: Option>> = if web { let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); - let events_dir = identity_db_path.with_file_name(crate::local_events::DIR_NAME); - let events = crate::local_events::LocalEvents::open( + let events_dir = identity_db_path.with_file_name(id_events::local_events::DIR_NAME); + let events = id_events::local_events::LocalEvents::open( &events_dir, p2panda_core::SigningKey::from_bytes(&key.to_bytes()), )?; @@ -1580,14 +1580,14 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // bridge. The default world opens now so a bad journal fails startup. #[cfg(feature = "world")] let world_hub = if world { - use crate::world_hub::{HubLimits, WorldHub}; - let runtime = crate::world_limits::RuntimeLimits::from_args(&world_runtime)?; + use id_worlds::world_hub::{HubLimits, WorldHub}; + let runtime = id_caps::world_limits::RuntimeLimits::from_args(&world_runtime)?; let server_caps = allowed_caps(world_allowed_caps.as_deref())?; let compiler = resolve_compiler(roc_bin, roc_platform)?; let trusted_module_keys = world_module_trust_keys .iter() .map(|encoded| { - let bytes = crate::world_session::decode_hex(encoded).ok_or_else(|| { + let bytes = id_worlds::world_session::decode_hex(encoded).ok_or_else(|| { anyhow::anyhow!("--world-module-trust-key must be 32-byte hex") })?; <[u8; 32]>::try_from(bytes.as_slice()) @@ -1691,9 +1691,9 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "world")] let abuse_handle = world_protocol .as_ref() - .map(crate::world_net::WorldProtocol::abuse_handle); + .map(id_worlds::world_net::WorldProtocol::abuse_handle); #[cfg(not(feature = "world"))] - let abuse_handle: Option>> = None; + let abuse_handle: Option>> = None; let meta = MetaProtocol::new( &store_handle, @@ -1705,7 +1705,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { ); #[cfg(all(feature = "world", feature = "ssh"))] - let (ssh_tunnel, ssh_tunnel_port) = crate::world_ssh::SshTunnelProtocol::deferred(); + let (ssh_tunnel, ssh_tunnel_port) = id_worlds::world_ssh::SshTunnelProtocol::deferred(); let router_builder = Router::builder(endpoint) .accept(META_ALPN, meta) .accept(BLOBS_ALPN, blobs) @@ -1714,10 +1714,10 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "web")] let router_builder = match &event_events { Some(events) => router_builder.accept( - crate::event_store::sync::ALPN, - crate::event_sync::EventSyncProtocol::with_gate( + id_events::event_store::sync::ALPN, + id_events::event_sync::EventSyncProtocol::with_gate( Arc::clone(events), - crate::event_sync::gate(event_sync_policy), + id_events::event_sync::gate(event_sync_policy), ), ), None => router_builder, @@ -1725,30 +1725,30 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "world")] let router_builder = match (world_hub.as_ref(), world_protocol) { (Some(hub), Some(world_protocol)) => router_builder - .accept(crate::world_net::WORLD_ALPN, world_protocol) + .accept(id_worlds::world_net::WORLD_ALPN, world_protocol) .accept( - crate::world_replication_net::REPLICATION_ALPN, - crate::world_replication_net::WorldReplicationProtocol::new( + id_worlds::world_replication_net::REPLICATION_ALPN, + id_worlds::world_replication_net::WorldReplicationProtocol::new( hub.clone(), ed25519_dalek::SigningKey::from_bytes(&key.to_bytes()), ), ) .accept( - crate::envelope_net::ENVELOPE_ALPN, - crate::envelope_net::EnvelopeProtocol::new(hub.clone()), + id_sync::envelope_net::ENVELOPE_ALPN, + id_sync::envelope_net::EnvelopeProtocol::new(hub.clone()), ) .accept( - crate::artifact::PUSH_ALPN, - crate::artifact::ArtifactPushProtocol::new(hub.clone()), + id_sync::artifact::PUSH_ALPN, + id_sync::artifact::ArtifactPushProtocol::new(hub.clone()), ) .accept( - crate::artifact::PULL_ALPN, - crate::artifact::ArtifactPullProtocol::new(hub.clone()), + id_sync::artifact::PULL_ALPN, + id_sync::artifact::ArtifactPullProtocol::new(hub.clone()), ), _ => router_builder, }; #[cfg(all(feature = "world", feature = "ssh"))] - let router_builder = router_builder.accept(crate::world_ssh::SSH_TUNNEL_ALPN, ssh_tunnel); + let router_builder = router_builder.accept(id_worlds::world_ssh::SSH_TUNNEL_ALPN, ssh_tunnel); let router = router_builder.spawn(); info!("serve startup: router spawned (#190 breadcrumb)"); @@ -1766,7 +1766,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // every pull is refused — and says so here rather than silently // serving open. let policy = event_sync_policy; - if policy == crate::pull_policy::PullPolicy::Members { + if policy == id_events::pull_policy::PullPolicy::Members { status!( "event sync: [policy] pull_policy=members — the local event store has no \ membership source, so every pull is refused (fail closed)" @@ -1774,16 +1774,16 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { } let endpoint = router.endpoint().clone(); let discovery = peer_discovery.clone(); - let gate = crate::event_sync::gate(policy); + let gate = id_events::event_sync::gate(policy); tokio::spawn(async move { loop { - tokio::time::sleep(crate::event_sync::SYNC_INTERVAL).await; + tokio::time::sleep(id_events::event_sync::SYNC_INTERVAL).await; for peer in discovery.peers() { let peer_id = peer.announcement.node_id; if peer_id == endpoint.id() { continue; } - match crate::event_sync::sync_with_peer(&endpoint, peer_id, &events, &gate) + match id_events::event_sync::sync_with_peer(&endpoint, peer_id, &events, &gate) .await { Ok(outcome) if outcome.sent + outcome.received > 0 => { @@ -1933,7 +1933,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "world")] let _ = ssh_tunnel_port.set(ssh_port); let host_key = - crate::world_ssh::load_or_create_host_key(crate::world_ssh::SSH_HOST_KEY_FILE) + id_worlds::world_ssh::load_or_create_host_key(id_worlds::world_ssh::SSH_HOST_KEY_FILE) .await?; Some(( listener, @@ -1986,7 +1986,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { if world { status!( "world {world_name}: enabled (iroh {})", - String::from_utf8_lossy(crate::world_net::WORLD_ALPN) + String::from_utf8_lossy(id_worlds::world_net::WORLD_ALPN) ); #[cfg(feature = "web")] if web { @@ -2008,10 +2008,10 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // opens exclusively); each listener's router is finished with // its own per-bind security. Do not initialize web persistence // when serving without the web interface. - let securities: Vec = web_listeners + let securities: Vec = web_listeners .iter() .map(|(listener_addr, _, _)| { - crate::web::WebSecurity::for_bind(listener_addr.ip(), web_token.clone(), &[]) + id_web::WebSecurity::for_bind(listener_addr.ip(), web_token.clone(), &[]) }) .collect(); // Each listener's #2146 content target, parallel to @@ -2034,13 +2034,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // accounts and its `AccountVerified` appends land in the // same journal. #[cfg(feature = "world")] - let seitan_state = crate::web::SeitanState::new( - crate::directory::Directory::open(&server_config_directory_path(&groups_log))?, + let seitan_state = id_web::SeitanState::new( + id_directory::directory::Directory::open(&server_config_directory_path(&groups_log))?, serve_freshness_window(started_server_config.as_ref()), ); #[cfg(not(feature = "world"))] - let seitan_state = crate::web::SeitanState::default(); - let web_routers = crate::web::web_routers( + let seitan_state = id_web::SeitanState::default(); + let web_routers = id_web::web_routers( store_handle.clone(), Some(peer_discovery.clone()), node_id.to_string(), @@ -2132,13 +2132,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { status!("world ssh: port {ssh_port} (ssh -p {ssh_port} @)"); status!( "world ssh host key: {}", - crate::world_ssh::host_key_fingerprint(&host_key) + id_worlds::world_ssh::host_key_fingerprint(&host_key) ); status!( "world ssh over iroh: `id world ssh-tunnel ` then `ssh -p 2222 @127.0.0.1`" ); tokio::spawn(async move { - if let Err(e) = crate::world_ssh::serve(listener, hub, host_key, blobs).await { + if let Err(e) = id_worlds::world_ssh::serve(listener, hub, host_key, blobs).await { tracing::error!("world ssh server error: {}", e); } }) @@ -2256,7 +2256,7 @@ impl GroupWarningWatcher { fn evaluate( &mut self, projection: &Projection, - events: &[crate::groups::Event], + events: &[id_events::groups::Event], now: u64, ) -> Vec<(Hash, Warning)> { let delta_readds = self.fold_new_events(projection, events); @@ -2311,7 +2311,7 @@ impl GroupWarningWatcher { times.push(now); } times.retain(|at| { - now.saturating_sub(*at) < crate::groups::warnings::CHURN_WINDOW_SECS + now.saturating_sub(*at) < id_groups::groups::warnings::CHURN_WINDOW_SECS }); } let readds = self.readds.get(group).cloned().unwrap_or_default(); @@ -2323,7 +2323,7 @@ impl GroupWarningWatcher { }; let warnings = self.evaluator.observe(&observation, now); if !warnings.is_empty() { - crate::groups::warnings::log(group, &warnings); + id_groups::groups::warnings::log(group, &warnings); fired.extend(warnings.into_iter().map(|warning| (*group, warning))); } } @@ -2343,7 +2343,7 @@ impl GroupWarningWatcher { fn fold_new_events( &mut self, projection: &Projection, - events: &[crate::groups::Event], + events: &[id_events::groups::Event], ) -> std::collections::BTreeMap { let mut counts = std::collections::BTreeMap::new(); let Some(cursor) = self.events_seen else { @@ -2360,14 +2360,14 @@ impl GroupWarningWatcher { let Some(group) = event.group else { continue; }; - let crate::groups::Body::Device(op) = &event.body else { + let id_events::groups::Body::Device(op) = &event.body else { continue; }; - if projection.outcome(&event.id) != Some(&crate::groups::Outcome::Applied) { + if projection.outcome(&event.id) != Some(&id_events::groups::Outcome::Applied) { continue; } match op { - crate::groups::DeviceOp::Add { device, .. } => { + id_events::groups::DeviceOp::Add { device, .. } => { let seen = self.seen_devices.entry(group).or_default(); let was_seen = seen.contains(device); seen.insert(*device); @@ -2377,7 +2377,7 @@ impl GroupWarningWatcher { } authorized.entry(*device).or_default().insert(event.author); } - crate::groups::DeviceOp::Revoke { device } => { + id_events::groups::DeviceOp::Revoke { device } => { // A revocation is account-scoped in the fold: it ends // only the revoking account's grant, so the device // stays authorized while another account's grant for @@ -2717,7 +2717,7 @@ async fn run_gossip_loop( // Try to connect and send ListPeers RPC let probe_result = tokio::time::timeout(PROBE_TIMEOUT, async { - let conn = crate::connectivity::connect(&endpoint, peer_id, META_ALPN).await?; + let conn = id_core::connectivity::connect(&endpoint, peer_id, META_ALPN).await?; let (mut send, mut recv) = conn.open_bi().await?; let req = postcard::to_allocvec(&MetaRequest::ListPeers)?; send.write_all(&req).await?; @@ -2757,10 +2757,10 @@ async fn run_gossip_loop( /// Select a deterministic, bounded round-robin batch from stale peers. fn select_stale_probe_batch( - stale: &[crate::discovery::PeerInfo], + stale: &[id_core::discovery::PeerInfo], after: Option, limit: usize, -) -> Vec { +) -> Vec { if stale.is_empty() || limit == 0 { return Vec::new(); } @@ -2789,9 +2789,9 @@ mod tests { use proptest::test_runner::{Config as ProptestConfig, TestCaseError}; use super::*; - fn stale_test_peer(seed: u8) -> crate::discovery::PeerInfo { + fn stale_test_peer(seed: u8) -> id_core::discovery::PeerInfo { let node_id = iroh_base::SecretKey::from_bytes(&[seed; 32]).public(); - crate::discovery::PeerInfo { + id_core::discovery::PeerInfo { announcement: PeerAnnouncement { node_id, name: None, @@ -2868,8 +2868,8 @@ mod tests { } fn group_log_with_members_at(path: &std::path::Path, members: usize) -> Hash { - use crate::groups::Role; - use crate::groups::actions::NewGroup; + use id_events::groups::Role; + use id_groups::groups::actions::NewGroup; let mut log = GroupLog::open(path).unwrap(); let author: GroupKey = [1; 32]; @@ -2897,7 +2897,7 @@ mod tests { use ed25519_dalek::SigningKey; use crate::chat_presence::Liveness; - use crate::groups::Role; + use id_events::groups::Role; let dir = serve_test_dir("presence-membership"); let path = dir.join(GROUPS_FILE_NAME); @@ -3004,7 +3004,7 @@ mod tests { let author: GroupKey = [1; 32]; for i in 96..128 { let member: GroupKey = [u8::try_from(i + 1).unwrap(); 32]; - log.add(author, group, member, crate::groups::Role::Read) + log.add(author, group, member, id_events::groups::Role::Read) .unwrap(); } } @@ -3022,7 +3022,7 @@ mod tests { #[test] fn serve_group_warnings_fire_on_device_readd_churn() { - use crate::groups::Role; + use id_events::groups::Role; let dir = serve_test_dir("churn"); let path = dir.join(GROUPS_FILE_NAME); @@ -3055,7 +3055,7 @@ mod tests { #[test] fn serve_group_warnings_fire_on_intra_interval_readd_churn() { - use crate::groups::Role; + use id_events::groups::Role; // #1847 regression: revoke + re-add cycles that complete inside // one evaluation interval are invisible to a net-set comparison. @@ -3088,7 +3088,7 @@ mod tests { #[test] fn serve_group_warnings_ignore_other_accounts_revoke_readd_cycles() { - use crate::groups::Role; + use id_events::groups::Role; // Codex review on PR #4035: a revocation is account-scoped in the // fold - it ends only the revoking account's grant. When account A @@ -3121,7 +3121,7 @@ mod tests { #[test] fn serve_group_warnings_count_churn_after_a_grant_owner_is_removed() { - use crate::groups::Role; + use id_events::groups::Role; // Codex review on PR #4035 (second round): when accounts A and B // both authorize a device and A is then removed from the group, @@ -3147,7 +3147,7 @@ mod tests { // Removing the other account leaves the device authorized // through the author alone; the evaluation reconciles the // tracked grant owners with the fold. Not itself a re-add. - log.remove(author, group, other, crate::groups::RemoveMode::Revoke) + log.remove(author, group, other, id_events::groups::RemoveMode::Revoke) .unwrap(); assert!(evaluate_group_warnings(&mut watcher, &path, 1_001).is_empty()); @@ -3169,7 +3169,7 @@ mod tests { fn test_the_server_ceiling_is_the_named_list_or_the_default_ceiling() { assert_eq!( allowed_caps(None).unwrap(), - crate::world_caps::default_ceiling_names() + id_caps::world_caps::default_ceiling_names() ); let named = ["time.now".to_owned(), "chat.say".to_owned()]; assert_eq!( @@ -3697,7 +3697,7 @@ mod tests { #[test] fn test_web_content_target_program_validates_world_name_rule() { // #5711: a program target names a world, so program()/parse - // reject every name crate::world_hub::validate_world_name + // reject every name id_worlds::world_hub::validate_world_name // rejects -- a target no world can bear could never resolve. for bad in [ "Arena", // uppercase @@ -3742,13 +3742,13 @@ mod tests { #[test] fn prop_program_target_acceptance_matches_world_name_oracle() { // Oracle (AGENTS.md testing doctrine; Codex finding on PR #8682): - // crate::world_hub::validate_world_name applied to the trimmed + // id_worlds::world_hub::validate_world_name applied to the trimmed // input decides acceptance. program() and parse("program:") // must agree with the oracle, and on acceptance the stored name // is exactly the trimmed input. fn check(input: &str) -> Result<(), TestCaseError> { let trimmed = input.trim(); - let oracle_ok = crate::world_hub::validate_world_name(trimmed).is_ok(); + let oracle_ok = id_worlds::world_hub::validate_world_name(trimmed).is_ok(); let program = WebContentTarget::program(input.to_owned()); prop_assert!( program.is_ok() == oracle_ok, @@ -3992,7 +3992,7 @@ mod tests { assert_eq!(seeded.users_created, 2); // The world's own directory now resolves both configured // accounts, as world_store::open_world would load it. - let directory = crate::directory::Directory::open(&world.join("directory.jsonl")).unwrap(); + let directory = id_directory::directory::Directory::open(&world.join("directory.jsonl")).unwrap(); assert!(directory.account(&id(1)).is_some()); assert!(directory.account(&id(2)).is_some()); drop(directory); @@ -4030,7 +4030,7 @@ mod tests { fn serve_pull_policy_defaults_to_open_without_a_config() { assert_eq!( serve_pull_policy(None), - crate::pull_policy::PullPolicy::Open + id_events::pull_policy::PullPolicy::Open ); } @@ -4045,7 +4045,7 @@ mod tests { let started = start_server_config(&path).unwrap(); assert_eq!( serve_pull_policy(Some(&started)), - crate::pull_policy::PullPolicy::Members + id_events::pull_policy::PullPolicy::Members ); let _ = std::fs::remove_dir_all(&dir); } @@ -4057,7 +4057,7 @@ mod tests { fn serve_freshness_window_defaults_without_a_config() { assert_eq!( serve_freshness_window(None), - crate::seitan::DEFAULT_WINDOW + id_directory::seitan::DEFAULT_WINDOW ); } @@ -4100,12 +4100,12 @@ mod tests { let started = start_server_config(&path).unwrap(); assert_ne!( *started.config.budgets(), - crate::abuse::BudgetPolicy::default() + id_core::abuse::BudgetPolicy::default() ); - let world = crate::world::WorldHandle::spawn( - crate::world::WorldCore::new("lobby", crate::world::WorldLimits::default()).unwrap(), + let world = id_worlds::world::WorldHandle::spawn( + id_worlds::world::WorldCore::new("lobby", id_worlds::world::WorldLimits::default()).unwrap(), ); - let service = crate::world_session::WorldService::new(world, None); + let service = id_worlds::world_session::WorldService::new(world, None); let protocol = world_protocol_for(service.into(), [9; 32], Some(&started)); let handle = protocol.abuse_handle(); let mut evaluator = handle.lock().unwrap(); @@ -4118,25 +4118,25 @@ mod tests { // A charge beyond the configured cap is refused as a budget // refusal (the frame is dropped; the peer is not disconnected). let refusal = evaluator - .check_budget(crate::abuse::Direction::Inbound, ann, None, 600, 1_000) + .check_budget(id_core::abuse::Direction::Inbound, ann, None, 600, 1_000) .unwrap_err(); - assert_eq!(refusal.reason, crate::abuse::RefusalReason::BudgetExhausted); + assert_eq!(refusal.reason, id_core::abuse::RefusalReason::BudgetExhausted); let _ = std::fs::remove_dir_all(&dir); } #[cfg(feature = "world")] #[tokio::test] async fn serve_world_protocol_defaults_budgets_without_config() { - let world = crate::world::WorldHandle::spawn( - crate::world::WorldCore::new("lobby", crate::world::WorldLimits::default()).unwrap(), + let world = id_worlds::world::WorldHandle::spawn( + id_worlds::world::WorldCore::new("lobby", id_worlds::world::WorldLimits::default()).unwrap(), ); - let service = crate::world_session::WorldService::new(world, None); + let service = id_worlds::world_session::WorldService::new(world, None); let protocol = world_protocol_for(service.into(), [9; 32], None); let handle = protocol.abuse_handle(); let evaluator = handle.lock().unwrap(); assert_eq!( evaluator.budgets(), - Some(&crate::abuse::BudgetPolicy::default()) + Some(&id_core::abuse::BudgetPolicy::default()) ); } diff --git a/pkgs/id/src/commands/tag.rs b/pkgs/id/crates/id-cli/src/commands/tag.rs similarity index 99% rename from pkgs/id/src/commands/tag.rs rename to pkgs/id/crates/id-cli/src/commands/tag.rs index f12f839a22..7549d61425 100644 --- a/pkgs/id/src/commands/tag.rs +++ b/pkgs/id/crates/id-cli/src/commands/tag.rs @@ -17,7 +17,7 @@ //! `--value-hex ` / `--value-file ` (`-` for stdin) for raw bytes. //! Output (`list`/`search`): UTF-8 values print as text; non-UTF-8 values print //! as ``, or as `0x` with `--hex`, or as lossy text with -//! `--binary`. Long values truncate at [`crate::tags::TAG_DISPLAY_MAX_BYTES`] +//! `--binary`. Long values truncate at [`id_store::tags::TAG_DISPLAY_MAX_BYTES`] //! on a character boundary unless `--no-truncate` is given. //! //! # Examples @@ -40,7 +40,7 @@ use crate::cli::TagCommand; use crate::commands::text::plain_field; use crate::meta_client::{MetaClient, MetaRequester, expect_ok}; use crate::protocol::{MetaRequest, MetaResponse, WireTag}; -use crate::tags::TAG_DISPLAY_MAX_BYTES; +use id_store::tags::TAG_DISPLAY_MAX_BYTES; /// Options controlling how tag values are displayed. #[derive(Debug, Clone, Default)] diff --git a/pkgs/id/src/commands/text.rs b/pkgs/id/crates/id-cli/src/commands/text.rs similarity index 97% rename from pkgs/id/src/commands/text.rs rename to pkgs/id/crates/id-cli/src/commands/text.rs index 3584cdedc7..43308fd6ad 100644 --- a/pkgs/id/src/commands/text.rs +++ b/pkgs/id/crates/id-cli/src/commands/text.rs @@ -1,7 +1,7 @@ //! Plain-text rendering of values that are not trusted to be row-safe. //! //! Peer names arrive over unsigned gossip, are stored verbatim by -//! [`crate::discovery::PeerDiscovery::update`] and are served verbatim by +//! [`id_core::discovery::PeerDiscovery::update`] and are served verbatim by //! `MetaRequest::ListPeers`, so a printer must never assume a name is free of //! bytes that mean something to its own format (#1613). //! @@ -55,8 +55,8 @@ //! `key=value` renderer (`crate::commands::group`) quote an affected value and //! render each offending character as `\uXXXX`, so the value stays complete //! and JSON-recoverable but no raw actor reaches the terminal. -//! * **Stripping sanitizers strip**: `crate::world::sanitize_display_name`, -//! `crate::world::sanitize_chat` and the SSH world's terminal gate drop both +//! * **Stripping sanitizers strip**: `id_worlds::world::sanitize_display_name`, +//! `id_worlds::world::sanitize_chat` and the SSH world's terminal gate drop both //! classes (chat keeps `ZWJ`/`ZWNJ` so legitimate emoji survive; the SSH //! gate keeps `LF`/`TAB` so terminal layout survives). //! * **Ingest validators refuse**: directory names/descriptions, invite @@ -105,7 +105,7 @@ fn push_unicode_escape(rendered: &mut String, c: char) { /// physical line and never contains a raw tab. /// /// ```rust -/// use id::commands::text::plain_field; +/// use id_cli::commands::text::plain_field; /// /// assert_eq!(plain_field("my-server"), "my-server"); /// assert_eq!(plain_field("my server"), "my server"); diff --git a/pkgs/id/src/commands/world.rs b/pkgs/id/crates/id-cli/src/commands/world.rs similarity index 92% rename from pkgs/id/src/commands/world.rs rename to pkgs/id/crates/id-cli/src/commands/world.rs index b263361f4d..1f77786a3e 100644 --- a/pkgs/id/src/commands/world.rs +++ b/pkgs/id/crates/id-cli/src/commands/world.rs @@ -1,6 +1,6 @@ //! `id world`: invite to and join multiplayer worlds hosted over Iroh. //! -//! Frames are the JSON protocol of [`crate::world_session`]. `join` prints +//! Frames are the JSON protocol of [`id_worlds::world_session`]. `join` prints //! every server frame as one JSON line, so a terminal, script, or other //! presentation can consume the same stream a browser would. @@ -15,12 +15,13 @@ use iroh::{ use rand::RngExt as _; use tokio::io::{AsyncBufReadExt, BufReader}; +use id_core::frames::{read_frame_from, write_frame_to}; +use id_worlds::world_net::WorldClient; + use crate::{ CLIENT_KEY_FILE, cli::{WorldCommand, WorldVia}, - frames::{read_frame_from, write_frame_to}, is_node_id, load_or_create_keypair, - world_net::WorldClient, }; /// Dial a world host and open one session. @@ -47,7 +48,7 @@ async fn connect( async fn client_endpoint(addrs: &[SocketAddr], no_relay: bool) -> Result { let key = load_or_create_keypair(CLIENT_KEY_FILE).await?; let endpoint = if addrs.is_empty() { - crate::connectivity::public_builder(crate::connectivity::RelayPolicy::from_no_relay( + id_core::connectivity::public_builder(id_core::connectivity::RelayPolicy::from_no_relay( no_relay, )) .secret_key(key) @@ -103,7 +104,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { uses, .. } = args; - crate::world_session::check_invite_bounds(expires_in, uses) + id_worlds::world_session::check_invite_bounds(expires_in, uses) .map_err(anyhow::Error::msg)?; let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; let result = client @@ -129,9 +130,9 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let metadata = std::fs::metadata(&module) .with_context(|| format!("read module metadata {}", module.display()))?; anyhow::ensure!( - metadata.len() <= crate::world_session::MAX_WORLD_MODULE_BYTES as u64, + metadata.len() <= id_worlds::world_session::MAX_WORLD_MODULE_BYTES as u64, "module exceeds {} bytes", - crate::world_session::MAX_WORLD_MODULE_BYTES + id_worlds::world_session::MAX_WORLD_MODULE_BYTES ); let wasm = std::fs::read(&module) .with_context(|| format!("read Wasm module {}", module.display()))?; @@ -179,7 +180,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let replica = Replica::start(dir.as_deref(), no_relay).await?; let timeout = std::time::Duration::from_secs(timeout_secs.max(1)); let (doc, records) = - crate::world_records::replicate(&replica.docs, &replica.blobs, &ticket, timeout) + id_worlds::world_records::replicate(&replica.docs, &replica.blobs, &ticket, timeout) .await?; println!("{}", serde_json::to_string_pretty(&records)?); if follow { @@ -190,7 +191,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { // Coalesce bursts, then re-read. tokio::time::sleep(std::time::Duration::from_millis(200)).await; let records = - crate::world_records::read_records(&doc, &replica.blobs).await?; + id_worlds::world_records::read_records(&doc, &replica.blobs).await?; println!("{}", serde_json::to_string_pretty(&records)?); } } @@ -254,18 +255,18 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { .await .with_context(|| format!("read {}", path.display()))?; anyhow::ensure!( - content.len() <= crate::world_compile::MAX_COMPILE_FILE_BYTES, + content.len() <= id_worlds::world_compile::MAX_COMPILE_FILE_BYTES, "{} exceeds {} bytes", path.display(), - crate::world_compile::MAX_COMPILE_FILE_BYTES + id_worlds::world_compile::MAX_COMPILE_FILE_BYTES ); sources.push((name, content)); } anyhow::ensure!( sources.iter().map(|(_, c)| c.len()).sum::() - <= crate::world_compile::MAX_COMPILE_TOTAL_BYTES, + <= id_worlds::world_compile::MAX_COMPILE_TOTAL_BYTES, "the sources exceed {} bytes", - crate::world_compile::MAX_COMPILE_TOTAL_BYTES + id_worlds::world_compile::MAX_COMPILE_TOTAL_BYTES ); let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; let seed = seed.unwrap_or_else(|| rand::rng().random::()); @@ -346,7 +347,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let admin_token = admin_token.context( "the admin token is needed to configure the world's execution profile", )?; - let profile = crate::world_limits::WorldExecutionProfile { + let profile = id_caps::world_limits::WorldExecutionProfile { wasm_fuel, wasm_memory_bytes, wasm_message_bytes, @@ -472,7 +473,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let text = std::fs::read_to_string(&path) .with_context(|| format!("read execution profile {}", path.display()))?; Some( - serde_json::from_str::( + serde_json::from_str::( &text, ) .with_context(|| { @@ -482,16 +483,16 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { } None => None, }; - let inputs = crate::world_doctor::DoctorInputs { + let inputs = id_worlds::world_doctor::DoctorInputs { roc_bin, roc_resolved: None, platform_dir, caps_ceiling: ceiling, profile, journal, - now_ms: Some(crate::time::unix_ms()), + now_ms: Some(id_core::time::unix_ms()), }; - let report = crate::world_doctor::run(&inputs); + let report = id_worlds::world_doctor::run(&inputs); if json { println!("{}", serde_json::to_string_pretty(&report)?); } else { @@ -516,11 +517,11 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let state = current_world_state(&client, &capability, None).await?; client.close(); endpoint.close().await; - print!("{}", crate::world_manifest::diff(&manifest, &state)); + print!("{}", id_caps::world_manifest::diff(&manifest, &state)); // Diff stays informational: report drift an apply would refuse. - if let Err(error) = crate::world_manifest::check_schedule_horizon( - &crate::world_manifest::plan(&manifest, &state), - crate::time::unix_ms(), + if let Err(error) = id_caps::world_manifest::check_schedule_horizon( + &id_caps::world_manifest::plan(&manifest, &state), + id_core::time::unix_ms(), ) { eprintln!("warning: `world apply` would refuse this manifest: {error:#}"); } @@ -541,11 +542,11 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { let manifest = parse_manifest_file(&file)?; let (endpoint, client) = connect(&node, &addrs, no_relay, world.as_deref()).await?; let state = current_world_state(&client, &capability, Some(&admin_token)).await?; - let steps = crate::world_manifest::plan(&manifest, &state); + let steps = id_caps::world_manifest::plan(&manifest, &state); // Refuse before any step runs: schedules apply last, so the // host's horizon refusal would otherwise abort a partial apply (#6486). if let Err(error) = - crate::world_manifest::check_schedule_horizon(&steps, crate::time::unix_ms()) + id_caps::world_manifest::check_schedule_horizon(&steps, id_core::time::unix_ms()) { client.close(); endpoint.close().await; @@ -558,7 +559,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { "{}", steps .iter() - .map(crate::world_manifest::ApplyStep::kind) + .map(id_caps::world_manifest::ApplyStep::kind) .collect::>() .join(", ") ); @@ -582,7 +583,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { Ok(()) } WorldCommand::Contract { check: None } => { - print!("{}", crate::shell_contract::SHELL_CONTRACT_JSON); + print!("{}", id_worlds::shell_contract::SHELL_CONTRACT_JSON); Ok(()) } WorldCommand::Contract { check: Some(path) } => { @@ -756,22 +757,22 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { for fixture_path in &fixtures { let text = String::from_utf8(read_bounded( fixture_path, - crate::world_fixture::MAX_FIXTURE_BYTES, + id_worlds::world_fixture::MAX_FIXTURE_BYTES, "fixture", )?) .context("the fixture is not UTF-8")?; - let fixture = crate::world_fixture::decode(&text)?; + let fixture = id_worlds::world_fixture::decode(&text)?; fixture_inputs.push((fixture_path.display().to_string(), fixture)); } if let Some(fuzz_path) = &fuzz { let text = String::from_utf8(read_bounded( fuzz_path, - crate::world_dev::MAX_FUZZ_DECL_BYTES as u64, + id_worlds::world_dev::MAX_FUZZ_DECL_BYTES as u64, "fuzz declaration", )?) .context("the fuzz declaration is not UTF-8")?; - let decl = crate::world_dev::parse_fuzz_decl(&text)?; - let report = crate::world_dev::run_dev_fuzz( + let decl = id_worlds::world_dev::parse_fuzz_decl(&text)?; + let report = id_worlds::world_dev::run_dev_fuzz( &dir, platform.as_deref(), roc.as_deref(), @@ -788,7 +789,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { return Ok(()); } if watch { - let report = crate::world_dev::run_dev_watch( + let report = id_worlds::world_dev::run_dev_watch( &dir, platform.as_deref(), roc.as_deref(), @@ -814,7 +815,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { } return Ok(()); } - let report = crate::world_dev::run_dev_once( + let report = id_worlds::world_dev::run_dev_once( &dir, platform.as_deref(), roc.as_deref(), @@ -858,9 +859,9 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { endpoint.close().await; let (default, worlds) = result?; if json { - let worlds: Vec = worlds + let worlds: Vec = worlds .into_iter() - .map(|(name, open, presence)| crate::world_hub::WorldInfo { + .map(|(name, open, presence)| id_worlds::world_hub::WorldInfo { name, open, presence, @@ -868,7 +869,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { .collect(); println!( "{}", - serde_json::to_string_pretty(&crate::world_hub::directory_json( + serde_json::to_string_pretty(&id_worlds::world_hub::directory_json( &worlds, &default ))? ); @@ -913,7 +914,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { "after": after, }); // The same routed bytes on every transport. - let first = crate::world_net::route_frame(&join, world.as_deref()); + let first = id_worlds::world_net::route_frame(&join, world.as_deref()); match via { WorldVia::Iroh => { if ssh_host_key.is_some() { @@ -964,7 +965,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { /// opening the journal for append. A torn final fragment (a crash /// mid-append, never acknowledged) is skipped, mirroring /// `FileJournal::open`; any other unparseable line is corruption. -fn read_world_journal(dir: &std::path::Path) -> Result> { +fn read_world_journal(dir: &std::path::Path) -> Result> { let path = dir.join("journal.jsonl"); let bytes = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?; let mut lines: Vec<&[u8]> = bytes.split(|byte| *byte == b'\n').collect(); @@ -980,7 +981,7 @@ fn read_world_journal(dir: &std::path::Path) -> Result Result { let entries = read_world_journal(dir)?; - let Some(crate::world::JournalEntry::Created { world_id, .. }) = entries.first() else { + let Some(id_worlds::world::JournalEntry::Created { world_id, .. }) = entries.first() else { bail!( "{} has no Created header", dir.join("journal.jsonl").display() @@ -1004,7 +1005,7 @@ fn world_provenance(dir: &std::path::Path) -> Result { }; let world_id = world_id.clone(); let forked = entries.iter().rev().find_map(|entry| match entry { - crate::world::JournalEntry::Forked { + id_worlds::world::JournalEntry::Forked { from_world_id, from_module_hash, template, @@ -1075,7 +1076,7 @@ fn fork_world_on_disk( .map(str::to_owned) .context("the destination directory has no name; pass --name")?, }; - crate::world_hub::validate_world_name(&to_world_id)?; + id_worlds::world_hub::validate_world_name(&to_world_id)?; if dir.exists() { anyhow::ensure!( std::fs::read_dir(dir)?.next().is_none(), @@ -1084,10 +1085,10 @@ fn fork_world_on_disk( ); } let from_world_id = world_provenance(source)?.world_id; - crate::world_store::fork_world( + id_worlds::world_store::fork_world( source, dir, - &crate::world_store::ForkSpec { + &id_worlds::world_store::ForkSpec { from_world_id, to_world_id, template, @@ -1111,7 +1112,7 @@ async fn join_over_ssh( json: bool, capability: &str, ) -> Result<()> { - use crate::world_ssh::{HostKeyCheck, SshTarget, connect_frames}; + use id_worlds::world_ssh::{HostKeyCheck, SshTarget, connect_frames}; let target: SshTarget = target.parse()?; let check = match ssh_host_key { Some(fingerprint) => HostKeyCheck::Fingerprint(fingerprint), @@ -1149,7 +1150,7 @@ async fn ssh_tunnel( let id: EndpointId = node.parse().context("parse node ID")?; let endpoint = client_endpoint(addrs, no_relay).await?; let addr = EndpointAddr::from_parts(id, addrs.iter().copied().map(TransportAddr::Ip)); - let conn = crate::connectivity::connect(&endpoint, addr, crate::world_ssh::SSH_TUNNEL_ALPN) + let conn = id_core::connectivity::connect(&endpoint, addr, id_worlds::world_ssh::SSH_TUNNEL_ALPN) .await .context("connect ssh tunnel")?; if stdio { @@ -1216,10 +1217,10 @@ async fn join_over_ssh( } /// Parse a `world.toml` file into a validated manifest. -fn parse_manifest_file(file: &std::path::Path) -> Result { +fn parse_manifest_file(file: &std::path::Path) -> Result { let text = std::fs::read_to_string(file) .with_context(|| format!("read world manifest {}", file.display()))?; - crate::world_manifest::parse(&text) + id_caps::world_manifest::parse(&text) } /// Fetch the current world state the manifest is compared against: the active @@ -1232,7 +1233,7 @@ async fn current_world_state( client: &WorldClient, capability: &str, admin_token: Option<&str>, -) -> Result { +) -> Result { // One fresh session per read: admin and query frames are served one // operation per stream, so sequencing these reads on one stream would // talk to a session the host already finished. @@ -1241,10 +1242,10 @@ async fn current_world_state( .await? .info_details(capability) .await?; - let caps: crate::world_caps::CapsReport = + let caps: id_caps::world_caps::CapsReport = serde_json::from_value(client.fresh_session().await?.caps(capability).await?) .context("host returned a malformed capability report")?; - let profile: crate::world_limits::WorldExecutionProfile = serde_json::from_value( + let profile: id_caps::world_limits::WorldExecutionProfile = serde_json::from_value( client .fresh_session() .await? @@ -1256,13 +1257,13 @@ async fn current_world_state( // fold turns a report equal to the default ceiling into None, which // means the default ceiling — the one meaning of None for a live // ceiling (#6817, #838). - let ceiling = crate::world_manifest::fold_reported_ceiling(caps.ceiling.clone()); + let ceiling = id_caps::world_manifest::fold_reported_ceiling(caps.ceiling.clone()); let (seed, schedules) = client .fresh_session() .await? .manifest_state(admin_token, Some(capability)) .await?; - Ok(crate::world_manifest::WorldState { + Ok(id_caps::world_manifest::WorldState { module_hash: info.active_module_hash, seed: seed.unwrap_or(0), grants: caps.granted, @@ -1277,8 +1278,8 @@ async fn current_world_state( /// so every step counts toward the "applied N step(s)" summary (#818). The /// predicate stays explicit per kind so a future reported-only step cannot /// silently claim credit: list it here only when its apply path lands. -fn step_is_applied(step: &crate::world_manifest::ApplyStep) -> bool { - use crate::world_manifest::ApplyStep; +fn step_is_applied(step: &id_caps::world_manifest::ApplyStep) -> bool { + use id_caps::world_manifest::ApplyStep; matches!( step, ApplyStep::InstallModule { .. } @@ -1316,9 +1317,9 @@ fn step_is_applied(step: &crate::world_manifest::ApplyStep) -> bool { /// and schedule additions last. The sort is stable, so steps of the /// same kind keep their plan order. fn ordered_steps<'a>( - steps: &'a [crate::world_manifest::ApplyStep], -) -> Vec<&'a crate::world_manifest::ApplyStep> { - use crate::world_manifest::ApplyStep; + steps: &'a [id_caps::world_manifest::ApplyStep], +) -> Vec<&'a id_caps::world_manifest::ApplyStep> { + use id_caps::world_manifest::ApplyStep; fn rank(step: &ApplyStep) -> u8 { match step { ApplyStep::CancelSchedule { .. } => 0, @@ -1338,15 +1339,15 @@ async fn apply_steps( client: &WorldClient, admin_token: &str, capability: &str, - steps: &[crate::world_manifest::ApplyStep], + steps: &[id_caps::world_manifest::ApplyStep], ) -> Result { - use crate::world_manifest::ApplyStep; + use id_caps::world_manifest::ApplyStep; let applied = steps.iter().filter(|step| step_is_applied(step)).count(); let ordered = ordered_steps(steps); for step in ordered { match step { ApplyStep::SetGrants { grants } => { - let current: crate::world_caps::CapsReport = + let current: id_caps::world_caps::CapsReport = serde_json::from_value(client.fresh_session().await?.caps(capability).await?) .context("host returned a malformed capability report")?; let to_revoke: Vec = current @@ -1374,7 +1375,7 @@ async fn apply_steps( // names on the wire; providers with an `Excluded` manifest // default stay out until a ceiling names them (#838). let names = ceiling.clone().unwrap_or_else(|| { - crate::world_caps::default_ceiling_names() + id_caps::world_caps::default_ceiling_names() .into_iter() .collect::>() }); @@ -1470,18 +1471,18 @@ fn read_compile_sources(source: &std::path::Path) -> Result Result<()> { let (endpoint, mut client) = connect(node, addrs, no_relay, world).await?; - let result = crate::world_fixture::record(&mut client, admin_token).await; + let result = id_worlds::world_fixture::record(&mut client, admin_token).await; client.close(); endpoint.close().await; let fixture = result?; - let text = crate::world_fixture::encode(&fixture.header, &fixture.events); + let text = id_worlds::world_fixture::encode(&fixture.header, &fixture.events); match out { Some(path) => { tokio::fs::write(path, &text) @@ -1544,23 +1545,23 @@ fn replay_fixture( seed: u64, allow_partial: bool, ) -> Result<()> { - use crate::world_fixture::Verdict; + use id_worlds::world_fixture::Verdict; let wasm = read_bounded( module, - crate::world_session::MAX_WORLD_MODULE_BYTES as u64, + id_worlds::world_session::MAX_WORLD_MODULE_BYTES as u64, "module", )?; let text = String::from_utf8(read_bounded( fixture_path, - crate::world_fixture::MAX_FIXTURE_BYTES, + id_worlds::world_fixture::MAX_FIXTURE_BYTES, "fixture", )?) .context("the fixture is not UTF-8")?; - let fixture = crate::world_fixture::decode(&text)?; - crate::world_fixture::check_module(&fixture.header, &wasm)?; - let runner = crate::sandbox::Sandbox::compile(&wasm, crate::sandbox::SandboxLimits::default())?; - let replayed = crate::world_fixture::replay(&runner, seed, &fixture, allow_partial)?; + let fixture = id_worlds::world_fixture::decode(&text)?; + id_worlds::world_fixture::check_module(&fixture.header, &wasm)?; + let runner = id_worlds::sandbox::Sandbox::compile(&wasm, id_worlds::sandbox::SandboxLimits::default())?; + let replayed = id_worlds::world_fixture::replay(&runner, seed, &fixture, allow_partial)?; match &replayed.verdict { Verdict::Match => println!("records match"), Verdict::Mismatch => println!("records differ"), @@ -1610,19 +1611,19 @@ fn verify_fixture( ) -> Result<()> { let wasm = read_bounded( module, - crate::world_session::MAX_WORLD_MODULE_BYTES as u64, + id_worlds::world_session::MAX_WORLD_MODULE_BYTES as u64, "module", )?; let text = String::from_utf8(read_bounded( fixture_path, - crate::world_fixture::MAX_FIXTURE_BYTES, + id_worlds::world_fixture::MAX_FIXTURE_BYTES, "fixture", )?) .context("the fixture is not UTF-8")?; - let fixture = crate::world_fixture::decode(&text)?; - crate::world_fixture::check_module(&fixture.header, &wasm)?; - let runner = crate::sandbox::Sandbox::compile(&wasm, crate::sandbox::SandboxLimits::default())?; - let verification = crate::world_fixture::verify(&runner, seed, &fixture, allow_partial)?; + let fixture = id_worlds::world_fixture::decode(&text)?; + id_worlds::world_fixture::check_module(&fixture.header, &wasm)?; + let runner = id_worlds::sandbox::Sandbox::compile(&wasm, id_worlds::sandbox::SandboxLimits::default())?; + let verification = id_worlds::world_fixture::verify(&runner, seed, &fixture, allow_partial)?; match &verification.divergence { None => println!( "records verify (two replays agree at all {} steps)", @@ -1635,7 +1636,7 @@ fn verify_fixture( header_verdict_line(&verification.first.verdict) ); if verification.divergence.is_none() - && verification.first.verdict == crate::world_fixture::Verdict::Mismatch + && verification.first.verdict == id_worlds::world_fixture::Verdict::Mismatch { println!("the two replays agree with each other but mismatch the fixture header"); } @@ -1650,7 +1651,7 @@ fn verify_fixture( if let Some(divergence) = &verification.divergence { bail!("the two replays diverge: {divergence}"); } - if verification.first.verdict == crate::world_fixture::Verdict::Mismatch { + if verification.first.verdict == id_worlds::world_fixture::Verdict::Mismatch { bail!("the replayed records differ from the fixture's"); } Ok(()) @@ -1659,8 +1660,8 @@ fn verify_fixture( /// Render a replay's verdict against the fixture header exactly as /// `replay_fixture` renders it (#1539). #[cfg(feature = "sandbox")] -fn header_verdict_line(verdict: &crate::world_fixture::Verdict) -> String { - use crate::world_fixture::Verdict; +fn header_verdict_line(verdict: &id_worlds::world_fixture::Verdict) -> String { + use id_worlds::world_fixture::Verdict; match verdict { Verdict::Match => "records match".to_owned(), Verdict::Mismatch => "records differ".to_owned(), @@ -1690,12 +1691,12 @@ fn measure_module( inputs: &[String], viewport: Option<(u16, u16)>, ) -> Result { - use crate::sandbox::{GuestCall, Sandbox, SandboxLimits}; + use id_worlds::sandbox::{GuestCall, Sandbox, SandboxLimits}; let events = inputs .iter() .map(|hex| { - crate::world_session::decode_hex(hex) + id_worlds::world_session::decode_hex(hex) .with_context(|| format!("`{hex}` is not an even-length hex string")) }) .collect::>>()?; @@ -1937,7 +1938,7 @@ impl Replica { .bind() .await? } else { - crate::connectivity::public_builder(crate::connectivity::RelayPolicy::from_no_relay( + id_core::connectivity::public_builder(id_core::connectivity::RelayPolicy::from_no_relay( no_relay, )) .secret_key(key) @@ -1980,7 +1981,7 @@ async fn terminal_probe_replay(command_mode: bool) -> Vec { if command_mode { return Vec::new(); } - match tokio::task::spawn_blocking(crate::world_terminal::probe_local_tty).await { + match tokio::task::spawn_blocking(id_worlds::world_terminal::probe_local_tty).await { Ok(Some(outcome)) => outcome.replay, Ok(None) | Err(_) => Vec::new(), } @@ -2101,8 +2102,8 @@ where /// /// Fails on an unreadable transcript, or with every violation listed. fn check_contract(text: &str) -> Result { - let contract = crate::shell_contract::ShellContract::embedded().map_err(anyhow::Error::msg)?; - let violations = crate::shell_contract::check_transcript(contract, text)?; + let contract = id_worlds::shell_contract::ShellContract::embedded().map_err(anyhow::Error::msg)?; + let violations = id_worlds::shell_contract::check_transcript(contract, text)?; let frames = text.lines().filter(|line| !line.trim().is_empty()).count(); if violations.is_empty() { return Ok(format!( @@ -2141,12 +2142,12 @@ fn local_transcript_record(level: &str, message: &str) -> serde_json::Value { serde_json::json!({"type": "local", "level": level, "message": message}) } -/// Map one line of the shared grammar ([`crate::world_line`]) to what the +/// Map one line of the shared grammar ([`id_worlds::world_line`]) to what the /// pump does. Every frame it sends is in the shell contract's joined phase; /// the commands that need the host's own store (`/documents`) or that the /// pump already does (`/logs`) are answered locally. fn pump_command(line: &str, capability: &str) -> PumpLine { - use crate::world_line::{WorldLine, parse_line}; + use id_worlds::world_line::{WorldLine, parse_line}; let Some(action) = parse_line(line) else { return PumpLine::Quit; }; @@ -2189,7 +2190,7 @@ fn pump_command(line: &str, capability: &str) -> PumpLine { /// Map the plain `id world join` input line, validating `/input` while /// leaving every other line as chat. fn pump_plain(line: &str) -> PumpLine { - use crate::world_line::{WorldLine, parse_line}; + use id_worlds::world_line::{WorldLine, parse_line}; if line != "/input" && !line.starts_with("/input ") { return PumpLine::Send(serde_json::json!({"type": "chat", "text": line})); @@ -2274,7 +2275,7 @@ mod tests { /// step counts toward the applied summary. #[test] fn every_step_kind_counts_as_applied() { - use crate::world_manifest::ApplyStep; + use id_caps::world_manifest::ApplyStep; let steps = [ ApplyStep::InstallModule { hash: Some("abc".to_owned()), @@ -2284,7 +2285,7 @@ mod tests { ApplyStep::SetGrants { grants: vec![] }, ApplyStep::SetCeiling { ceiling: None }, ApplyStep::SetProfile { - profile: crate::world_limits::WorldExecutionProfile::default(), + profile: id_caps::world_limits::WorldExecutionProfile::default(), }, ApplyStep::ScheduleAt { id: "round".to_owned(), @@ -2304,7 +2305,7 @@ mod tests { /// compiles or installs under them. #[test] fn apply_steps_run_in_reachability_order() { - use crate::world_manifest::ApplyStep; + use id_caps::world_manifest::ApplyStep; let steps = [ ApplyStep::ScheduleAt { id: "new".to_owned(), @@ -2318,7 +2319,7 @@ mod tests { ApplyStep::SetCeiling { ceiling: None }, ApplyStep::SetGrants { grants: vec![] }, ApplyStep::SetProfile { - profile: crate::world_limits::WorldExecutionProfile::default(), + profile: id_caps::world_limits::WorldExecutionProfile::default(), }, ApplyStep::CancelSchedule { id: "old".to_owned(), @@ -2366,11 +2367,11 @@ mod tests { /// The shared line grammar maps the same line to the same action on the /// join pump as it does on the SSH command mode (both call - /// [`crate::world_line::parse_line`]); this asserts the pump's mapping, + /// [`id_worlds::world_line::parse_line`]); this asserts the pump's mapping, /// and that every frame it sends is in the shell contract. #[test] fn the_pump_command_mode_maps_the_shared_grammar_to_contract_frames() { - use crate::shell_contract::{Phase, ShellContract}; + use id_worlds::shell_contract::{Phase, ShellContract}; let send = |line: &str| match pump_command(line, "cap") { PumpLine::Send(frame) => frame, other => panic!("{line}: {other:?}"), @@ -2522,7 +2523,7 @@ mod tests { #[cfg(feature = "sandbox")] #[test] fn measure_reports_fuel_per_call_kind_for_a_checked_in_module() { - let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let wasm = include_bytes!("../../../../examples/roc-counter/counter.wasm"); let report = super::measure_module(wasm, 7, &["696e63".to_owned()], Some((40, 20))).unwrap(); assert_eq!(report["module_bytes"], wasm.len()); diff --git a/pkgs/id/src/commands/writer_set.rs b/pkgs/id/crates/id-cli/src/commands/writer_set.rs similarity index 92% rename from pkgs/id/src/commands/writer_set.rs rename to pkgs/id/crates/id-cli/src/commands/writer_set.rs index 98f2dfab02..a458f98022 100644 --- a/pkgs/id/src/commands/writer_set.rs +++ b/pkgs/id/crates/id-cli/src/commands/writer_set.rs @@ -2,9 +2,9 @@ //! the event store (writer-set spec §§4–5; issue #6690). //! //! This module parses the arguments, acts on the event store, and prints. -//! The rules are the library's ([`crate::event_store`]): a stored set is read +//! The rules are the library's ([`id_events::event_store`]): a stored set is read //! back from its retained body and checked against its publishing header, -//! the projection is [`crate::idset::view::expand_set`] over snapshots the +//! the projection is [`id_events::idset::view::expand_set`] over snapshots the //! store builds from its resolved group state, and discovery is //! subject-first — filter by the set's scope, each hit carrying the set and //! the writers it expands to. @@ -27,12 +27,12 @@ use serde_json::{Value, json}; use crate::cli::WriterSetCommand; use crate::commands::doc::{print_action, print_rows}; use crate::commands::group::hex; -use crate::event_store::{DiscoveredWriterSet, EventStore}; -use crate::groups::log::hash_from_hex; -use crate::idset::WriterSet; -use crate::idset::view::ExpandedWriters; -use crate::local_events::DIR_NAME; -use crate::waiting::WaitingLimits; +use id_events::event_store::{DiscoveredWriterSet, EventStore}; +use id_groups::groups::log::hash_from_hex; +use id_events::idset::WriterSet; +use id_events::idset::view::ExpandedWriters; +use id_events::local_events::DIR_NAME; +use id_core::waiting::WaitingLimits; /// Opens the event store the command reads, at `path` or the default /// events directory. diff --git a/pkgs/id/crates/id-cli/src/fileops_tests.rs b/pkgs/id/crates/id-cli/src/fileops_tests.rs new file mode 100644 index 0000000000..a267556ddb --- /dev/null +++ b/pkgs/id/crates/id-cli/src/fileops_tests.rs @@ -0,0 +1,652 @@ +//! File-operations behaviour tests, moved with `crate::local` in +//! split step 7b (#4411): they exercise `id_sync::fileops` through +//! the in-process `LocalNode` harness that now lives in id-cli. + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod replacement_metadata_tests { + use crate::local::LocalNode; + use id_store::tags::Tag; + + use id_sync::fileops::*; + + async fn put(node: &LocalNode, name: &str, content: &[u8]) { + let guard = node + .blobs() + .add_bytes(content.to_vec()) + .temp_tag() + .await + .unwrap(); + node.ops().put(name, guard.hash()).await.unwrap(); + } + + async fn set_tag(node: &LocalNode, subject: &str, key: &str, value: &str) { + node.tags() + .set_tag( + &node.tags().global, + subject.as_bytes(), + key.as_bytes(), + Some(value.as_bytes()), + b"", + ) + .await + .unwrap(); + } + + async fn set_singleton(node: &LocalNode, subject: &str, key: &str, value: &str) { + node.tags() + .set_singleton( + &node.tags().global, + subject.as_bytes(), + key.as_bytes(), + Some(value.as_bytes()), + b"", + ) + .await + .unwrap(); + } + + async fn tags_of(node: &LocalNode, subject: &str) -> Vec { + node.tags() + .get_tags(&node.tags().global, subject.as_bytes()) + .await + .unwrap() + } + + fn values(tags: &[Tag], key: &str) -> Vec> { + tags.iter() + .filter(|tag| tag.key.as_bytes() == key.as_bytes()) + .filter_map(|tag| tag.value.as_ref().map(|value| value.as_bytes().to_vec())) + .collect() + } + + fn has_tag(tags: &[Tag], key: &str, value: &str) -> bool { + values(tags, key) + .iter() + .any(|found| found == value.as_bytes()) + } + + fn assert_single_value(tags: &[Tag], key: &str, value: &str) { + assert_eq!( + values(tags, key), + vec![value.as_bytes().to_vec()], + "{tags:?}" + ); + } + + fn assert_archive_identity(tags: &[Tag], archive: &str) { + assert_single_value(tags, "name", archive); + assert_single_value(tags, "file", archive.rsplit('/').next().unwrap_or(archive)); + assert!( + values(tags, "path").is_empty(), + "archive inherited path: {tags:?}" + ); + } + + async fn seed_replacement_pair(node: &LocalNode) { + put(node, "source.txt", b"new content").await; + put(node, "destination.txt", b"replaced content").await; + + set_tag(node, "source.txt", "shared", "source-value").await; + set_tag(node, "source.txt", "source-only", "source-metadata").await; + set_singleton(node, "source.txt", "created", "source-created").await; + set_singleton(node, "source.txt", "modified", "source-modified").await; + + set_tag(node, "destination.txt", "shared", "replaced-value").await; + set_tag( + node, + "destination.txt", + "replaced-only", + "replaced-metadata", + ) + .await; + set_tag( + node, + "destination.txt", + "archive.previous", + "earlier.archive.7", + ) + .await; + set_tag(node, "destination.txt", "path", "old/source/path.txt").await; + set_singleton(node, "destination.txt", "created", "replaced-created").await; + set_singleton(node, "destination.txt", "modified", "replaced-modified").await; + } + + fn assert_replaced_metadata_on_archive(tags: &[Tag], archive: &str) { + assert!(has_tag(tags, "shared", "replaced-value"), "{tags:?}"); + assert!( + has_tag(tags, "replaced-only", "replaced-metadata"), + "{tags:?}" + ); + assert!( + has_tag(tags, "archive.previous", "earlier.archive.7"), + "{tags:?}" + ); + assert_single_value(tags, "created", "replaced-created"); + assert_single_value(tags, "modified", "replaced-modified"); + assert_archive_identity(tags, archive); + assert!(!has_tag(tags, "name", "destination.txt"), "{tags:?}"); + assert!(!has_tag(tags, "file", "destination.txt"), "{tags:?}"); + } + + #[tokio::test] + async fn rename_with_archive_preserves_source_provenance_on_archive_alias() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "before.txt", b"original").await; + set_singleton(&node, "before.txt", "origin", "node-alpha").await; + set_singleton(&node, "before.txt", "created", "1700000000").await; + + // The source's recorded provenance, exactly as stored. + let source_tags = tags_of(&node, "before.txt").await; + assert_single_value(&source_tags, "origin", "node-alpha"); + let source_created = values(&source_tags, "created"); + assert!(!source_created.is_empty(), "{source_tags:?}"); + + let rename = node + .ops() + .rename("before.txt", "after.txt", true) + .await + .unwrap(); + let archive = rename.archived_original.unwrap(); + + // #5383: the archive alias carries the source's recorded + // provenance, not an unknown origin. + let archive_tags = tags_of(&node, &archive).await; + assert_single_value(&archive_tags, "origin", "node-alpha"); + assert_eq!(values(&archive_tags, "created"), source_created); + + // The live name keeps its provenance too (tags move with it). + let live_tags = tags_of(&node, "after.txt").await; + assert_single_value(&live_tags, "origin", "node-alpha"); + assert_eq!(values(&live_tags, "created"), source_created); + + node.shutdown().await.unwrap(); + } + + async fn rename_onto_existing_moves_replaced_metadata_and_refreshes_archive_identity() { + let node = LocalNode::open(true).await.unwrap(); + seed_replacement_pair(&node).await; + + let outcome = node + .ops() + .rename("source.txt", "destination.txt", false) + .await + .unwrap(); + let archive = outcome.archived_replaced.expect("replaced file archived"); + + let archived = tags_of(&node, &archive).await; + assert_replaced_metadata_on_archive(&archived, &archive); + + let destination = tags_of(&node, "destination.txt").await; + assert!( + has_tag(&destination, "shared", "source-value"), + "{destination:?}" + ); + assert!( + has_tag(&destination, "source-only", "source-metadata"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "shared", "replaced-value"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "replaced-only", "replaced-metadata"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "archive.previous", "earlier.archive.7"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "path", "old/source/path.txt"), + "{destination:?}" + ); + assert_single_value(&destination, "created", "source-created"); + assert_single_value(&destination, "modified", "source-modified"); + assert_single_value(&destination, "name", "destination.txt"); + assert_single_value(&destination, "file", "destination.txt"); + assert!( + has_tag(&destination, "archive.replace", &archive), + "{destination:?}" + ); + + node.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn copy_onto_existing_moves_replaced_metadata_and_keeps_single_fresh_stamps() { + let node = LocalNode::open(true).await.unwrap(); + seed_replacement_pair(&node).await; + + let outcome = node + .ops() + .copy("source.txt", "destination.txt") + .await + .unwrap(); + let archive = outcome.archived_replaced.expect("replaced file archived"); + + let archived = tags_of(&node, &archive).await; + assert_replaced_metadata_on_archive(&archived, &archive); + + let destination = tags_of(&node, "destination.txt").await; + assert!( + has_tag(&destination, "shared", "source-value"), + "{destination:?}" + ); + assert!( + has_tag(&destination, "source-only", "source-metadata"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "shared", "replaced-value"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "replaced-only", "replaced-metadata"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "archive.previous", "earlier.archive.7"), + "{destination:?}" + ); + assert!( + !has_tag(&destination, "path", "old/source/path.txt"), + "{destination:?}" + ); + assert_eq!(values(&destination, "created").len(), 1, "{destination:?}"); + assert_eq!(values(&destination, "modified").len(), 1, "{destination:?}"); + assert_single_value(&destination, "name", "destination.txt"); + assert_single_value(&destination, "file", "destination.txt"); + assert!( + has_tag(&destination, "archive.replace", &archive), + "{destination:?}" + ); + + let source = tags_of(&node, "source.txt").await; + assert!(has_tag(&source, "shared", "source-value"), "{source:?}"); + assert!( + has_tag(&source, "source-only", "source-metadata"), + "{source:?}" + ); + + node.shutdown().await.unwrap(); + } + + /// A copy must not become a second owner of the source's archives + /// (#4761): deleting the copy must leave the source's archives intact. + #[tokio::test] + async fn copy_does_not_inherit_source_archive_refs() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "source.txt", b"source content").await; + put(&node, "other.txt", b"other content").await; + // Renaming onto source.txt with archiving enabled adds both + // archive.rename and archive.replace refs to the live source. + let rename_outcome = node + .ops() + .rename("other.txt", "source.txt", true) + .await + .unwrap(); + let source_archives = [ + rename_outcome + .archived_original + .expect("original source archived"), + rename_outcome + .archived_replaced + .expect("replaced source archived"), + ]; + let source_before = tags_of(&node, "source.txt").await; + assert!( + has_tag(&source_before, "archive.rename", &source_archives[0]), + "{source_before:?}" + ); + assert!( + has_tag(&source_before, "archive.replace", &source_archives[1]), + "{source_before:?}" + ); + + node.ops().copy("source.txt", "copy.txt").await.unwrap(); + let copy_tags = tags_of(&node, "copy.txt").await; + assert!( + values(©_tags, "archive.rename").is_empty(), + "copy inherited archive.rename refs: {copy_tags:?}" + ); + assert!( + values(©_tags, "archive.replace").is_empty(), + "copy inherited archive.replace refs: {copy_tags:?}" + ); + + // Deleting the copy must not touch the source's archive. + let delete_outcome = node.ops().delete("copy.txt").await.unwrap(); + assert_eq!( + delete_outcome.archives_removed, 0, + "copy delete removed archives" + ); + for archive in &source_archives { + assert!( + !tags_of(&node, archive).await.is_empty(), + "source archive {archive} removed by copy delete" + ); + } + let source_after = tags_of(&node, "source.txt").await; + assert!( + has_tag(&source_after, "archive.rename", &source_archives[0]), + "source lost its archive.rename ref: {source_after:?}" + ); + assert!( + has_tag(&source_after, "archive.replace", &source_archives[1]), + "source lost its archive ref: {source_after:?}" + ); + + node.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn rename_onto_existing_preserves_replaced_tag_payloads() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "source.txt", b"new content").await; + put(&node, "destination.txt", b"replaced content").await; + + // A tag with a non-empty entry payload, as written for legacy + // links by migrate_legacy_meta (payload carries the link target). + let payload: &[u8] = b"hash:0123abcd"; + node.tags() + .set_tag( + &node.tags().global, + b"destination.txt", + b"link", + Some(b"target"), + payload, + ) + .await + .unwrap(); + let before = tags_of(&node, "destination.txt").await; + let before = before + .iter() + .find(|tag| tag.key.as_bytes() == b"link") + .expect("link tag seeded"); + assert_eq!(before.len as usize, payload.len(), "{before:?}"); + let before_hash = before.hash; + + let outcome = node + .ops() + .rename("source.txt", "destination.txt", false) + .await + .unwrap(); + let archive = outcome.archived_replaced.expect("replaced file archived"); + + let archived = tags_of(&node, &archive).await; + let moved = archived + .iter() + .find(|tag| tag.key.as_bytes() == b"link") + .expect("link tag moved to archive"); + assert_eq!(moved.hash, before_hash, "{moved:?}"); + assert_eq!(moved.len as usize, payload.len(), "{moved:?}"); + + node.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn delete_removes_archived_replaced_metadata() { + let node = LocalNode::open(true).await.unwrap(); + seed_replacement_pair(&node).await; + + let outcome = node + .ops() + .rename("source.txt", "destination.txt", false) + .await + .unwrap(); + let archive = outcome.archived_replaced.expect("replaced file archived"); + assert!( + !tags_of(&node, &archive).await.is_empty(), + "archive carries the replaced file's metadata before delete" + ); + + let deleted = node.ops().delete("destination.txt").await.unwrap(); + assert_eq!(deleted.archives_removed, 1); + assert!( + tags_of(&node, &archive).await.is_empty(), + "archive metadata removed with the archive" + ); + + node.shutdown().await.unwrap(); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod delete_tests { + use crate::local::LocalNode; + + use id_sync::fileops::*; + + async fn put(node: &LocalNode, name: &str, data: &[u8]) { + let guard = node + .blobs() + .add_bytes(data.to_vec()) + .temp_tag() + .await + .unwrap(); + node.ops().put(name, guard.hash()).await.unwrap(); + } + + #[tokio::test] + async fn delete_after_archived_rename_removes_previous_name_archive() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "before", b"original").await; + + let rename = node.ops().rename("before", "after", true).await.unwrap(); + let archive = rename.archived_original.unwrap(); + assert!(node.blobs().tags().get(&archive).await.unwrap().is_some()); + + let deleted = node.ops().delete("after").await.unwrap(); + + assert_eq!(deleted.archives_removed, 1); + assert!(node.blobs().tags().get(&archive).await.unwrap().is_none()); + node.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn delete_after_repeated_replacements_removes_all_replaced_archives() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "A", b"original").await; + + put(&node, "replacement-1", b"first replacement").await; + let first = node + .ops() + .rename("replacement-1", "A", false) + .await + .unwrap() + .archived_replaced + .unwrap(); + put(&node, "replacement-2", b"second replacement").await; + let second = node + .ops() + .rename("replacement-2", "A", false) + .await + .unwrap() + .archived_replaced + .unwrap(); + assert_ne!(first, second); + + node.ops().rename("A", "B", false).await.unwrap(); + let deleted = node.ops().delete("B").await.unwrap(); + + assert_eq!(deleted.archives_removed, 2); + assert!(node.blobs().tags().get(&first).await.unwrap().is_none()); + assert!(node.blobs().tags().get(&second).await.unwrap().is_none()); + node.shutdown().await.unwrap(); + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod name_rule_tests { + use crate::local::LocalNode; + + use id_sync::fileops::*; + + async fn put(node: &LocalNode, name: &str, data: &[u8]) { + let guard = node + .blobs() + .add_bytes(data.to_vec()) + .temp_tag() + .await + .unwrap(); + node.ops().put(name, guard.hash()).await.unwrap(); + } + + fn assert_invalid(name: &str) { + assert!( + matches!( + FileOps::validate_name(name), + Err(FileOpError::InvalidName(_)) + ), + "{name:?} must be refused as InvalidName" + ); + } + + /// Padding and empty components are refused by the one canonical rule + /// (#4102 / design #4766 Phase 3), so a name can never be stored in a + /// form that rename/copy would normalise away. + #[test] + fn refuses_padding_and_empty_components() { + for name in [ + " report.txt", + "report.txt ", + "\treport.txt", + "report.txt\n", + "a//b", + "a/", + "a\\", + "a//b/c", + "a/b/", + ] { + assert_invalid(name); + } + } + + /// The pre-existing refusals stay in place: rooted names, drive + /// prefixes, and `.`/`..` traversal components. + #[test] + fn preserves_traversal_refusals() { + for name in [ + "/etc/passwd", + "\\windows", + "C:file.txt", + ".", + "..", + "a/./b", + "a/../b", + ] { + assert_invalid(name); + } + assert!(matches!( + FileOps::validate_name(" "), + Err(FileOpError::EmptyName) + )); + // Padding is a refusal, but interior spaces in a name are not. + assert!(FileOps::validate_name("my report.txt").is_ok()); + assert!(FileOps::validate_name("a/b").is_ok()); + } + + /// A padded `put` cannot create an untargetable twin, and a padded + /// rename/copy target is refused instead of being silently trimmed. + #[tokio::test] + async fn padded_names_cannot_create_twins() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "report.txt", b"report").await; + + let guard = node + .blobs() + .add_bytes(b"report".to_vec()) + .temp_tag() + .await + .unwrap(); + assert!(matches!( + node.ops().put(" report.txt", guard.hash()).await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get(" report.txt") + .await + .unwrap() + .is_none() + ); + assert!( + node.blobs() + .tags() + .get("report.txt") + .await + .unwrap() + .is_some() + ); + + assert!(matches!( + node.ops().rename("report.txt", "other.txt ", false).await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get("other.txt") + .await + .unwrap() + .is_none() + ); + + assert!(matches!( + node.ops().copy("report.txt", " copy.txt").await, + Err(FileOpError::InvalidName(_)) + )); + assert!( + node.blobs() + .tags() + .get(" copy.txt") + .await + .unwrap() + .is_none() + ); + assert!(node.blobs().tags().get("copy.txt").await.unwrap().is_none()); + + node.shutdown().await.unwrap(); + } + + /// Empty components are refused at put and at rename/copy targets alike. + #[tokio::test] + async fn empty_components_refused_across_put_rename_copy() { + let node = LocalNode::open(true).await.unwrap(); + put(&node, "a/b", b"body").await; + + let guard = node + .blobs() + .add_bytes(b"body".to_vec()) + .temp_tag() + .await + .unwrap(); + for name in ["a//b", "a/", "a\\"] { + assert!(matches!( + node.ops().put(name, guard.hash()).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(matches!( + node.ops().rename("a/b", name, false).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(matches!( + node.ops().copy("a/b", name).await, + Err(FileOpError::InvalidName(_)) + )); + assert!(node.blobs().tags().get(name).await.unwrap().is_none()); + } + + // The canonical source is untouched and ordinary names still work. + assert!(node.blobs().tags().get("a/b").await.unwrap().is_some()); + node.ops().copy("a/b", "a/c").await.unwrap(); + assert!(node.blobs().tags().get("a/c").await.unwrap().is_some()); + + node.shutdown().await.unwrap(); + } +} diff --git a/pkgs/id/src/helpers.rs b/pkgs/id/crates/id-cli/src/helpers.rs similarity index 99% rename from pkgs/id/src/helpers.rs rename to pkgs/id/crates/id-cli/src/helpers.rs index 36d978d6bb..90c6aba225 100644 --- a/pkgs/id/src/helpers.rs +++ b/pkgs/id/crates/id-cli/src/helpers.rs @@ -11,7 +11,7 @@ //! Many commands support a `source:destination` syntax for renaming: //! //! ```rust -//! use id::helpers::parse_put_spec; +//! use id_cli::helpers::parse_put_spec; //! //! // Simple path (no rename) //! let (path, name) = parse_put_spec("file.txt"); @@ -53,7 +53,7 @@ use anyhow::{Result, bail}; /// # Examples /// /// ```rust -/// use id::helpers::parse_put_spec; +/// use id_cli::helpers::parse_put_spec; /// /// // Simple path /// let (path, name) = parse_put_spec("file.txt"); @@ -106,7 +106,7 @@ pub fn parse_put_spec(spec: &str) -> (&str, Option<&str>) { /// # Examples /// /// ```rust -/// use id::helpers::parse_get_spec; +/// use id_cli::helpers::parse_get_spec; /// /// // Simple source /// let (source, output) = parse_get_spec("config.json"); @@ -192,7 +192,7 @@ fn format_match_cli(m: &TaggedMatch, format: &str) -> String { /// # Example /// /// ```rust,ignore -/// use id::helpers::print_matches_cli; +/// use id_cli::helpers::print_matches_cli; /// /// // Print results grouped by query /// print_matches_cli(&matches, "group"); diff --git a/pkgs/id/crates/id-cli/src/lib.rs b/pkgs/id/crates/id-cli/src/lib.rs new file mode 100644 index 0000000000..50c6cf5acd --- /dev/null +++ b/pkgs/id/crates/id-cli/src/lib.rs @@ -0,0 +1,231 @@ +//! The id command-line application layer: `cli` (argument parsing), +//! `commands` (subcommand implementations), `repl`, and +//! `server_config`, plus the support modules they share (`local`, +//! `protocol`, `meta_client`, `helpers`, `chat_presence`, +//! `app_manifest`, `match_audit`, `aliases`, `publications`). +//! +//! Extracted from the facade in split step 7b (#4411). The facade +//! re-exports these modules at their historical `id::` paths and +//! keeps `main.rs`; this crate depends only downward on the member +//! crates (id-core, id-caps, id-store, id-events, id-groups, +//! id-sync, id-worlds, id-directory, and id-web under `web`). + +use anyhow::Result; +use std::path::PathBuf; + +pub mod aliases; +pub mod app_manifest; +pub mod chat_presence; +pub mod cli; +pub mod commands; +pub mod helpers; +pub mod local; +pub mod match_audit; +pub mod meta_client; +mod peer_announcement; +pub mod protocol; +pub mod publications; +pub mod publications_runtime; +pub mod repl; +pub mod server_config; + +#[cfg(test)] +mod fileops_tests; + +// Root convenience re-exports, mirroring the layer the facade root +// provided when these modules lived there: moved code imports +// several of these as `crate::`. +pub use id_core::{CLIENT_KEY_FILE, KEY_FILE, SERVE_LOCK}; +pub use id_core::{is_format_char, is_node_id}; +pub use id_store::STORE_PATH; +pub use id_sync::protocol::META_ALPN; + +pub use crate::cli::{Cli, Command, KeyCommand, TagCommand}; +pub use crate::commands::{ + PeekOptions, PeersOptions, ReplContext, ReplContextInner, SearchOptions, ServeInfo, + ServeOptions, cmd_find, cmd_find_matches, cmd_get_local, cmd_get_multi, cmd_get_one, + cmd_get_one_remote, cmd_gethash, cmd_id, cmd_list, cmd_list_remote, cmd_migrate_tags, + cmd_peek, cmd_peers, cmd_put_hash, cmd_put_local_file, cmd_put_local_stdin, + cmd_put_multi, cmd_put_one, cmd_put_one_remote, cmd_search, cmd_serve, cmd_show, + cmd_tag, create_local_client_endpoint, create_serve_lock, get_serve_info, + is_process_alive, remove_serve_lock, +}; +pub use crate::helpers::{ + download_output_path, parse_get_spec, parse_put_spec, print_match_cli, print_match_repl, + print_matches_cli, +}; +pub use crate::protocol::{ + FindMatch, MatchKind, MetaProtocol, MetaRequest, MetaResponse, TaggedMatch, +}; +pub use crate::protocol::match_kind; +pub use crate::repl::run_repl; +pub use id_core::discovery::{ + ANNOUNCE_INTERVAL, DEFAULT_TOPIC, DEFAULT_TOPIC_SECRET, Defaults, MAX_PEER_NAME_BYTES, + MAX_PEERS, PeerAnnouncement, PeerDiscovery, PeerInfo, ResolvedConfig, + STALE_CHECK_INTERVAL, STALE_THRESHOLD, defaults, parse_defaults, resolve_config, +}; +pub use id_store::store::{StoreType, load_or_create_keypair, open_store}; + +// Root helpers moved from the facade root in step 7b: they serve +// the command layer (get/put/repl) and are re-exported by the facade +// at their historical `id::` paths. + +/// Parses items from stdin, splitting on common delimiters. +/// +/// Reads all content from stdin and splits it on newlines, tabs, or commas. +/// Empty items and whitespace-only items are filtered out. This is useful +/// for batch operations where file lists are piped in. +/// +/// # Returns +/// +/// A vector of trimmed, non-empty strings. +/// +/// # Example +/// +/// ```bash +/// # From command line: +/// echo "file1.txt,file2.txt,file3.txt" | id put --stdin +/// ``` +/// +/// ```rust,no_run +/// use id_cli::parse_stdin_items; +/// +/// // If stdin contains "a.txt\nb.txt\tc.txt,d.txt" +/// let items = parse_stdin_items().unwrap(); +/// // items = ["a.txt", "b.txt", "c.txt", "d.txt"] +/// ``` +pub fn parse_stdin_items() -> Result> { + use std::io::Read; + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + Ok(input + .split(['\n', '\t', ',']) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned) + .collect()) +} + +/// Reads input data from a file path or stdin. +/// +/// If the input is "-", reads from stdin. Otherwise, reads from the specified +/// file path. This is a common pattern for CLI tools that accept either a +/// file or piped input. +/// +/// # Arguments +/// +/// * `input` - Either "-" for stdin, or a file path +/// +/// # Returns +/// +/// The raw bytes read from the source. +/// +/// # Example +/// +/// ```rust,ignore +/// use id_cli::read_input; +/// +/// # async fn example() -> anyhow::Result<()> { +/// // Read from file +/// let data = read_input("myfile.txt").await?; +/// +/// // Read from stdin (when input is "-") +/// let stdin_data = read_input("-").await?; +/// # Ok(()) +/// # } +/// ``` +pub async fn read_input(input: &str) -> Result> { + use std::io::Read; + use tokio::fs as afs; + + if input == "-" { + let mut data = Vec::new(); + std::io::stdin().read_to_end(&mut data)?; + Ok(data) + } else { + Ok(afs::read(input).await?) + } +} + +/// Exports a blob to a file or stdout. +/// +/// Retrieves the blob data by hash from the store and writes it to the +/// specified output. If output is "-", writes to stdout. Otherwise, +/// writes to a file at the given path (converting to absolute if needed). +/// +/// # Arguments +/// +/// * `store` - The blob store to read from +/// * `hash` - The hash of the blob to export +/// * `output` - Either "-" for stdout, or a file path +/// +/// # Example +/// +/// ```rust,ignore +/// use id_cli::{open_store, export_blob}; +/// use iroh_blobs::Hash; +/// +/// # async fn example() -> anyhow::Result<()> { +/// let store_type = open_store(false).await?; +/// let store = store_type.as_store(); +/// +/// // Export to file +/// let hash: Hash = "abc123...".parse()?; +/// export_blob(&store, hash, "output.txt").await?; +/// +/// // Export to stdout +/// export_blob(&store, hash, "-").await?; +/// # Ok(()) +/// # } +/// ``` +pub async fn export_blob( + store: &iroh_blobs::api::Store, + hash: iroh_blobs::Hash, + output: &str, +) -> Result<()> { + use std::io::Write; + + if output == "-" { + let data = store.blobs().get_bytes(hash).await?; + std::io::stdout().write_all(&data)?; + } else { + let path = to_absolute(&PathBuf::from(output))?; + store.blobs().export(hash, &path).await?; + eprintln!("exported: {} -> {}", hash, path.display()); + } + Ok(()) +} + +/// Converts a potentially relative path to an absolute path. +/// +/// If the path is already absolute, it is returned unchanged. Otherwise, +/// it is joined with the current working directory. +/// +/// # Arguments +/// +/// * `path` - The path to convert +/// +/// # Returns +/// +/// The absolute path, or an error if the current directory cannot be determined. +/// +/// # Example +/// +/// ```rust +/// use std::path::PathBuf; +/// use id_cli::to_absolute; +/// +/// let abs = to_absolute(&PathBuf::from("/already/absolute")).unwrap(); +/// assert_eq!(abs, PathBuf::from("/already/absolute")); +/// +/// // Relative paths are joined with the current directory +/// let rel = to_absolute(&PathBuf::from("relative/path")).unwrap(); +/// assert!(rel.is_absolute()); +/// ``` +pub fn to_absolute(path: &PathBuf) -> Result { + if path.is_absolute() { + Ok(path.clone()) + } else { + Ok(std::env::current_dir()?.join(path)) + } +} diff --git a/pkgs/id/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs similarity index 96% rename from pkgs/id/src/local.rs rename to pkgs/id/crates/id-cli/src/local.rs index 7458b694f2..cea1ca11f8 100644 --- a/pkgs/id/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -30,12 +30,14 @@ use iroh_blobs::{ALPN as BLOBS_ALPN, BlobsProtocol, api::Store}; use iroh_docs::protocol::Docs; use iroh_gossip::net::Gossip; -use crate::access::AccessPolicy; -use crate::fileops::FileOps; +use id_core::access::AccessPolicy; +use id_sync::fileops::FileOps; use crate::protocol::{MetaProtocol, MetaRequest, MetaResponse}; -use crate::store::{StoreType, load_or_create_keypair, open_store}; -use crate::tags::TagStore; -use crate::{KEY_FILE, META_ALPN, STORE_PATH, access::blobs_events}; +use id_store::store::{StoreType, load_or_create_keypair, open_store}; +use id_store::tags::TagStore; +use id_core::access::blobs_events; + +use crate::{KEY_FILE, META_ALPN, STORE_PATH}; /// A network-less node exposing the blob store and the metadata [`TagStore`]. #[derive(Debug)] diff --git a/pkgs/id/src/match_audit.rs b/pkgs/id/crates/id-cli/src/match_audit.rs similarity index 99% rename from pkgs/id/src/match_audit.rs rename to pkgs/id/crates/id-cli/src/match_audit.rs index a5a6098fbc..b96b926fe8 100644 --- a/pkgs/id/src/match_audit.rs +++ b/pkgs/id/crates/id-cli/src/match_audit.rs @@ -10,9 +10,9 @@ use p2panda_core::{Hash, SigningKey as IdSigningKey}; use serde::{Deserialize, Serialize}; #[cfg(feature = "sandbox")] -use crate::sandbox::{Sandbox, SandboxLimits}; +use id_worlds::sandbox::{Sandbox, SandboxLimits}; #[cfg(feature = "world")] -use crate::world::signed::MoveChain; +use id_worlds::world::signed::MoveChain; const HEADER_DOMAIN: &[u8] = b"id.match-audit.v0/header\0"; const ENTRY_DOMAIN: &[u8] = b"id.match-audit.v0/entry\0"; @@ -22,7 +22,7 @@ const FOOTER_DOMAIN: &[u8] = b"id.match-audit.v0/footer\0"; pub const TIC_TAC_TOE_REFERENCE_ID: &str = "id.apps.tic-tac-toe/reference-v0"; /// Bundled Wasm build used by the reference exporter and verifier. pub const TIC_TAC_TOE_REFERENCE_WASM: &[u8] = - include_bytes!("../apps/tic-tac-toe/program/tic-tac-toe.wasm"); + include_bytes!("../../../apps/tic-tac-toe/program/tic-tac-toe.wasm"); const TIC_TAC_TOE_RULES_V0: &[u8] = b"tic-tac-toe/v0; cells=0..8; x-first; invalid-occupied-post-win-ignored"; /// RNG identifier for the reference match's eight-byte little-endian seed. @@ -675,7 +675,7 @@ pub fn export_tic_tac_toe_reference( let tick = u64::try_from(index + 1) .map_err(|_| AuditErrorV0::ReferenceRuntime("tick overflow".to_owned()))?; let payload = vec![b'0' + cell]; - let signed_move = crate::world::signed::sign_move( + let signed_move = id_worlds::world::signed::sign_move( player_keys[slot], &header.world_id, move_sequences[slot], @@ -875,7 +875,7 @@ fn replay_tic_tac_toe(log: &MatchLogV0) -> TechnicalVerdictV0 { } #[cfg(feature = "sandbox")] -fn snapshot(world: &mut crate::sandbox::WorldInstance) -> Option> { +fn snapshot(world: &mut id_worlds::sandbox::WorldInstance) -> Option> { world.snapshot().ok().flatten() } @@ -1062,7 +1062,7 @@ mod tests { .map(|key| sign_header(key, &header).unwrap()) .collect(); let signed_move = - crate::world::signed::sign_move(&players[0], &header.world_id, 0, None, b"place:0") + id_worlds::world::signed::sign_move(&players[0], &header.world_id, 0, None, b"place:0") .unwrap() .bytes; let first = chain_entry( diff --git a/pkgs/id/src/meta_client.rs b/pkgs/id/crates/id-cli/src/meta_client.rs similarity index 90% rename from pkgs/id/src/meta_client.rs rename to pkgs/id/crates/id-cli/src/meta_client.rs index c1d20d6a15..ad4c15a016 100644 --- a/pkgs/id/src/meta_client.rs +++ b/pkgs/id/crates/id-cli/src/meta_client.rs @@ -46,7 +46,7 @@ impl MetaClient { pub async fn open() -> Result { if let Some(info) = get_serve_info().await { let (endpoint, addr) = create_local_client_endpoint(&info).await?; - let conn = crate::connectivity::connect(&endpoint, addr, META_ALPN).await?; + let conn = id_core::connectivity::connect(&endpoint, addr, META_ALPN).await?; Ok(Self::Remote { endpoint, conn }) } else { Ok(Self::Local(Box::new(LocalNode::open(false).await?))) @@ -56,14 +56,14 @@ impl MetaClient { /// Connect to a specific peer by node ID. pub async fn connect_node(node: EndpointId, no_relay: bool) -> Result { let key = load_or_create_keypair(CLIENT_KEY_FILE).await?; - let endpoint = crate::connectivity::public_builder( - crate::connectivity::RelayPolicy::from_no_relay(no_relay), + let endpoint = id_core::connectivity::public_builder( + id_core::connectivity::RelayPolicy::from_no_relay(no_relay), ) .secret_key(key) .bind() .await?; let conn = - crate::connectivity::connect(&endpoint, EndpointAddr::from(node), META_ALPN).await?; + id_core::connectivity::connect(&endpoint, EndpointAddr::from(node), META_ALPN).await?; Ok(Self::Remote { endpoint, conn }) } diff --git a/pkgs/id/src/peer_announcement.rs b/pkgs/id/crates/id-cli/src/peer_announcement.rs similarity index 99% rename from pkgs/id/src/peer_announcement.rs rename to pkgs/id/crates/id-cli/src/peer_announcement.rs index 02386eeaeb..23ac5dd7d8 100644 --- a/pkgs/id/src/peer_announcement.rs +++ b/pkgs/id/crates/id-cli/src/peer_announcement.rs @@ -3,7 +3,7 @@ use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use serde::{Deserialize, Serialize}; -use crate::discovery::{MAX_PEER_NAME_BYTES, PeerAnnouncement}; +use id_core::discovery::{MAX_PEER_NAME_BYTES, PeerAnnouncement}; /// Magic prefix separates authenticated v2 gossip frames from legacy postcard payloads. pub(crate) const PEER_ANNOUNCEMENT_FRAME_MAGIC: &[u8] = b"id-peer-announcement/v2\n"; diff --git a/pkgs/id/src/protocol.rs b/pkgs/id/crates/id-cli/src/protocol.rs similarity index 99% rename from pkgs/id/src/protocol.rs rename to pkgs/id/crates/id-cli/src/protocol.rs index c07ed45425..a4a1970157 100644 --- a/pkgs/id/src/protocol.rs +++ b/pkgs/id/crates/id-cli/src/protocol.rs @@ -30,7 +30,7 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use crate::access::AccessPolicy; + use id_core::access::AccessPolicy; fn eid(n: u8) -> EndpointId { iroh_base::SecretKey::from_bytes(&[n; 32]).public() diff --git a/pkgs/id/src/publications.rs b/pkgs/id/crates/id-cli/src/publications.rs similarity index 99% rename from pkgs/id/src/publications.rs rename to pkgs/id/crates/id-cli/src/publications.rs index eeb5fd7005..74585dd9e5 100644 --- a/pkgs/id/src/publications.rs +++ b/pkgs/id/crates/id-cli/src/publications.rs @@ -57,8 +57,8 @@ use serde::{Deserialize, Serialize}; /// Explorer route prefixes a path mount can shadow, as path prefixes /// at segment granularity. Parameterised routes are named by their /// static prefix (`/edit/{*name}` is `/edit`). Grounded in -/// `crate::web::routes` / `crate::web::explore` / -/// `crate::web::world_ws` at the time of writing; the registry takes +/// `id_web::routes` / `id_web::explore` / +/// `id_web::world_ws` at the time of writing; the registry takes /// the route list as a parameter everywhere it matters, so callers /// with a fresher list can pass their own — this constant is the /// fallback for the boot path, which runs before any router exists. diff --git a/pkgs/id/src/publications_runtime.rs b/pkgs/id/crates/id-cli/src/publications_runtime.rs similarity index 100% rename from pkgs/id/src/publications_runtime.rs rename to pkgs/id/crates/id-cli/src/publications_runtime.rs diff --git a/pkgs/id/src/repl/input.rs b/pkgs/id/crates/id-cli/src/repl/input.rs similarity index 100% rename from pkgs/id/src/repl/input.rs rename to pkgs/id/crates/id-cli/src/repl/input.rs diff --git a/pkgs/id/src/repl/mod.rs b/pkgs/id/crates/id-cli/src/repl/mod.rs similarity index 100% rename from pkgs/id/src/repl/mod.rs rename to pkgs/id/crates/id-cli/src/repl/mod.rs diff --git a/pkgs/id/src/repl/runner.rs b/pkgs/id/crates/id-cli/src/repl/runner.rs similarity index 100% rename from pkgs/id/src/repl/runner.rs rename to pkgs/id/crates/id-cli/src/repl/runner.rs diff --git a/pkgs/id/src/server_config/mod.rs b/pkgs/id/crates/id-cli/src/server_config/mod.rs similarity index 95% rename from pkgs/id/src/server_config/mod.rs rename to pkgs/id/crates/id-cli/src/server_config/mod.rs index 8fca99e147..63c4aac0ef 100644 --- a/pkgs/id/src/server_config/mod.rs +++ b/pkgs/id/crates/id-cli/src/server_config/mod.rs @@ -30,7 +30,7 @@ //! pull_policy = "open" # who may pull a world's events: "open" or "members" (P6.5) //! # (the operator block list is not config: it lives in the //! # event store's `blocks` table, #2245, and gates read it -//! # from there via `crate::event_store::BlockList`) +//! # from there via `id_events::event_store::BlockList`) //! //! [budgets] # absent: the #2247 code defaults apply //! app_inbound_bytes_per_hour = 21474836480 # 20 GiB/h app-wide inbound @@ -57,9 +57,9 @@ use std::time::Duration; use p2panda_core::Hash; -use crate::groups::{Key, Projection, Role}; -use crate::pull_policy::PullPolicy; -use crate::seitan::Freshness; +use id_events::groups::{Key, Projection, Role}; +use id_events::pull_policy::PullPolicy; +use id_directory::seitan::Freshness; /// Re-exported so `crate::server_config::Object` keeps working: the type now lives in /// [`crate::aliases`] so alias display builds without the `world` feature. @@ -76,7 +76,7 @@ pub struct ServerConfig { policy: PolicySpec, /// The #2247 rolling-window abuse budgets. Defaults apply when /// the file has no `[budgets]` table. - budgets: crate::abuse::BudgetPolicy, + budgets: id_core::abuse::BudgetPolicy, /// Every local key, for users and groups alike. Keys are unique within the config. names: BTreeMap, /// The primary alias of each object that has one. @@ -112,7 +112,7 @@ pub struct GroupSpec { /// as before: a five-minute window and open pull. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PolicySpec { - /// The server-level freshness window. `None` keeps [`crate::seitan::DEFAULT_WINDOW`]. + /// The server-level freshness window. `None` keeps [`id_directory::seitan::DEFAULT_WINDOW`]. pub freshness_window: Option, /// Who may pull a world's events from this server. pub pull_policy: PullPolicy, @@ -229,7 +229,7 @@ impl ServerConfig { /// anything it does not set. Per-counterparty override rows are /// already resolved to endpoint IDs. #[must_use] - pub const fn budgets(&self) -> &crate::abuse::BudgetPolicy { + pub const fn budgets(&self) -> &id_core::abuse::BudgetPolicy { &self.budgets } diff --git a/pkgs/id/src/server_config/parse.rs b/pkgs/id/crates/id-cli/src/server_config/parse.rs similarity index 97% rename from pkgs/id/src/server_config/parse.rs rename to pkgs/id/crates/id-cli/src/server_config/parse.rs index f5661f71a3..ee76471d94 100644 --- a/pkgs/id/src/server_config/parse.rs +++ b/pkgs/id/crates/id-cli/src/server_config/parse.rs @@ -12,9 +12,9 @@ use serde::Deserialize; use thiserror::Error; use super::{CreateRule, GroupSpec, Object, PolicySpec, ServerConfig, UserSpec}; -use crate::directory::{hex_to_array, normalize_key}; -use crate::groups::{Key, Role}; -use crate::pull_policy::PullPolicy; +use id_directory::directory::{hex_to_array, normalize_key}; +use id_events::groups::{Key, Role}; +use id_events::pull_policy::PullPolicy; /// Why a config was refused. #[derive(Clone, Debug, PartialEq, Eq, Error)] @@ -329,7 +329,7 @@ pub(super) fn parse(text: &str) -> Result { Some(raw_policy) => policy_spec(raw_policy)?, }; let budgets = match &raw.budgets { - None => crate::abuse::BudgetPolicy::default(), + None => id_core::abuse::BudgetPolicy::default(), Some(raw_budgets) => budget_policy(raw_budgets, &names)?, }; Ok(ServerConfig { @@ -351,9 +351,9 @@ pub(super) fn parse(text: &str) -> Result { fn budget_policy( raw: &RawBudgets, names: &BTreeMap, -) -> Result { - use crate::abuse::BudgetLimit; - let mut policy = crate::abuse::BudgetPolicy::default(); +) -> Result { + use id_core::abuse::BudgetLimit; + let mut policy = id_core::abuse::BudgetPolicy::default(); let checked = |field: &'static str, value: Option| -> Result, ConfigError> { match value { Some(0) => Err(ConfigError::ZeroBudget { field }), @@ -393,7 +393,7 @@ fn budget_policy( if let Some(v) = checked("per_ip_bytes_per_hour", raw.per_ip_bytes_per_hour)? { policy.per_ip[0] = BudgetLimit::bytes(3_600_000, v); } - let mut seen: BTreeSet = BTreeSet::new(); + let mut seen: BTreeSet = BTreeSet::new(); for row in &raw.counterparty { if row.bytes_per_window == 0 { return Err(ConfigError::ZeroBudget { @@ -442,7 +442,7 @@ fn budget_policy( fn counterparty_peer( peer: &str, names: &BTreeMap, -) -> Result { +) -> Result { if let Some(object) = names.get(peer) { return match object { Object::User(id) => Ok(*id), @@ -654,10 +654,10 @@ mod tests { use ed25519_dalek::SigningKey; - use crate::groups::{Key, Role}; - use crate::pull_policy::PullPolicy; + use id_events::groups::{Key, Role}; + use id_events::pull_policy::PullPolicy; use crate::server_config::{ConfigError, CreateRule, Object, PolicySpec, ServerConfig}; - use crate::world::hex_encode; + use id_worlds::world::hex_encode; /// The public key of the account that the test calls `n`. fn key(n: u8) -> Key { @@ -708,7 +708,7 @@ mod tests { fn test_no_policy_table_keeps_the_code_defaults() { let config = config("").unwrap(); assert_eq!(config.pull_policy(), PullPolicy::Open); - assert_eq!(config.freshness().window(), crate::seitan::DEFAULT_WINDOW); + assert_eq!(config.freshness().window(), id_directory::seitan::DEFAULT_WINDOW); assert_eq!(config.policy(), PolicySpec::default()); } @@ -1097,7 +1097,7 @@ mod tests { fn test_budgets_default_when_the_table_is_absent() { assert_eq!( config("").unwrap().budgets(), - &crate::abuse::BudgetPolicy::default() + &id_core::abuse::BudgetPolicy::default() ); } @@ -1107,10 +1107,10 @@ mod tests { let budgets = parsed.budgets(); assert_eq!( budgets.per_peer[1], - crate::abuse::BudgetLimit::bytes(3_600_000, 12345) + id_core::abuse::BudgetLimit::bytes(3_600_000, 12345) ); // Everything else keeps the code default. - let defaults = crate::abuse::BudgetPolicy::default(); + let defaults = id_core::abuse::BudgetPolicy::default(); assert_eq!(budgets.app_inbound, defaults.app_inbound); assert_eq!(budgets.per_peer[0], defaults.per_peer[0]); assert_eq!(budgets.per_ip, defaults.per_ip); @@ -1128,7 +1128,7 @@ mod tests { assert_eq!(overrides[0].0, key(1)); assert_eq!( overrides[0].1, - vec![crate::abuse::BudgetLimit { + vec![id_core::abuse::BudgetLimit { window_ms: 86_400_000, bytes_per_window: 1_048_576, messages_per_window: 1000, diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/crates/id-cli/src/server_config/provision.rs similarity index 98% rename from pkgs/id/src/server_config/provision.rs rename to pkgs/id/crates/id-cli/src/server_config/provision.rs index db139cfcd1..df11638eec 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/crates/id-cli/src/server_config/provision.rs @@ -14,12 +14,12 @@ use p2panda_core::Hash; use thiserror::Error; use super::{CreateRule, GroupSpec, ServerConfig}; -use crate::directory::Directory; -use crate::groups::{ +use id_directory::directory::Directory; +use id_events::groups::{ Body, Create, Event, FoldError, Key, MemberOp, Outcome, Policy, Projection, Refusal, Template, fold, }; -use crate::world::hex_encode; +use id_worlds::world::hex_encode; /// The accounts and group events of one server, as provisioning leaves them. #[derive(Debug)] @@ -281,9 +281,9 @@ mod tests { use proptest::prelude::*; use super::{ProvisionError, Provisioned, Report}; - use crate::groups::{Body, Event, Key, MemberOp, Outcome, Role}; + use id_events::groups::{Body, Event, Key, MemberOp, Outcome, Role}; use crate::server_config::ServerConfig; - use crate::world::hex_encode; + use id_worlds::world::hex_encode; fn key(n: u8) -> Key { SigningKey::from_bytes(&[n; 32]).verifying_key().to_bytes() @@ -339,7 +339,7 @@ mod tests { state: &Provisioned, config: &ServerConfig, group: &str, - ) -> crate::groups::GroupView { + ) -> id_events::groups::GroupView { let id = config.group_id(group).unwrap(); state.projection().unwrap().group(&id).cloned().unwrap() } @@ -419,7 +419,7 @@ mod tests { group: Some(team), body: Body::Member(MemberOp::Remove { member: key(2), - mode: crate::groups::RemoveMode::Revoke, + mode: id_events::groups::RemoveMode::Revoke, }), }; let projection = state.record(remove_bo).unwrap(); @@ -599,9 +599,9 @@ mod tests { author: who, after: Vec::new(), group: None, - body: Body::Create(crate::groups::Create { - template: crate::groups::Template::Custom, - policy: crate::groups::Policy::default(), + body: Body::Create(id_events::groups::Create { + template: id_events::groups::Template::Custom, + policy: id_events::groups::Policy::default(), members: Vec::new(), admins_on_create: false, }), diff --git a/pkgs/id/tests/aliases.rs b/pkgs/id/crates/id-cli/tests/aliases.rs similarity index 97% rename from pkgs/id/tests/aliases.rs rename to pkgs/id/crates/id-cli/tests/aliases.rs index 700f8635b6..6f81573190 100644 --- a/pkgs/id/tests/aliases.rs +++ b/pkgs/id/crates/id-cli/tests/aliases.rs @@ -19,11 +19,11 @@ use std::collections::BTreeMap; -use id::aliases::{ALIAS_NAME, Named, Object, Shown, aliases_of, rows}; -use id::chain::{ChainExt, Event, sign}; -use id::event_store::{EventStore, Ingest}; -use id::tag_claims::{SET_KIND, TagOp}; -use id::waiting::{AuthorKey, WaitingLimits}; +use id_cli::aliases::{ALIAS_NAME, Named, Object, Shown, aliases_of, rows}; +use id_store::chain::{ChainExt, Event, sign}; +use id_events::event_store::{EventStore, Ingest}; +use id_store::tag_claims::{SET_KIND, TagOp}; +use id_core::waiting::{AuthorKey, WaitingLimits}; use p2panda_core::{Hash, SeqNum, SigningKey}; /// A signer with its own chain. Each event names the one before it as its `after`. diff --git a/pkgs/id/crates/id-core/src/lib.rs b/pkgs/id/crates/id-core/src/lib.rs index 0d220c29a7..08d6cef066 100644 --- a/pkgs/id/crates/id-core/src/lib.rs +++ b/pkgs/id/crates/id-core/src/lib.rs @@ -93,3 +93,36 @@ pub const CLIENT_KEY_FILE: &str = ".iroh-key-client"; /// Created when `id serve` is running. Contains the node ID and addresses /// for local clients to connect. Automatically removed on clean shutdown. pub const SERVE_LOCK: &str = ".iroh-serve.lock"; + +/// Checks if a string is a valid node ID format. +/// +/// A valid node ID is exactly 64 hexadecimal characters (representing a +/// 32-byte Ed25519 public key). This function only validates the format, +/// not whether the node actually exists. +/// +/// # Arguments +/// +/// * `s` - The string to check +/// +/// # Returns +/// +/// `true` if the string is exactly 64 hex characters, `false` otherwise. +/// +/// # Example +/// +/// ```rust +/// use id_core::is_node_id; +/// +/// // Valid node ID (64 hex chars) +/// assert!(is_node_id("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")); +/// +/// // Invalid: too short +/// assert!(!is_node_id("0123456789abcdef")); +/// +/// // Invalid: contains non-hex characters +/// assert!(!is_node_id("ghijklmnopqrstuv0123456789abcdef0123456789abcdef0123456789abcd")); +/// ``` +pub fn is_node_id(s: &str) -> bool { + s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) +} + diff --git a/pkgs/id/src/fileops.rs b/pkgs/id/src/fileops.rs index 4e70a71080..fcd99c7ef8 100644 --- a/pkgs/id/src/fileops.rs +++ b/pkgs/id/src/fileops.rs @@ -8,651 +8,3 @@ pub use id_sync::fileops::*; -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod replacement_metadata_tests { - use crate::local::LocalNode; - use crate::tags::Tag; - - use super::*; - - async fn put(node: &LocalNode, name: &str, content: &[u8]) { - let guard = node - .blobs() - .add_bytes(content.to_vec()) - .temp_tag() - .await - .unwrap(); - node.ops().put(name, guard.hash()).await.unwrap(); - } - - async fn set_tag(node: &LocalNode, subject: &str, key: &str, value: &str) { - node.tags() - .set_tag( - &node.tags().global, - subject.as_bytes(), - key.as_bytes(), - Some(value.as_bytes()), - b"", - ) - .await - .unwrap(); - } - - async fn set_singleton(node: &LocalNode, subject: &str, key: &str, value: &str) { - node.tags() - .set_singleton( - &node.tags().global, - subject.as_bytes(), - key.as_bytes(), - Some(value.as_bytes()), - b"", - ) - .await - .unwrap(); - } - - async fn tags_of(node: &LocalNode, subject: &str) -> Vec { - node.tags() - .get_tags(&node.tags().global, subject.as_bytes()) - .await - .unwrap() - } - - fn values(tags: &[Tag], key: &str) -> Vec> { - tags.iter() - .filter(|tag| tag.key.as_bytes() == key.as_bytes()) - .filter_map(|tag| tag.value.as_ref().map(|value| value.as_bytes().to_vec())) - .collect() - } - - fn has_tag(tags: &[Tag], key: &str, value: &str) -> bool { - values(tags, key) - .iter() - .any(|found| found == value.as_bytes()) - } - - fn assert_single_value(tags: &[Tag], key: &str, value: &str) { - assert_eq!( - values(tags, key), - vec![value.as_bytes().to_vec()], - "{tags:?}" - ); - } - - fn assert_archive_identity(tags: &[Tag], archive: &str) { - assert_single_value(tags, "name", archive); - assert_single_value(tags, "file", archive.rsplit('/').next().unwrap_or(archive)); - assert!( - values(tags, "path").is_empty(), - "archive inherited path: {tags:?}" - ); - } - - async fn seed_replacement_pair(node: &LocalNode) { - put(node, "source.txt", b"new content").await; - put(node, "destination.txt", b"replaced content").await; - - set_tag(node, "source.txt", "shared", "source-value").await; - set_tag(node, "source.txt", "source-only", "source-metadata").await; - set_singleton(node, "source.txt", "created", "source-created").await; - set_singleton(node, "source.txt", "modified", "source-modified").await; - - set_tag(node, "destination.txt", "shared", "replaced-value").await; - set_tag( - node, - "destination.txt", - "replaced-only", - "replaced-metadata", - ) - .await; - set_tag( - node, - "destination.txt", - "archive.previous", - "earlier.archive.7", - ) - .await; - set_tag(node, "destination.txt", "path", "old/source/path.txt").await; - set_singleton(node, "destination.txt", "created", "replaced-created").await; - set_singleton(node, "destination.txt", "modified", "replaced-modified").await; - } - - fn assert_replaced_metadata_on_archive(tags: &[Tag], archive: &str) { - assert!(has_tag(tags, "shared", "replaced-value"), "{tags:?}"); - assert!( - has_tag(tags, "replaced-only", "replaced-metadata"), - "{tags:?}" - ); - assert!( - has_tag(tags, "archive.previous", "earlier.archive.7"), - "{tags:?}" - ); - assert_single_value(tags, "created", "replaced-created"); - assert_single_value(tags, "modified", "replaced-modified"); - assert_archive_identity(tags, archive); - assert!(!has_tag(tags, "name", "destination.txt"), "{tags:?}"); - assert!(!has_tag(tags, "file", "destination.txt"), "{tags:?}"); - } - - #[tokio::test] - async fn rename_with_archive_preserves_source_provenance_on_archive_alias() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "before.txt", b"original").await; - set_singleton(&node, "before.txt", "origin", "node-alpha").await; - set_singleton(&node, "before.txt", "created", "1700000000").await; - - // The source's recorded provenance, exactly as stored. - let source_tags = tags_of(&node, "before.txt").await; - assert_single_value(&source_tags, "origin", "node-alpha"); - let source_created = values(&source_tags, "created"); - assert!(!source_created.is_empty(), "{source_tags:?}"); - - let rename = node - .ops() - .rename("before.txt", "after.txt", true) - .await - .unwrap(); - let archive = rename.archived_original.unwrap(); - - // #5383: the archive alias carries the source's recorded - // provenance, not an unknown origin. - let archive_tags = tags_of(&node, &archive).await; - assert_single_value(&archive_tags, "origin", "node-alpha"); - assert_eq!(values(&archive_tags, "created"), source_created); - - // The live name keeps its provenance too (tags move with it). - let live_tags = tags_of(&node, "after.txt").await; - assert_single_value(&live_tags, "origin", "node-alpha"); - assert_eq!(values(&live_tags, "created"), source_created); - - node.shutdown().await.unwrap(); - } - - async fn rename_onto_existing_moves_replaced_metadata_and_refreshes_archive_identity() { - let node = LocalNode::open(true).await.unwrap(); - seed_replacement_pair(&node).await; - - let outcome = node - .ops() - .rename("source.txt", "destination.txt", false) - .await - .unwrap(); - let archive = outcome.archived_replaced.expect("replaced file archived"); - - let archived = tags_of(&node, &archive).await; - assert_replaced_metadata_on_archive(&archived, &archive); - - let destination = tags_of(&node, "destination.txt").await; - assert!( - has_tag(&destination, "shared", "source-value"), - "{destination:?}" - ); - assert!( - has_tag(&destination, "source-only", "source-metadata"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "shared", "replaced-value"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "replaced-only", "replaced-metadata"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "archive.previous", "earlier.archive.7"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "path", "old/source/path.txt"), - "{destination:?}" - ); - assert_single_value(&destination, "created", "source-created"); - assert_single_value(&destination, "modified", "source-modified"); - assert_single_value(&destination, "name", "destination.txt"); - assert_single_value(&destination, "file", "destination.txt"); - assert!( - has_tag(&destination, "archive.replace", &archive), - "{destination:?}" - ); - - node.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn copy_onto_existing_moves_replaced_metadata_and_keeps_single_fresh_stamps() { - let node = LocalNode::open(true).await.unwrap(); - seed_replacement_pair(&node).await; - - let outcome = node - .ops() - .copy("source.txt", "destination.txt") - .await - .unwrap(); - let archive = outcome.archived_replaced.expect("replaced file archived"); - - let archived = tags_of(&node, &archive).await; - assert_replaced_metadata_on_archive(&archived, &archive); - - let destination = tags_of(&node, "destination.txt").await; - assert!( - has_tag(&destination, "shared", "source-value"), - "{destination:?}" - ); - assert!( - has_tag(&destination, "source-only", "source-metadata"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "shared", "replaced-value"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "replaced-only", "replaced-metadata"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "archive.previous", "earlier.archive.7"), - "{destination:?}" - ); - assert!( - !has_tag(&destination, "path", "old/source/path.txt"), - "{destination:?}" - ); - assert_eq!(values(&destination, "created").len(), 1, "{destination:?}"); - assert_eq!(values(&destination, "modified").len(), 1, "{destination:?}"); - assert_single_value(&destination, "name", "destination.txt"); - assert_single_value(&destination, "file", "destination.txt"); - assert!( - has_tag(&destination, "archive.replace", &archive), - "{destination:?}" - ); - - let source = tags_of(&node, "source.txt").await; - assert!(has_tag(&source, "shared", "source-value"), "{source:?}"); - assert!( - has_tag(&source, "source-only", "source-metadata"), - "{source:?}" - ); - - node.shutdown().await.unwrap(); - } - - /// A copy must not become a second owner of the source's archives - /// (#4761): deleting the copy must leave the source's archives intact. - #[tokio::test] - async fn copy_does_not_inherit_source_archive_refs() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "source.txt", b"source content").await; - put(&node, "other.txt", b"other content").await; - // Renaming onto source.txt with archiving enabled adds both - // archive.rename and archive.replace refs to the live source. - let rename_outcome = node - .ops() - .rename("other.txt", "source.txt", true) - .await - .unwrap(); - let source_archives = [ - rename_outcome - .archived_original - .expect("original source archived"), - rename_outcome - .archived_replaced - .expect("replaced source archived"), - ]; - let source_before = tags_of(&node, "source.txt").await; - assert!( - has_tag(&source_before, "archive.rename", &source_archives[0]), - "{source_before:?}" - ); - assert!( - has_tag(&source_before, "archive.replace", &source_archives[1]), - "{source_before:?}" - ); - - node.ops().copy("source.txt", "copy.txt").await.unwrap(); - let copy_tags = tags_of(&node, "copy.txt").await; - assert!( - values(©_tags, "archive.rename").is_empty(), - "copy inherited archive.rename refs: {copy_tags:?}" - ); - assert!( - values(©_tags, "archive.replace").is_empty(), - "copy inherited archive.replace refs: {copy_tags:?}" - ); - - // Deleting the copy must not touch the source's archive. - let delete_outcome = node.ops().delete("copy.txt").await.unwrap(); - assert_eq!( - delete_outcome.archives_removed, 0, - "copy delete removed archives" - ); - for archive in &source_archives { - assert!( - !tags_of(&node, archive).await.is_empty(), - "source archive {archive} removed by copy delete" - ); - } - let source_after = tags_of(&node, "source.txt").await; - assert!( - has_tag(&source_after, "archive.rename", &source_archives[0]), - "source lost its archive.rename ref: {source_after:?}" - ); - assert!( - has_tag(&source_after, "archive.replace", &source_archives[1]), - "source lost its archive ref: {source_after:?}" - ); - - node.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn rename_onto_existing_preserves_replaced_tag_payloads() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "source.txt", b"new content").await; - put(&node, "destination.txt", b"replaced content").await; - - // A tag with a non-empty entry payload, as written for legacy - // links by migrate_legacy_meta (payload carries the link target). - let payload: &[u8] = b"hash:0123abcd"; - node.tags() - .set_tag( - &node.tags().global, - b"destination.txt", - b"link", - Some(b"target"), - payload, - ) - .await - .unwrap(); - let before = tags_of(&node, "destination.txt").await; - let before = before - .iter() - .find(|tag| tag.key.as_bytes() == b"link") - .expect("link tag seeded"); - assert_eq!(before.len as usize, payload.len(), "{before:?}"); - let before_hash = before.hash; - - let outcome = node - .ops() - .rename("source.txt", "destination.txt", false) - .await - .unwrap(); - let archive = outcome.archived_replaced.expect("replaced file archived"); - - let archived = tags_of(&node, &archive).await; - let moved = archived - .iter() - .find(|tag| tag.key.as_bytes() == b"link") - .expect("link tag moved to archive"); - assert_eq!(moved.hash, before_hash, "{moved:?}"); - assert_eq!(moved.len as usize, payload.len(), "{moved:?}"); - - node.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn delete_removes_archived_replaced_metadata() { - let node = LocalNode::open(true).await.unwrap(); - seed_replacement_pair(&node).await; - - let outcome = node - .ops() - .rename("source.txt", "destination.txt", false) - .await - .unwrap(); - let archive = outcome.archived_replaced.expect("replaced file archived"); - assert!( - !tags_of(&node, &archive).await.is_empty(), - "archive carries the replaced file's metadata before delete" - ); - - let deleted = node.ops().delete("destination.txt").await.unwrap(); - assert_eq!(deleted.archives_removed, 1); - assert!( - tags_of(&node, &archive).await.is_empty(), - "archive metadata removed with the archive" - ); - - node.shutdown().await.unwrap(); - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod delete_tests { - use crate::local::LocalNode; - - use super::*; - - async fn put(node: &LocalNode, name: &str, data: &[u8]) { - let guard = node - .blobs() - .add_bytes(data.to_vec()) - .temp_tag() - .await - .unwrap(); - node.ops().put(name, guard.hash()).await.unwrap(); - } - - #[tokio::test] - async fn delete_after_archived_rename_removes_previous_name_archive() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "before", b"original").await; - - let rename = node.ops().rename("before", "after", true).await.unwrap(); - let archive = rename.archived_original.unwrap(); - assert!(node.blobs().tags().get(&archive).await.unwrap().is_some()); - - let deleted = node.ops().delete("after").await.unwrap(); - - assert_eq!(deleted.archives_removed, 1); - assert!(node.blobs().tags().get(&archive).await.unwrap().is_none()); - node.shutdown().await.unwrap(); - } - - #[tokio::test] - async fn delete_after_repeated_replacements_removes_all_replaced_archives() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "A", b"original").await; - - put(&node, "replacement-1", b"first replacement").await; - let first = node - .ops() - .rename("replacement-1", "A", false) - .await - .unwrap() - .archived_replaced - .unwrap(); - put(&node, "replacement-2", b"second replacement").await; - let second = node - .ops() - .rename("replacement-2", "A", false) - .await - .unwrap() - .archived_replaced - .unwrap(); - assert_ne!(first, second); - - node.ops().rename("A", "B", false).await.unwrap(); - let deleted = node.ops().delete("B").await.unwrap(); - - assert_eq!(deleted.archives_removed, 2); - assert!(node.blobs().tags().get(&first).await.unwrap().is_none()); - assert!(node.blobs().tags().get(&second).await.unwrap().is_none()); - node.shutdown().await.unwrap(); - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod name_rule_tests { - use crate::local::LocalNode; - - use super::*; - - async fn put(node: &LocalNode, name: &str, data: &[u8]) { - let guard = node - .blobs() - .add_bytes(data.to_vec()) - .temp_tag() - .await - .unwrap(); - node.ops().put(name, guard.hash()).await.unwrap(); - } - - fn assert_invalid(name: &str) { - assert!( - matches!( - FileOps::validate_name(name), - Err(FileOpError::InvalidName(_)) - ), - "{name:?} must be refused as InvalidName" - ); - } - - /// Padding and empty components are refused by the one canonical rule - /// (#4102 / design #4766 Phase 3), so a name can never be stored in a - /// form that rename/copy would normalise away. - #[test] - fn refuses_padding_and_empty_components() { - for name in [ - " report.txt", - "report.txt ", - "\treport.txt", - "report.txt\n", - "a//b", - "a/", - "a\\", - "a//b/c", - "a/b/", - ] { - assert_invalid(name); - } - } - - /// The pre-existing refusals stay in place: rooted names, drive - /// prefixes, and `.`/`..` traversal components. - #[test] - fn preserves_traversal_refusals() { - for name in [ - "/etc/passwd", - "\\windows", - "C:file.txt", - ".", - "..", - "a/./b", - "a/../b", - ] { - assert_invalid(name); - } - assert!(matches!( - FileOps::validate_name(" "), - Err(FileOpError::EmptyName) - )); - // Padding is a refusal, but interior spaces in a name are not. - assert!(FileOps::validate_name("my report.txt").is_ok()); - assert!(FileOps::validate_name("a/b").is_ok()); - } - - /// A padded `put` cannot create an untargetable twin, and a padded - /// rename/copy target is refused instead of being silently trimmed. - #[tokio::test] - async fn padded_names_cannot_create_twins() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "report.txt", b"report").await; - - let guard = node - .blobs() - .add_bytes(b"report".to_vec()) - .temp_tag() - .await - .unwrap(); - assert!(matches!( - node.ops().put(" report.txt", guard.hash()).await, - Err(FileOpError::InvalidName(_)) - )); - assert!( - node.blobs() - .tags() - .get(" report.txt") - .await - .unwrap() - .is_none() - ); - assert!( - node.blobs() - .tags() - .get("report.txt") - .await - .unwrap() - .is_some() - ); - - assert!(matches!( - node.ops().rename("report.txt", "other.txt ", false).await, - Err(FileOpError::InvalidName(_)) - )); - assert!( - node.blobs() - .tags() - .get("other.txt") - .await - .unwrap() - .is_none() - ); - - assert!(matches!( - node.ops().copy("report.txt", " copy.txt").await, - Err(FileOpError::InvalidName(_)) - )); - assert!( - node.blobs() - .tags() - .get(" copy.txt") - .await - .unwrap() - .is_none() - ); - assert!(node.blobs().tags().get("copy.txt").await.unwrap().is_none()); - - node.shutdown().await.unwrap(); - } - - /// Empty components are refused at put and at rename/copy targets alike. - #[tokio::test] - async fn empty_components_refused_across_put_rename_copy() { - let node = LocalNode::open(true).await.unwrap(); - put(&node, "a/b", b"body").await; - - let guard = node - .blobs() - .add_bytes(b"body".to_vec()) - .temp_tag() - .await - .unwrap(); - for name in ["a//b", "a/", "a\\"] { - assert!(matches!( - node.ops().put(name, guard.hash()).await, - Err(FileOpError::InvalidName(_)) - )); - assert!(matches!( - node.ops().rename("a/b", name, false).await, - Err(FileOpError::InvalidName(_)) - )); - assert!(matches!( - node.ops().copy("a/b", name).await, - Err(FileOpError::InvalidName(_)) - )); - assert!(node.blobs().tags().get(name).await.unwrap().is_none()); - } - - // The canonical source is untouched and ordinary names still work. - assert!(node.blobs().tags().get("a/b").await.unwrap().is_some()); - node.ops().copy("a/b", "a/c").await.unwrap(); - assert!(node.blobs().tags().get("a/c").await.unwrap().is_some()); - - node.shutdown().await.unwrap(); - } -} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index e1996a25a6..d86ac2939e 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -205,8 +205,6 @@ pub use id_core::abuse; pub use id_core::access; -pub mod aliases; -pub mod app_manifest; #[cfg(feature = "world")] pub mod artifact; pub use id_events::attestation; @@ -216,9 +214,6 @@ pub mod blob_gate; pub mod boards; pub use id_store::chain; pub use id_store::chat; -pub mod chat_presence; -pub mod cli; -pub mod commands; pub use id_core::connectivity; pub mod conversion; pub mod currency; @@ -253,34 +248,25 @@ pub use id_core::frames; pub mod grant_service; pub mod grants; pub mod groups; -pub mod helpers; pub mod hosted_binding; pub use id_events::idset; pub mod input_framing; pub use id_directory::invite; pub use id_directory::invites; pub use id_store::issuer_rotation; -pub mod local; pub use id_events::local_claims; pub use id_events::local_events; pub use id_sync::log_sync; -mod peer_announcement; pub mod serve_proxy; pub use id_core::membership; -pub mod match_audit; -pub mod meta_client; pub use id_store::note_links; pub use id_store::notes; #[cfg(feature = "world")] pub use id_core::petname; -pub mod protocol; -pub mod publications; -pub mod publications_runtime; pub mod pull_policy; pub use id_core::residency; pub mod references; pub use id_core::rejection; -pub mod repl; #[cfg(feature = "sandbox")] pub use id_worlds::sandbox; #[cfg(feature = "sandbox")] @@ -289,7 +275,6 @@ pub use id_store::search; #[cfg(feature = "world")] pub use id_directory::seitan; #[cfg(feature = "world")] -pub mod server_config; pub use id_store::session_checkpoint; #[cfg(feature = "world")] pub use id_worlds::shell_contract; @@ -346,12 +331,20 @@ pub(crate) use id_worlds::world_terminal; #[cfg(feature = "web")] pub use id_core::qr; +// Application layer extracted in split step 7b (#4411): the modules +// below live in the id-cli crate and are re-exported at their +// historical `id::` paths. `main.rs` consumes them through here. +pub use id_cli::{ + aliases, app_manifest, chat_presence, cli, commands, helpers, local, match_audit, + meta_client, protocol, publications, publications_runtime, repl, server_config, +}; + #[cfg(feature = "web")] pub use id_web as web; // Re-export commonly used types for convenience -pub use cli::{Cli, Command, KeyCommand, TagCommand}; -pub use commands::{ +pub use id_cli::cli::{Cli, Command, KeyCommand, TagCommand}; +pub use id_cli::commands::{ PeekOptions, PeersOptions, ReplContext, ReplContextInner, SearchOptions, ServeInfo, ServeOptions, cmd_find, cmd_find_matches, cmd_get_local, cmd_get_multi, cmd_get_one, cmd_get_one_remote, cmd_gethash, cmd_id, cmd_list, cmd_list_remote, cmd_migrate_tags, cmd_peek, @@ -364,13 +357,13 @@ pub use discovery::{ MAX_PEERS, PeerAnnouncement, PeerDiscovery, PeerInfo, ResolvedConfig, STALE_CHECK_INTERVAL, STALE_THRESHOLD, defaults, parse_defaults, resolve_config, }; -pub use helpers::{ +pub use id_cli::helpers::{ download_output_path, parse_get_spec, parse_put_spec, print_match_cli, print_match_repl, print_matches_cli, }; -pub use protocol::{FindMatch, MatchKind, MetaProtocol, MetaRequest, MetaResponse, TaggedMatch}; -pub use protocol::match_kind; -pub use repl::run_repl; +pub use id_cli::protocol::{FindMatch, MatchKind, MetaProtocol, MetaRequest, MetaResponse, TaggedMatch}; +pub use id_cli::protocol::match_kind; +pub use id_cli::repl::run_repl; pub use store::{StoreType, load_or_create_keypair, open_store}; use anyhow::Result; @@ -393,199 +386,17 @@ pub use id_sync::protocol::META_ALPN; // Utility Functions // ============================================================================ -/// Converts a potentially relative path to an absolute path. -/// -/// If the path is already absolute, it is returned unchanged. Otherwise, -/// it is joined with the current working directory. -/// -/// # Arguments -/// -/// * `path` - The path to convert -/// -/// # Returns -/// -/// The absolute path, or an error if the current directory cannot be determined. -/// -/// # Example -/// -/// ```rust -/// use std::path::PathBuf; -/// use id::to_absolute; -/// -/// let abs = to_absolute(&PathBuf::from("/already/absolute")).unwrap(); -/// assert_eq!(abs, PathBuf::from("/already/absolute")); -/// -/// // Relative paths are joined with the current directory -/// let rel = to_absolute(&PathBuf::from("relative/path")).unwrap(); -/// assert!(rel.is_absolute()); -/// ``` -pub fn to_absolute(path: &PathBuf) -> Result { - if path.is_absolute() { - Ok(path.clone()) - } else { - Ok(std::env::current_dir()?.join(path)) - } -} +pub use id_cli::to_absolute; -/// Checks if a string is a valid node ID format. -/// -/// A valid node ID is exactly 64 hexadecimal characters (representing a -/// 32-byte Ed25519 public key). This function only validates the format, -/// not whether the node actually exists. -/// -/// # Arguments -/// -/// * `s` - The string to check -/// -/// # Returns -/// -/// `true` if the string is exactly 64 hex characters, `false` otherwise. -/// -/// # Example -/// -/// ```rust -/// use id::is_node_id; -/// -/// // Valid node ID (64 hex chars) -/// assert!(is_node_id("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")); -/// -/// // Invalid: too short -/// assert!(!is_node_id("0123456789abcdef")); -/// -/// // Invalid: contains non-hex characters -/// assert!(!is_node_id("ghijklmnopqrstuv0123456789abcdef0123456789abcdef0123456789abcd")); -/// ``` -pub fn is_node_id(s: &str) -> bool { - s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) -} +pub use id_core::is_node_id; -/// Parses items from stdin, splitting on common delimiters. -/// -/// Reads all content from stdin and splits it on newlines, tabs, or commas. -/// Empty items and whitespace-only items are filtered out. This is useful -/// for batch operations where file lists are piped in. -/// -/// # Returns -/// -/// A vector of trimmed, non-empty strings. -/// -/// # Example -/// -/// ```bash -/// # From command line: -/// echo "file1.txt,file2.txt,file3.txt" | id put --stdin -/// ``` -/// -/// ```rust,no_run -/// use id::parse_stdin_items; -/// -/// // If stdin contains "a.txt\nb.txt\tc.txt,d.txt" -/// let items = parse_stdin_items().unwrap(); -/// // items = ["a.txt", "b.txt", "c.txt", "d.txt"] -/// ``` -pub fn parse_stdin_items() -> Result> { - use std::io::Read; - let mut input = String::new(); - std::io::stdin().read_to_string(&mut input)?; - Ok(input - .split(['\n', '\t', ',']) - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(ToOwned::to_owned) - .collect()) -} +pub use id_cli::parse_stdin_items; -/// Reads input data from a file path or stdin. -/// -/// If the input is "-", reads from stdin. Otherwise, reads from the specified -/// file path. This is a common pattern for CLI tools that accept either a -/// file or piped input. -/// -/// # Arguments -/// -/// * `input` - Either "-" for stdin, or a file path -/// -/// # Returns -/// -/// The raw bytes read from the source. -/// -/// # Example -/// -/// ```rust,ignore -/// use id::read_input; -/// -/// # async fn example() -> anyhow::Result<()> { -/// // Read from file -/// let data = read_input("myfile.txt").await?; -/// -/// // Read from stdin (when input is "-") -/// let stdin_data = read_input("-").await?; -/// # Ok(()) -/// # } -/// ``` -pub async fn read_input(input: &str) -> Result> { - use std::io::Read; - use tokio::fs as afs; - - if input == "-" { - let mut data = Vec::new(); - std::io::stdin().read_to_end(&mut data)?; - Ok(data) - } else { - Ok(afs::read(input).await?) - } -} +pub use id_cli::read_input; -/// Exports a blob to a file or stdout. -/// -/// Retrieves the blob data by hash from the store and writes it to the -/// specified output. If output is "-", writes to stdout. Otherwise, -/// writes to a file at the given path (converting to absolute if needed). -/// -/// # Arguments -/// -/// * `store` - The blob store to read from -/// * `hash` - The hash of the blob to export -/// * `output` - Either "-" for stdout, or a file path -/// -/// # Example -/// -/// ```rust,ignore -/// use id::{open_store, export_blob}; -/// use iroh_blobs::Hash; -/// -/// # async fn example() -> anyhow::Result<()> { -/// let store_type = open_store(false).await?; -/// let store = store_type.as_store(); -/// -/// // Export to file -/// let hash: Hash = "abc123...".parse()?; -/// export_blob(&store, hash, "output.txt").await?; -/// -/// // Export to stdout -/// export_blob(&store, hash, "-").await?; -/// # Ok(()) -/// # } -/// ``` -pub async fn export_blob( - store: &iroh_blobs::api::Store, - hash: iroh_blobs::Hash, - output: &str, -) -> Result<()> { - use std::io::Write; - - if output == "-" { - let data = store.blobs().get_bytes(hash).await?; - std::io::stdout().write_all(&data)?; - } else { - let path = to_absolute(&PathBuf::from(output))?; - store.blobs().export(hash, &path).await?; - eprintln!("exported: {} -> {}", hash, path.display()); - } - Ok(()) -} +pub use id_cli::export_blob; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]