diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 0262968c2..53fc0e0ee 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -32,7 +32,13 @@ default-members = [".", "crates/id-core"] [features] default = ["sandbox", "world"] sandbox = ["dep:wasmtime", "world", "id-core/sandbox"] -world = ["dep:subtle", "dep:hmac", "dep:scrypt", "dep:rmp-serde", "id-core/world"] +world = [ + "dep:subtle", + "dep:hmac", + "dep:scrypt", + "dep:rmp-serde", + "id-core/world", +] ssh = ["world", "dep:russh"] web = [ "world", @@ -163,7 +169,9 @@ russh = { version = "=0.65.0", optional = true } # Paused-time session-driver tests. Dev only. tokio = { version = "1", features = ["test-util"] } # The root package's tests exercise dial deadlines using id-core's test-only helpers. -id-core = { path = "crates/id-core", default-features = false, features = ["test-utils"] } +id-core = { path = "crates/id-core", default-features = false, features = [ + "test-utils", +] } # SQLite for the bridge PoC's DO-shaped hosted store (#2276). Bundled, so no system SQLite is needed. rusqlite = { version = "0.32", features = ["bundled"] } wat = "=1.261.0" diff --git a/pkgs/id/README.md b/pkgs/id/README.md index 54a95de95..1bc5d9929 100644 --- a/pkgs/id/README.md +++ b/pkgs/id/README.md @@ -134,32 +134,32 @@ it is — a valid world capability, minted by the host's admin with ## CLI Commands -| Command | Aliases | Description | -| -------------- | ------------------------------ | ----------------------------------------------- | -| `serve` | | Start server for peer requests | -| `repl` | `shell` | Interactive REPL with pipes and subshells | -| `put` | `in`, `add`, `store`, `import` | Store files in blob store | -| `put-hash` | | Store content by hash only (no named tag) | -| `get` | | Retrieve files by name or hash | -| `get-hash` | | Retrieve file by hash with explicit output path | -| `cat` | `output`, `out` | Output file content to stdout | -| `show` | `view` | Find file by pattern and output content | -| `peek` | | Preview with configurable head/tail lines | -| `find` | | Find files by query, optionally output content | -| `search` | | Search files and list all matches | -| `list` | `ls` | List all stored files | -| `tag` | `label`, `link` | Manage metadata tags on files | -| `migrate-tags` | `migrate` | Add name/file auto-tags to existing files | -| `id` | | Print local node public ID | +| Command | Aliases | Description | +| -------------- | ------------------------------ | -------------------------------------------------- | +| `serve` | | Start server for peer requests | +| `repl` | `shell` | Interactive REPL with pipes and subshells | +| `put` | `in`, `add`, `store`, `import` | Store files in blob store | +| `put-hash` | | Store content by hash only (no named tag) | +| `get` | | Retrieve files by name or hash | +| `get-hash` | | Retrieve file by hash with explicit output path | +| `cat` | `output`, `out` | Output file content to stdout | +| `show` | `view` | Find file by pattern and output content | +| `peek` | | Preview with configurable head/tail lines | +| `find` | | Find files by query, optionally output content | +| `search` | | Search files and list all matches | +| `list` | `ls` | List all stored files | +| `tag` | `label`, `link` | Manage metadata tags on files | +| `migrate-tags` | `migrate` | Add name/file auto-tags to existing files | +| `id` | | Print local node public ID | | `key` | | Export or import a passphrase-wrapped identity key | -| `peers` | | Discover and list known peers | -| `world` | | Mint invites for, and join, multiplayer worlds | -| `match-audit` | | Export and verify signed match-audit v0 logs | -| `group` | | Groups: create, policy, add, remove, roles, join | -| `delegate` | | Grant a delegate a scope in a group | -| `revoke` | | Revoke a delegation by its grant event ID | -| `doc` | | Publish documents; list events/frontier/history | -| `claim` | | Tag claims on any subject (set, clear, search) | +| `peers` | | Discover and list known peers | +| `world` | | Mint invites for, and join, multiplayer worlds | +| `match-audit` | | Export and verify signed match-audit v0 logs | +| `group` | | Groups: create, policy, add, remove, roles, join | +| `delegate` | | Grant a delegate a scope in a group | +| `revoke` | | Revoke a delegation by its grant event ID | +| `doc` | | Publish documents; list events/frontier/history | +| `claim` | | Tag claims on any subject (set, clear, search) | ### Tag Subcommands diff --git a/pkgs/id/benches/BASELINES.md b/pkgs/id/benches/BASELINES.md index e411f01df..5f85beaf5 100644 --- a/pkgs/id/benches/BASELINES.md +++ b/pkgs/id/benches/BASELINES.md @@ -98,8 +98,8 @@ proof of a regression. The slice-2 `guest_replay` line above (median=0.146) was measured with a harness whose guest saw **zero** events: the journal was built from -committed *chat* events, and `WorldCore::restore` applies committed chat -to core state directly — only committed *input* (and journal system) +committed _chat_ events, and `WorldCore::restore` applies committed chat +to core state directly — only committed _input_ (and journal system) events are put in `RestoredWorld.replay`. The old number was therefore restore-only time divided by N, mislabeled as guest replay. diff --git a/pkgs/id/crates/id-core/Cargo.toml b/pkgs/id/crates/id-core/Cargo.toml index e2740a73e..e42e3e131 100644 --- a/pkgs/id/crates/id-core/Cargo.toml +++ b/pkgs/id/crates/id-core/Cargo.toml @@ -21,7 +21,9 @@ iroh = "1" iroh-base = "1" iroh-blobs = "0.103" p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" } -p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = ["serde"] } +p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = [ + "serde", +] } postcard = { version = "1", features = ["alloc"] } qrcode = { version = "0.14.1", default-features = false, optional = true } serde = { version = "1", features = ["derive"] } diff --git a/pkgs/id/crates/id-core/src/membership/gate.rs b/pkgs/id/crates/id-core/src/membership/gate.rs index 56e1f6b43..87a4e3c5a 100644 --- a/pkgs/id/crates/id-core/src/membership/gate.rs +++ b/pkgs/id/crates/id-core/src/membership/gate.rs @@ -285,4 +285,3 @@ mod tests { ); } } - diff --git a/pkgs/id/crates/id-core/src/membership/layer.rs b/pkgs/id/crates/id-core/src/membership/layer.rs index 1a9717d89..a267ac590 100644 --- a/pkgs/id/crates/id-core/src/membership/layer.rs +++ b/pkgs/id/crates/id-core/src/membership/layer.rs @@ -560,8 +560,7 @@ fn canonical_feed_order(events: &[CausalEvent]) -> Vec { } waiting.insert(event.id, dependencies.len()); } - let by_id: HashMap = - events.iter().map(|event| (event.id, event)).collect(); + let by_id: HashMap = events.iter().map(|event| (event.id, event)).collect(); let mut placed: HashSet = HashSet::new(); let mut order = Vec::with_capacity(events.len()); while let Some(Reverse(id)) = ready.pop() { @@ -1171,4 +1170,3 @@ mod tests { } } } - diff --git a/pkgs/id/crates/id-core/src/world_limits.rs b/pkgs/id/crates/id-core/src/world_limits.rs index cf64aad8f..6a2bfba46 100644 --- a/pkgs/id/crates/id-core/src/world_limits.rs +++ b/pkgs/id/crates/id-core/src/world_limits.rs @@ -48,7 +48,8 @@ pub const JOURNAL_ENTRY_OVERHEAD_BYTES: u64 = 64; /// payload length plus the fixed structural allowance. #[must_use] pub fn journal_entry_charge(serialized_len: usize) -> u64 { - u64::try_from(serialized_len).unwrap_or(u64::MAX) + u64::try_from(serialized_len) + .unwrap_or(u64::MAX) .saturating_add(JOURNAL_ENTRY_OVERHEAD_BYTES) } @@ -377,9 +378,11 @@ impl WorldExecutionProfile { // them beneath the budget lands with the enforcement charge sites // (Phase 3), so a configured budget never silently shrinks guest // limits before the ledger exists to account for it. - let total_memory_bytes = self.total_memory_bytes.map_or(hard.total_memory_bytes, |value| { - value.min(hard.total_memory_bytes) - }); + let total_memory_bytes = self + .total_memory_bytes + .map_or(hard.total_memory_bytes, |value| { + value.min(hard.total_memory_bytes) + }); #[cfg(feature = "sandbox")] let sandbox = { let hard_memory = u64::try_from(hard.sandbox.memory_bytes)?; @@ -664,10 +667,7 @@ mod tests { fn an_empty_profile_inherits_the_server_total_budget() { let hard = RuntimeLimits::default(); let effective = WorldExecutionProfile::default().resolve(hard).unwrap(); - assert_eq!( - effective.total_memory_bytes, - hard.total_memory_bytes - ); + assert_eq!(effective.total_memory_bytes, hard.total_memory_bytes); } #[test] @@ -679,10 +679,7 @@ mod tests { } .resolve(hard) .unwrap(); - assert_eq!( - lowered.total_memory_bytes, - hard.total_memory_bytes / 2 - ); + assert_eq!(lowered.total_memory_bytes, hard.total_memory_bytes / 2); let raised = WorldExecutionProfile { total_memory_bytes: Some(u64::MAX), ..Default::default() @@ -710,14 +707,8 @@ mod tests { #[cfg(feature = "sandbox")] { assert_eq!(effective.sandbox.fuel, hard.sandbox.fuel); - assert_eq!( - effective.sandbox.memory_bytes, - hard.sandbox.memory_bytes - ); - assert_eq!( - effective.sandbox.message_bytes, - hard.sandbox.message_bytes - ); + assert_eq!(effective.sandbox.memory_bytes, hard.sandbox.memory_bytes); + assert_eq!(effective.sandbox.message_bytes, hard.sandbox.message_bytes); } } diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 0f456afb7..26021ebc0 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -1039,11 +1039,10 @@ mod tests { #[test] fn text_parses_and_round_trips() { - let parsed = parse_surface( - r#"{"kind":"text","version":1,"lines":["hello","wide 界 line"]}"#, - ) - .unwrap() - .unwrap(); + let parsed = + parse_surface(r#"{"kind":"text","version":1,"lines":["hello","wide 界 line"]}"#) + .unwrap() + .unwrap(); let WorldSurface::Text(text) = &parsed else { panic!("expected a text surface"); }; @@ -1067,19 +1066,21 @@ mod tests { let text = TextSurface::with_width(4, vec!["abcdefghij".to_owned()]).unwrap(); assert_eq!(text.lines, ["abcd", "efgh", "ij"]); let text = TextSurface::with_width(3, vec!["ab界cd".to_owned()]).unwrap(); - assert!(text - .lines - .iter() - .all(|line| UnicodeWidthStr::width(line.as_str()) <= 3)); + assert!( + text.lines + .iter() + .all(|line| UnicodeWidthStr::width(line.as_str()) <= 3) + ); assert_eq!(text.lines.concat(), "ab界cd"); // The default is 80 and any requested width is capped like a screen. let text = TextSurface::with_width(10_000, vec!["x".repeat(200)]).unwrap(); assert_eq!(usize::from(text.width), MAX_SCREEN_WIDTH); - assert!(text - .lines - .iter() - .all(|line| UnicodeWidthStr::width(line.as_str()) <= MAX_SCREEN_WIDTH)); + assert!( + text.lines + .iter() + .all(|line| UnicodeWidthStr::width(line.as_str()) <= MAX_SCREEN_WIDTH) + ); assert!(TextSurface::with_width(0, vec!["x".to_owned()]).is_err()); } diff --git a/pkgs/id/examples/roc-world/ABI.md b/pkgs/id/examples/roc-world/ABI.md index 865cd69d9..652f1dbdf 100644 --- a/pkgs/id/examples/roc-world/ABI.md +++ b/pkgs/id/examples/roc-world/ABI.md @@ -42,22 +42,22 @@ returned value to negotiate versions. Signatures below are Wasm signatures; `i32` pointers and lengths refer to the guest's linear memory. -| Export | Signature | Contract | -| --- | --- | --- | -| `plaza_abi_version` | `() -> i32` | Returns `1` for this ABI specification. New v1 host builds export it; older guest modules may omit it. | -| `plaza_alloc` | `(i32 byte_len) -> i32 ptr` | Allocates guest-owned memory for host-provided input bytes. The host writes the input before calling the guest operation and releases the allocation with `plaza_free`. | -| `plaza_free` | `(i32 ptr, i32 allocation_len) -> ()` | Releases a matching allocation made by `plaza_alloc`. The length is the allocation length; for an empty logical input the runner allocates and later frees one byte while passing logical length zero to the operation. | -| `plaza_init` | `(i64 seed) -> i32 model` | Creates the initial model from the host-provided `u64` seed. Called once for a newly instantiated world. | -| `plaza_update` | `(i32 model, i32 participant, i32 event_ptr, i32 event_len) -> i32 model` | Applies one UTF-8 serialized world event and returns the next model. `participant` is the sender's ID; host-generated events use participant `0`. The runner commits the returned model only when the call succeeds. | -| `plaza_view` | `(i32 model) -> i32 output_ptr` | Returns UTF-8 text or a portable screen JSON document for the current model. | -| `plaza_layout` | `(i32 model, i64 width, i64 height) -> i32 output_ptr` | Optional viewport-specific rendering. Width and height are the connection's viewport dimensions. When absent, the host falls back to `plaza_view`. | -| `plaza_records` | `(i32 model) -> i32 output_ptr` | Optional structured projection. The returned bytes are a JSON object of string keys to JSON values; the host validates and publishes it. | -| `plaza_wants` | `(i32 model) -> i32 output_ptr` | Optional capability request/subscription document, as specified below. | -| `plaza_snapshot` | `(i32 model) -> i32 output_ptr` | Optional UTF-8 serialization of the model for a journal checkpoint. Must be paired with `plaza_restore`. | -| `plaza_restore` | `(i32 snapshot_ptr, i32 snapshot_len) -> i32 model` | Reconstructs a model from bytes produced by `plaza_snapshot`. The input is allocated by the host and released after the call. A Roc program should return a sensible model for invalid snapshot text rather than trap. | -| `plaza_out_len` | `() -> i32 byte_len` | Returns the byte length of the most recent output from `view`, `layout`, `records`, `wants`, or `snapshot`. It is one shared output slot. | -| `plaza_error_ptr` | `() -> i32 ptr` | Optional diagnostic pointer exposed after a guest trap. In the Roc host it points to the captured Roc crash message in guest memory. | -| `plaza_error_len` | `() -> i32 byte_len` | Optional diagnostic length paired with `plaza_error_ptr`; the Roc host captures at most 4096 bytes. The bytes are not NUL-terminated and are diagnostic only, not a result/status channel. | +| Export | Signature | Contract | +| ------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `plaza_abi_version` | `() -> i32` | Returns `1` for this ABI specification. New v1 host builds export it; older guest modules may omit it. | +| `plaza_alloc` | `(i32 byte_len) -> i32 ptr` | Allocates guest-owned memory for host-provided input bytes. The host writes the input before calling the guest operation and releases the allocation with `plaza_free`. | +| `plaza_free` | `(i32 ptr, i32 allocation_len) -> ()` | Releases a matching allocation made by `plaza_alloc`. The length is the allocation length; for an empty logical input the runner allocates and later frees one byte while passing logical length zero to the operation. | +| `plaza_init` | `(i64 seed) -> i32 model` | Creates the initial model from the host-provided `u64` seed. Called once for a newly instantiated world. | +| `plaza_update` | `(i32 model, i32 participant, i32 event_ptr, i32 event_len) -> i32 model` | Applies one UTF-8 serialized world event and returns the next model. `participant` is the sender's ID; host-generated events use participant `0`. The runner commits the returned model only when the call succeeds. | +| `plaza_view` | `(i32 model) -> i32 output_ptr` | Returns UTF-8 text or a portable screen JSON document for the current model. | +| `plaza_layout` | `(i32 model, i64 width, i64 height) -> i32 output_ptr` | Optional viewport-specific rendering. Width and height are the connection's viewport dimensions. When absent, the host falls back to `plaza_view`. | +| `plaza_records` | `(i32 model) -> i32 output_ptr` | Optional structured projection. The returned bytes are a JSON object of string keys to JSON values; the host validates and publishes it. | +| `plaza_wants` | `(i32 model) -> i32 output_ptr` | Optional capability request/subscription document, as specified below. | +| `plaza_snapshot` | `(i32 model) -> i32 output_ptr` | Optional UTF-8 serialization of the model for a journal checkpoint. Must be paired with `plaza_restore`. | +| `plaza_restore` | `(i32 snapshot_ptr, i32 snapshot_len) -> i32 model` | Reconstructs a model from bytes produced by `plaza_snapshot`. The input is allocated by the host and released after the call. A Roc program should return a sensible model for invalid snapshot text rather than trap. | +| `plaza_out_len` | `() -> i32 byte_len` | Returns the byte length of the most recent output from `view`, `layout`, `records`, `wants`, or `snapshot`. It is one shared output slot. | +| `plaza_error_ptr` | `() -> i32 ptr` | Optional diagnostic pointer exposed after a guest trap. In the Roc host it points to the captured Roc crash message in guest memory. | +| `plaza_error_len` | `() -> i32 byte_len` | Optional diagnostic length paired with `plaza_error_ptr`; the Roc host captures at most 4096 bytes. The bytes are not NUL-terminated and are diagnostic only, not a result/status channel. | ### Buffer lifetime and errors @@ -94,7 +94,7 @@ subscriptions and outstanding one-shot requests. Version 1 uses this shape: { "v": 1, "subscribe": ["players", "time.tick:5000"], - "requests": [{"id": "r1", "cap": "time.now"}] + "requests": [{ "id": "r1", "cap": "time.now" }] } ``` @@ -118,19 +118,19 @@ accepts them, so replay feeds the same events back through `plaza_update`. The runtime provider catalog is: -| Capability | Behavior | -| --- | --- | -| `time.now` | One-shot current Unix time in milliseconds (`{"now": ...}`). | -| `time.tick` | Subscribe as `time.tick:` with a positive interval; periodic host events while a participant is present, subject to the world's configured minimum interval and the four-interval limit. | -| `random.u64` | One-shot random unsigned 64-bit value (`{"value": ...}`). | -| `players` | Subscribe to participant join/leave events. | -| `players.list` | One-shot participant list, including ID, display name, and presence. | -| `chat.say` | Commit a chat line from `args.text`; result contains its sequence. | -| `chat.history` | Read recent chat lines; `args.count` defaults to 16 and is capped at 64. | -| `records.read` | Read a byte-bounded, key-ordered page of published records. `args.prefix` filters keys and `args.after` is an exclusive cursor; continue with `next_after`. | -| `schedule.at` | Schedule one event using printable-ASCII `args.id` (1–64 bytes) and Unix-millisecond `args.at`; at most 64 schedules may be pending, past times fire on the next wakeup, and times more than 30 days ahead are refused. | -| `schedule.cancel` | Cancel a pending schedule by printable-ASCII `args.id`; result reports `{"cancelled": bool}`. | -| `world.info` | Read the world ID and current sequence. | +| Capability | Behavior | +| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `time.now` | One-shot current Unix time in milliseconds (`{"now": ...}`). | +| `time.tick` | Subscribe as `time.tick:` with a positive interval; periodic host events while a participant is present, subject to the world's configured minimum interval and the four-interval limit. | +| `random.u64` | One-shot random unsigned 64-bit value (`{"value": ...}`). | +| `players` | Subscribe to participant join/leave events. | +| `players.list` | One-shot participant list, including ID, display name, and presence. | +| `chat.say` | Commit a chat line from `args.text`; result contains its sequence. | +| `chat.history` | Read recent chat lines; `args.count` defaults to 16 and is capped at 64. | +| `records.read` | Read a byte-bounded, key-ordered page of published records. `args.prefix` filters keys and `args.after` is an exclusive cursor; continue with `next_after`. | +| `schedule.at` | Schedule one event using printable-ASCII `args.id` (1–64 bytes) and Unix-millisecond `args.at`; at most 64 schedules may be pending, past times fire on the next wakeup, and times more than 30 days ahead are refused. | +| `schedule.cancel` | Cancel a pending schedule by printable-ASCII `args.id`; result reports `{"cancelled": bool}`. | +| `world.info` | Read the world ID and current sequence. | The `Key`, `Screen`, `RocJson`, `RocGrid`, `RocCap`, and `RocText` names are platform modules exposed to Roc source, not runtime request providers. The diff --git a/pkgs/id/hosted-worker/src/routing.ts b/pkgs/id/hosted-worker/src/routing.ts index a57c81483..dab361238 100644 --- a/pkgs/id/hosted-worker/src/routing.ts +++ b/pkgs/id/hosted-worker/src/routing.ts @@ -65,10 +65,18 @@ export function userStub( try { restricted = ns.jurisdiction(jurisdiction); } catch { - throw new FailClosed(503, "jurisdiction_unavailable", "jurisdiction-restricted namespace unavailable; failing closed"); + throw new FailClosed( + 503, + "jurisdiction_unavailable", + "jurisdiction-restricted namespace unavailable; failing closed", + ); } if (!restricted || typeof restricted.idFromName !== "function" || typeof restricted.get !== "function") { - throw new FailClosed(503, "jurisdiction_unavailable", "jurisdiction-restricted namespace unavailable; failing closed"); + throw new FailClosed( + 503, + "jurisdiction_unavailable", + "jurisdiction-restricted namespace unavailable; failing closed", + ); } const id = restricted.idFromName(bindingId); return restricted.get(id); diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 9b7310804..fab36fa3d 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -56,23 +56,14 @@ export class UserDO { // Versioned, idempotent schema bootstrap before serving. this.ready = state.blockConcurrencyWhile(async () => { const sql = this.state.storage.sql; - sql.exec( - "CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)", - ); - sql.exec( - "CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)", - ); - sql.exec( - "INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)", - "schema_version", String(SCHEMA_VERSION), - ); + sql.exec("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + sql.exec("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + sql.exec("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)", "schema_version", String(SCHEMA_VERSION)); }); } private meta(key: string): string | null { - const rows = this.state.storage.sql - .exec("SELECT value FROM meta WHERE key = ?", key) - .toArray(); + const rows = this.state.storage.sql.exec("SELECT value FROM meta WHERE key = ?", key).toArray(); return rows.length === 0 ? null : String(rows[0].value); } @@ -84,7 +75,11 @@ export class UserDO { const jurisdiction = parseJurisdiction(req.headers.get(HDR_JURISDICTION)); const runtimeJurisdiction = this.state.id.jurisdiction; if (typeof runtimeJurisdiction === "string" && runtimeJurisdiction !== jurisdiction) { - throw new FailClosed(409, "jurisdiction_mismatch", "object jurisdiction does not match routed jurisdiction; failing closed"); + throw new FailClosed( + 409, + "jurisdiction_mismatch", + "object jurisdiction does not match routed jurisdiction; failing closed", + ); } const boundBinding = this.meta("binding_id"); const boundJurisdiction = this.meta("jurisdiction"); @@ -94,10 +89,17 @@ export class UserDO { // rows are written together before any data route runs. this.state.storage.sql.exec( "INSERT INTO meta (key, value) VALUES (?, ?), (?, ?)", - "binding_id", bindingId, "jurisdiction", jurisdiction, + "binding_id", + bindingId, + "jurisdiction", + jurisdiction, ); } else if (boundBinding !== bindingId || boundJurisdiction !== jurisdiction) { - throw new FailClosed(409, "identity_mismatch", "object is bound to a different binding/jurisdiction; failing closed"); + throw new FailClosed( + 409, + "identity_mismatch", + "object is bound to a different binding/jurisdiction; failing closed", + ); } return { bindingId, jurisdiction }; } @@ -126,9 +128,7 @@ export class UserDO { return json({ key: kvMatch[1], stored: true }); } if (kvMatch && req.method === "GET") { - const rows = this.state.storage.sql - .exec("SELECT value FROM kv WHERE key = ?", kvMatch[1]) - .toArray(); + const rows = this.state.storage.sql.exec("SELECT value FROM kv WHERE key = ?", kvMatch[1]).toArray(); if (rows.length === 0) return json({ error: "not_found" }, 404); return json({ key: kvMatch[1], value: String(rows[0].value) }); } diff --git a/pkgs/id/hosted-worker/test/routing.test.ts b/pkgs/id/hosted-worker/test/routing.test.ts index c9dca4076..84f3dc198 100644 --- a/pkgs/id/hosted-worker/test/routing.test.ts +++ b/pkgs/id/hosted-worker/test/routing.test.ts @@ -23,9 +23,18 @@ test("jurisdiction must be present and supported", () => { test("userStub takes id and stub from the restricted namespace only", () => { const calls: string[] = []; const restricted = { - jurisdiction(j: string) { calls.push("jurisdiction:" + j); return restricted; }, - idFromName(name: string) { calls.push("idFromName:" + name); return { name }; }, - get(id: unknown) { calls.push("get"); return { fetch: async () => new Response("ok") }; }, + jurisdiction(j: string) { + calls.push("jurisdiction:" + j); + return restricted; + }, + idFromName(name: string) { + calls.push("idFromName:" + name); + return { name }; + }, + get(id: unknown) { + calls.push("get"); + return { fetch: async () => new Response("ok") }; + }, }; userStub(restricted, BINDING, "eu"); assert.deepEqual(calls, ["jurisdiction:eu", "idFromName:" + BINDING, "get"]); @@ -33,9 +42,18 @@ test("userStub takes id and stub from the restricted namespace only", () => { test("userStub fails closed when restriction is unavailable", () => { const ns = { - jurisdiction(): never { throw new Error("Jurisdiction restrictions are not implemented in workerd."); }, - idFromName(name: string) { return { name }; }, - get(id: unknown) { return { fetch: async () => new Response("unrestricted") }; }, + jurisdiction(): never { + throw new Error("Jurisdiction restrictions are not implemented in workerd."); + }, + idFromName(name: string) { + return { name }; + }, + get(id: unknown) { + return { fetch: async () => new Response("unrestricted") }; + }, }; - assert.throws(() => userStub(ns, BINDING, "us"), (e: unknown) => e instanceof FailClosed && e.status === 503); + assert.throws( + () => userStub(ns, BINDING, "us"), + (e: unknown) => e instanceof FailClosed && e.status === 503, + ); }); diff --git a/pkgs/id/src/abuse.rs b/pkgs/id/src/abuse.rs index a616826f4..de252f630 100644 --- a/pkgs/id/src/abuse.rs +++ b/pkgs/id/src/abuse.rs @@ -268,7 +268,6 @@ impl Default for AbusePolicy { } } - /// Which way traffic crosses a budget scope (#2247). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Direction { @@ -499,7 +498,10 @@ impl WindowCounter { /// True when both fixed windows are empty, so the state carries /// no information and may be dropped. fn is_empty(&self) -> bool { - self.cur_bytes == 0 && self.cur_messages == 0 && self.prev_bytes == 0 && self.prev_messages == 0 + self.cur_bytes == 0 + && self.cur_messages == 0 + && self.prev_bytes == 0 + && self.prev_messages == 0 } /// True when, rolled to `now_ms`, this counter would be empty: @@ -721,11 +723,7 @@ impl AbuseEvaluator { /// the app-wide, per-endpoint (or per-counterparty override), /// and direct-IP scopes in addition to the token buckets. #[must_use] - pub fn with_budgets( - policy: AbusePolicy, - local_node: NodeId, - budgets: BudgetPolicy, - ) -> Self { + pub fn with_budgets(policy: AbusePolicy, local_node: NodeId, budgets: BudgetPolicy) -> Self { let mut evaluator = Self::new(policy, local_node); evaluator.budgets = Some(budgets); evaluator @@ -772,7 +770,11 @@ impl AbuseEvaluator { ), ]; if let Some(ip) = direct_ip { - scopes.push((BudgetKey::Ip(ip), BudgetScope::Ip(ip), policy.per_ip.clone())); + scopes.push(( + BudgetKey::Ip(ip), + BudgetScope::Ip(ip), + policy.per_ip.clone(), + )); } scopes } @@ -793,10 +795,12 @@ impl AbuseEvaluator { let mut retry_ms = 0_u64; let mut refused = false; for (key, _scope, limits) in &scopes { - let counters = self - .budget_state - .entry(*key) - .or_insert_with(|| limits.iter().map(|l| WindowCounter::new(l, now_ms)).collect()); + let counters = self.budget_state.entry(*key).or_insert_with(|| { + limits + .iter() + .map(|l| WindowCounter::new(l, now_ms)) + .collect() + }); for (counter, limit) in counters.iter_mut().zip(limits.iter()) { counter.roll(now_ms); if !counter.can_admit(limit, bytes, now_ms) { @@ -819,10 +823,12 @@ impl AbuseEvaluator { ) { let scopes = self.budget_scopes(direction, endpoint, direct_ip); for (key, _scope, limits) in &scopes { - let counters = self - .budget_state - .entry(*key) - .or_insert_with(|| limits.iter().map(|l| WindowCounter::new(l, now_ms)).collect()); + let counters = self.budget_state.entry(*key).or_insert_with(|| { + limits + .iter() + .map(|l| WindowCounter::new(l, now_ms)) + .collect() + }); for counter in counters.iter_mut() { counter.roll(now_ms); counter.record(bytes); @@ -933,9 +939,10 @@ impl AbuseEvaluator { let (scope, limits): (BudgetScope, &[BudgetLimit]) = match key { BudgetKey::AppInbound => (BudgetScope::AppInbound, &policy.app_inbound), BudgetKey::AppOutbound => (BudgetScope::AppOutbound, &policy.app_outbound), - BudgetKey::Peer(endpoint) => { - (BudgetScope::Peer(*endpoint), policy.limits_for_peer(endpoint)) - } + BudgetKey::Peer(endpoint) => ( + BudgetScope::Peer(*endpoint), + policy.limits_for_peer(endpoint), + ), BudgetKey::Ip(ip) => (BudgetScope::Ip(*ip), &policy.per_ip), }; for (counter, limit) in counters.iter().zip(limits.iter()) { @@ -1551,9 +1558,10 @@ mod budget_tests { // 1_000-byte default. eval.check_budget(Direction::Inbound, capped, None, 100, 0) .expect("at override cap"); - assert!(eval - .check_budget(Direction::Inbound, capped, None, 1, 0) - .is_err()); + assert!( + eval.check_budget(Direction::Inbound, capped, None, 1, 0) + .is_err() + ); // The raised peer may exceed the default per-peer budget. eval.check_budget(Direction::Inbound, raised, None, 3_000, 0) .expect("override raises the cap"); @@ -1591,9 +1599,10 @@ mod budget_tests { eval.check_budget(Direction::Inbound, endpoint(1), Some(ip), 700, 0) .expect("first endpoint on the ip"); // A second endpoint behind the same direct IP shares its budget. - assert!(eval - .check_budget(Direction::Inbound, endpoint(2), Some(ip), 400, 0) - .is_err()); + assert!( + eval.check_budget(Direction::Inbound, endpoint(2), Some(ip), 400, 0) + .is_err() + ); // Relayed traffic (no directly observed IP) charges no IP scope. eval.check_budget(Direction::Inbound, endpoint(2), None, 400, 0) .expect("no ip observed, no ip scope"); @@ -1612,9 +1621,10 @@ mod budget_tests { let mut eval = budgeted(policy); eval.check_budget(Direction::Inbound, endpoint(1), None, 800, 0) .expect("first peer inbound"); - assert!(eval - .check_budget(Direction::Inbound, endpoint(2), None, 300, 0) - .is_err()); + assert!( + eval.check_budget(Direction::Inbound, endpoint(2), None, 300, 0) + .is_err() + ); // Outbound has its own app-wide scope. eval.check_budget(Direction::Outbound, endpoint(2), None, 300, 0) .expect("outbound separate"); @@ -1628,9 +1638,10 @@ mod budget_tests { let ep = endpoint(3); eval.check_budget(Direction::Inbound, ep, None, 100, 0) .expect("full window"); - assert!(eval - .check_budget(Direction::Inbound, ep, None, 1, 0) - .is_err()); + assert!( + eval.check_budget(Direction::Inbound, ep, None, 1, 0) + .is_err() + ); // Two windows later the usage has fully aged out. eval.check_budget(Direction::Inbound, ep, None, 100, 2_000) .expect("recovered after roll"); diff --git a/pkgs/id/src/app_manifest.rs b/pkgs/id/src/app_manifest.rs index 432b49db7..0b1e4bcf8 100644 --- a/pkgs/id/src/app_manifest.rs +++ b/pkgs/id/src/app_manifest.rs @@ -813,8 +813,7 @@ commands = ["play"] "a/./b", "", ] { - let source = - format!("{MANIFEST}\n[resources]\nfiles = [\"{entry}\"]\n"); + let source = format!("{MANIFEST}\n[resources]\nfiles = [\"{entry}\"]\n"); let error = parse_app_manifest(&source, "tic-tac-toe").unwrap_err(); let message = error.to_string(); assert!( @@ -825,8 +824,7 @@ commands = ["play"] // Confined entries — plain files, nested paths, and the design's // glob shapes — stay accepted. for entry in ["assets/logo.png", "web/templates/index.html", "assets/**"] { - let source = - format!("{MANIFEST}\n[resources]\nfiles = [\"{entry}\"]\n"); + let source = format!("{MANIFEST}\n[resources]\nfiles = [\"{entry}\"]\n"); assert!( parse_app_manifest(&source, "tic-tac-toe").is_ok(), "confined entry {entry:?} is accepted" diff --git a/pkgs/id/src/boards.rs b/pkgs/id/src/boards.rs index b22a89964..1454eec0c 100644 --- a/pkgs/id/src/boards.rs +++ b/pkgs/id/src/boards.rs @@ -751,10 +751,7 @@ impl BoardGraph { } BoardObject::Theme(value) => { if let Some(source) = &value.forked_from { - ensure!( - source != &signed.hash()?, - "a theme cannot fork from itself" - ); + ensure!(source != &signed.hash()?, "a theme cannot fork from itself"); let source_object = self .objects .get(source) @@ -905,9 +902,7 @@ impl BoardGraph { let mut set: BTreeSet = self .objects .iter() - .filter(|(hash, signed)| { - *hash == board || signed.object.board_ref() == Some(board) - }) + .filter(|(hash, signed)| *hash == board || signed.object.board_ref() == Some(board)) .map(|(hash, _)| hash.clone()) .collect(); let mut frontier: Vec = set.iter().cloned().collect(); @@ -925,9 +920,7 @@ impl BoardGraph { _ => Vec::new(), }; for dependency in dependencies { - if self.objects.contains_key(dependency) - && set.insert(dependency.clone()) - { + if self.objects.contains_key(dependency) && set.insert(dependency.clone()) { frontier.push(dependency.clone()); } } @@ -1014,16 +1007,14 @@ impl BoardGraph { /// lagging replica is never silently presented as current, and a /// newer signed object is never overwritten by an older replica /// (the graph is append-only and keeps every signed version). - pub fn replica_status_against(&self, board: &ArtifactHash, source: &BoardGraph) -> ReplicaStatus { + pub fn replica_status_against( + &self, + board: &ArtifactHash, + source: &BoardGraph, + ) -> ReplicaStatus { let expected = source.board_object_set(board); let mut missing: Vec = expected - .difference( - &self - .objects - .keys() - .cloned() - .collect::>(), - ) + .difference(&self.objects.keys().cloned().collect::>()) .cloned() .collect(); if expected.is_empty() { @@ -1203,10 +1194,7 @@ impl BoardGraph { .filter(|(hash, _)| active_records.contains(hash)) .map(|(_, previous)| previous.clone()) .collect(); - let next: BTreeSet = active_records - .difference(&named) - .cloned() - .collect(); + let next: BTreeSet = active_records.difference(&named).cloned().collect(); if next == active_records { break; } @@ -1261,10 +1249,8 @@ impl BoardGraph { .filter(|(hash, _)| active_attestations.contains(hash)) .filter_map(|(_, previous)| previous.clone()) .collect(); - let next: BTreeSet = eligible_attestations - .difference(&named) - .cloned() - .collect(); + let next: BTreeSet = + eligible_attestations.difference(&named).cloned().collect(); if next == active_attestations { break; } @@ -1290,9 +1276,7 @@ impl BoardGraph { }) .collect(); let owner = root.artifact.author.as_str(); - let has_authority = |author: &str| { - author == owner || current_moderators.contains(author) - }; + let has_authority = |author: &str| author == owner || current_moderators.contains(author); // Board layer facts, gathered in deterministic (content-hash) // order from the map. @@ -1310,18 +1294,15 @@ impl BoardGraph { // did) carry authority. Only empowered, current // records change the projection. moderation_log.push(hash.clone()); - if superseded.contains(hash) - || !has_authority(signed.artifact.author.as_str()) + if superseded.contains(hash) || !has_authority(signed.artifact.author.as_str()) { continue; } match value.action { ModerationActionKind::Hide => { *hide_balance.entry(value.target.clone()).or_default() += 1; - hide_source.insert( - value.target.clone(), - (hash.clone(), value.reason.clone()), - ); + hide_source + .insert(value.target.clone(), (hash.clone(), value.reason.clone())); } ModerationActionKind::Restore => { *hide_balance.entry(value.target.clone()).or_default() -= 1; @@ -1372,8 +1353,7 @@ impl BoardGraph { .unwrap_or((hash.clone(), None)); (Some(action), reason) } else { - let (action, reason) = - tombstone.cloned().unwrap_or((hash.clone(), None)); + let (action, reason) = tombstone.cloned().unwrap_or((hash.clone(), None)); (Some(action), reason) }; hidden.push(HiddenObject { @@ -2194,50 +2174,56 @@ mod tests { let author = key(21); let mut bad_name = BTreeMap::new(); bad_name.insert("Accent".to_owned(), "#ffffff".to_owned()); - assert!(SignedBoardObject::sign( - &author, - 1, - "", - BoardObject::Theme(Theme { - name: "Bad".to_owned(), - tokens: bad_name, - layout: ThemeLayout::List, - assets: Vec::new(), - forked_from: None, - }), - ) - .is_err()); + assert!( + SignedBoardObject::sign( + &author, + 1, + "", + BoardObject::Theme(Theme { + name: "Bad".to_owned(), + tokens: bad_name, + layout: ThemeLayout::List, + assets: Vec::new(), + forked_from: None, + }), + ) + .is_err() + ); let mut empty_value = BTreeMap::new(); empty_value.insert("accent".to_owned(), String::new()); - assert!(SignedBoardObject::sign( - &author, - 1, - "", - BoardObject::Theme(Theme { - name: "Bad".to_owned(), - tokens: empty_value, - layout: ThemeLayout::List, - assets: Vec::new(), - forked_from: None, - }), - ) - .is_err()); + assert!( + SignedBoardObject::sign( + &author, + 1, + "", + BoardObject::Theme(Theme { + name: "Bad".to_owned(), + tokens: empty_value, + layout: ThemeLayout::List, + assets: Vec::new(), + forked_from: None, + }), + ) + .is_err() + ); let asset = ArtifactHash::new("c".repeat(64)).unwrap(); - assert!(SignedBoardObject::sign( - &author, - 1, - "", - BoardObject::Theme(Theme { - name: "Bad".to_owned(), - tokens: BTreeMap::new(), - layout: ThemeLayout::Compact, - assets: vec![asset.clone(), asset], - forked_from: None, - }), - ) - .is_err()); + assert!( + SignedBoardObject::sign( + &author, + 1, + "", + BoardObject::Theme(Theme { + name: "Bad".to_owned(), + tokens: BTreeMap::new(), + layout: ThemeLayout::Compact, + assets: vec![asset.clone(), asset], + forked_from: None, + }), + ) + .is_err() + ); } #[test] @@ -2255,7 +2241,9 @@ mod tests { assert!(graph.insert(themed_board(&author, other_board)).is_err()); let root_hash = graph.insert(themed_board(&author, theme_hash)).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); let BoardObject::Theme(expected) = theme_signed.object else { unreachable!("theme helper builds a theme") }; @@ -2275,9 +2263,16 @@ mod tests { let author = key(24); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let post_hash = graph - .insert(post(&author, root_hash.clone(), thread_hash, "buy my stuff")) + .insert(post( + &author, + root_hash.clone(), + thread_hash, + "buy my stuff", + )) .unwrap(); let hide = moderation( @@ -2290,7 +2285,9 @@ mod tests { ); let hide_hash = graph.insert(hide).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(!view.objects.contains(&post_hash)); assert_eq!(view.moderation_log, vec![hide_hash.clone()]); assert_eq!(view.hidden.len(), 1); @@ -2310,7 +2307,9 @@ mod tests { None, ); graph.insert(restore).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.objects.contains(&post_hash)); assert!(view.hidden.is_empty()); assert_eq!(view.moderation_log.len(), 2); @@ -2325,7 +2324,9 @@ mod tests { Some("spam again"), ); graph.insert(rehide).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); assert_eq!(view.hidden[0].reason.as_deref(), Some("spam again")); } @@ -2337,9 +2338,16 @@ mod tests { let bob = key(27); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let alice_post = graph - .insert(post(&alice, root_hash.clone(), thread_hash.clone(), "alice")) + .insert(post( + &alice, + root_hash.clone(), + thread_hash.clone(), + "alice", + )) .unwrap(); let bob_post = graph .insert(post(&bob, root_hash.clone(), thread_hash, "bob")) @@ -2363,7 +2371,9 @@ mod tests { assert!(!view.objects.contains(&alice_post)); assert!(!view.objects.contains(&bob_post)); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.objects.contains(&alice_post)); assert!(view.objects.contains(&bob_post)); assert!(view.hidden.is_empty()); @@ -2376,7 +2386,9 @@ mod tests { let author = key(32); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let post_hash = graph .insert(post(&author, root_hash.clone(), thread_hash, "hello")) .unwrap(); @@ -2404,7 +2416,9 @@ mod tests { Some("spam"), )) .unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); assert_eq!(view.hidden[0].object, post_hash); @@ -2422,7 +2436,9 @@ mod tests { ) .unwrap(); graph.insert(revoke).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); // The revoked moderator's hide no longer has an effect... assert!(view.objects.contains(&post_hash)); assert!(view.hidden.is_empty()); @@ -2436,9 +2452,16 @@ mod tests { let author = key(34); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let first = graph - .insert(post(&author, root_hash.clone(), thread_hash.clone(), "first")) + .insert(post( + &author, + root_hash.clone(), + thread_hash.clone(), + "first", + )) .unwrap(); let second = graph .insert(post(&author, root_hash.clone(), thread_hash, "second")) @@ -2456,14 +2479,19 @@ mod tests { ) .unwrap() }; - let first_tombstone = graph.insert(tombstone(first.clone(), "wrong thread")).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let first_tombstone = graph + .insert(tombstone(first.clone(), "wrong thread")) + .unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); assert_eq!(view.hidden[0].object, first); assert_eq!(view.hidden[0].reason.as_deref(), Some("wrong thread")); - let second_tombstone = - graph.insert(tombstone(second.clone(), "duplicate")).unwrap(); + let second_tombstone = graph + .insert(tombstone(second.clone(), "duplicate")) + .unwrap(); let supersede = SignedBoardObject::sign( &author, 3, @@ -2476,7 +2504,9 @@ mod tests { ) .unwrap(); graph.insert(supersede).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.objects.contains(&first)); assert_eq!(view.hidden.len(), 1); assert_eq!(view.hidden[0].object, second); @@ -2488,9 +2518,13 @@ mod tests { let author = key(35); let mut graph = BoardGraph::default(); let theme_hash = graph.insert(theme(&author, 1, None)).unwrap(); - let root_hash = graph.insert(themed_board(&author, theme_hash.clone())).unwrap(); + let root_hash = graph + .insert(themed_board(&author, theme_hash.clone())) + .unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.theme.is_some()); let mut layers = ViewLayers::default(); @@ -2508,7 +2542,9 @@ mod tests { let author = key(38); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let post_hash = graph .insert(post(&author, root_hash.clone(), thread_hash, "hello")) .unwrap(); @@ -2538,7 +2574,9 @@ mod tests { Some("spam"), )) .unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); // Revocation by generic Supersede record (not the attestation's @@ -2556,7 +2594,9 @@ mod tests { ) .unwrap(); graph.insert(supersede).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.objects.contains(&post_hash)); assert!(view.hidden.is_empty()); assert_eq!(view.moderation_log.len(), 1); @@ -2573,25 +2613,28 @@ mod tests { let moderator_key = hex_encode(&moderator.verifying_key().to_bytes()); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let post_hash = graph .insert(post(&author, root_hash.clone(), thread_hash, "hello")) .unwrap(); - let attestation = |seq: u64, member: String, granted: bool, supersedes: Option| { - SignedBoardObject::sign( - &owner, - seq, - "", - BoardObject::RoleAttestation(RoleAttestation { - board: root_hash.clone(), - member, - role: BoardRole::Moderator, - granted, - supersedes, - }), - ) - .unwrap() - }; + let attestation = + |seq: u64, member: String, granted: bool, supersedes: Option| { + SignedBoardObject::sign( + &owner, + seq, + "", + BoardObject::RoleAttestation(RoleAttestation { + board: root_hash.clone(), + member, + role: BoardRole::Moderator, + granted, + supersedes, + }), + ) + .unwrap() + }; let grant_hash = graph .insert(attestation(2, moderator_key.clone(), true, None)) .unwrap(); @@ -2605,14 +2648,23 @@ mod tests { Some("spam"), )) .unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); // Revoke: the moderator's Hide stops applying. let revocation_hash = graph - .insert(attestation(3, moderator_key.clone(), false, Some(grant_hash.clone()))) + .insert(attestation( + 3, + moderator_key.clone(), + false, + Some(grant_hash.clone()), + )) + .unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) .unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); assert!(view.objects.contains(&post_hash)); assert!(view.hidden.is_empty()); @@ -2639,7 +2691,9 @@ mod tests { ) .unwrap(); graph.insert(supersede).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert_eq!(view.hidden.len(), 1); assert!(!view.objects.contains(&post_hash)); } @@ -2657,7 +2711,9 @@ mod tests { let moderator_key = hex_encode(&moderator.verifying_key().to_bytes()); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let post_hash = graph .insert(post(&author, root_hash.clone(), thread_hash, "hello")) .unwrap(); @@ -2710,7 +2766,9 @@ mod tests { .insert(attestation(5, false, Some(second_grant))) .unwrap(); assert_eq!(hidden(&graph), 0); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); assert!(view.objects.contains(&post_hash)); } @@ -2720,7 +2778,9 @@ mod tests { let author = key(40); let mut graph = BoardGraph::default(); let root_hash = graph.insert(board(&owner)).unwrap(); - let thread_hash = graph.insert(thread(&owner, root_hash.clone(), "General")).unwrap(); + let thread_hash = graph + .insert(thread(&owner, root_hash.clone(), "General")) + .unwrap(); let mut posts = Vec::new(); for body in ["a", "b", "c", "d"] { posts.push( @@ -2742,11 +2802,17 @@ mod tests { ) .unwrap() }; - let first = graph.insert(supersede(2, posts[0].clone(), posts[1].clone())).unwrap(); - let second = graph.insert(supersede(3, posts[2].clone(), posts[3].clone())).unwrap(); + let first = graph + .insert(supersede(2, posts[0].clone(), posts[1].clone())) + .unwrap(); + let second = graph + .insert(supersede(3, posts[2].clone(), posts[3].clone())) + .unwrap(); graph.insert(supersede(4, first, second)).unwrap(); - let view = graph.compose_view(&root_hash, &ViewLayers::default()).unwrap(); + let view = graph + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); // The first supersede was itself superseded: post A is current // again. The second supersede is active: post C is replaced. assert!(view.objects.contains(&posts[0])); @@ -2820,8 +2886,12 @@ mod tests { let host = key(9); let mut source = BoardGraph::default(); let root = source.insert(board(&owner)).unwrap(); - let thread = source.insert(thread(&owner, root.clone(), "welcome")).unwrap(); - source.insert(post(&owner, root.clone(), thread, "hello")).unwrap(); + let thread = source + .insert(thread(&owner, root.clone(), "welcome")) + .unwrap(); + source + .insert(post(&owner, root.clone(), thread, "hello")) + .unwrap(); source .insert(listing(&owner, 1, root.clone(), &host, 1, true, None)) .unwrap(); @@ -2829,8 +2899,14 @@ mod tests { let mut replica = BoardGraph::default(); let report = replica.replicate_board_from(&source, &root).unwrap(); assert_eq!(report.status.state, ReplicaState::Complete); - assert_eq!(report.transferred.len(), source.board_object_set(&root).len()); - assert_eq!(replica.board_object_set(&root), source.board_object_set(&root)); + assert_eq!( + report.transferred.len(), + source.board_object_set(&root).len() + ); + assert_eq!( + replica.board_object_set(&root), + source.board_object_set(&root) + ); // A second pass is a no-op: the hosts have converged. let again = replica.replicate_board_from(&source, &root).unwrap(); @@ -2846,13 +2922,18 @@ mod tests { let owner = key(7); let mut source = BoardGraph::default(); let theme_hash = source.insert(theme(&owner, 1, None)).unwrap(); - let root = source.insert(themed_board(&owner, theme_hash.clone())).unwrap(); + let root = source + .insert(themed_board(&owner, theme_hash.clone())) + .unwrap(); let mut replica = BoardGraph::default(); let report = replica.replicate_board_from(&source, &root).unwrap(); assert_eq!(report.status.state, ReplicaState::Complete); assert!(report.transferred.contains(&theme_hash)); - assert_eq!(replica.board_object_set(&root), source.board_object_set(&root)); + assert_eq!( + replica.board_object_set(&root), + source.board_object_set(&root) + ); } #[test] @@ -2954,5 +3035,4 @@ mod tests { assert_eq!(graph.len(), before); assert!(HostServingPolicy::default().serves_board(&root)); } - } diff --git a/pkgs/id/src/chain.rs b/pkgs/id/src/chain.rs index 58fab2f72..926b2c9eb 100644 --- a/pkgs/id/src/chain.rs +++ b/pkgs/id/src/chain.rs @@ -888,7 +888,7 @@ mod golden { use dcbor::{ByteString, CBOR}; use p2panda_core::{AnyHeader, Hash, Header, SigningKey}; - use super::{decode, sign, ChainExt, Event, DOMAIN_TAG}; + use super::{ChainExt, DOMAIN_TAG, Event, decode, sign}; /// The test key: the 32 bytes 00 through 1f. It is not a real key. fn key() -> SigningKey { diff --git a/pkgs/id/src/chat.rs b/pkgs/id/src/chat.rs index aed57f78d..af9628dc0 100644 --- a/pkgs/id/src/chat.rs +++ b/pkgs/id/src/chat.rs @@ -181,9 +181,7 @@ impl ChatMessage { ))); } if sanitize_chat(&self.text) != self.text { - return Err(ChatError::Text( - "the text is not sanitized".to_owned(), - )); + return Err(ChatError::Text("the text is not sanitized".to_owned())); } if self.links.len() > MAX_LINKS { return Err(ChatError::Links(format!( @@ -259,8 +257,11 @@ pub fn project(records: impl IntoIterator) -> Vec let mut pending: HashMap<[u8; 32], usize> = HashMap::new(); for record in by_id.values() { let mut parents = 0; - let mut parent_ids: Vec<[u8; 32]> = - record.after.iter().map(|parent| *parent.as_bytes()).collect(); + let mut parent_ids: Vec<[u8; 32]> = record + .after + .iter() + .map(|parent| *parent.as_bytes()) + .collect(); if let Some(backlink) = &record.backlink { parent_ids.push(*backlink.as_bytes()); } @@ -329,7 +330,10 @@ mod tests { ChatRecord { id: Hash::digest(&[id]), author: author(id), - after: after.iter().map(|parent| Hash::digest(&[*parent])).collect(), + after: after + .iter() + .map(|parent| Hash::digest(&[*parent])) + .collect(), backlink: None, message: ChatMessage::new(text, Vec::new()).unwrap(), } @@ -389,8 +393,9 @@ mod tests { #[test] fn test_link_kinds_are_only_blob_and_event() { - let parsed: Result = - serde_json::from_str(r#"{"kind":"file","hash":"0000000000000000000000000000000000000000000000000000000000000000","author":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"hint":null}"#); + let parsed: Result = serde_json::from_str( + r#"{"kind":"file","hash":"0000000000000000000000000000000000000000000000000000000000000000","author":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"hint":null}"#, + ); assert!(parsed.is_err()); } diff --git a/pkgs/id/src/chat_presence.rs b/pkgs/id/src/chat_presence.rs index 37db8f007..86772fdb3 100644 --- a/pkgs/id/src/chat_presence.rs +++ b/pkgs/id/src/chat_presence.rs @@ -712,7 +712,10 @@ mod tests { Liveness::Offline ); let roster = table.roster_at(&chan, &[alice], replay_at); - assert!(!roster[0].typing, "a replayed typing claim must not refresh"); + assert!( + !roster[0].typing, + "a replayed typing claim must not refresh" + ); } #[test] @@ -736,7 +739,9 @@ mod tests { forged.ts += 1; assert!(!forged.verify()); let mut forged = hb; - forged.node = SigningKey::from_bytes(&[8u8; 32]).verifying_key().to_bytes(); + forged.node = SigningKey::from_bytes(&[8u8; 32]) + .verifying_key() + .to_bytes(); assert!(!forged.verify()); } @@ -898,5 +903,4 @@ mod tests { assert_eq!(table.liveness_at(&alice, &chan, 4_200), Liveness::Live); } } - } diff --git a/pkgs/id/src/commands/find.rs b/pkgs/id/src/commands/find.rs index b2dcaa24c..597abe825 100644 --- a/pkgs/id/src/commands/find.rs +++ b/pkgs/id/src/commands/find.rs @@ -1093,7 +1093,9 @@ mod tests { }, ]; - let error = plan_download_paths("out", &matches).unwrap_err().to_string(); + let error = plan_download_paths("out", &matches) + .unwrap_err() + .to_string(); assert!(error.contains("destination collision"), "{error}"); assert!(error.contains("one/report.txt"), "{error}"); assert!(error.contains("two/report.txt"), "{error}"); @@ -1417,7 +1419,6 @@ mod tests { assert!(result.contains("lines:")); // Header should show line count } - // Regression (#1787): lines = usize::MAX/2 + 1 must not overflow the // printers' doubling — saturating arithmetic prints short content once, // with no omitted-count line and no panic. diff --git a/pkgs/id/src/currency.rs b/pkgs/id/src/currency.rs index f3fdb06ab..c48fac3e0 100644 --- a/pkgs/id/src/currency.rs +++ b/pkgs/id/src/currency.rs @@ -548,8 +548,14 @@ mod tests { let forward_order = [(author, rate_8000.clone()), (author, rate_9000.clone())]; let reverse_order = [(author, rate_9000.clone()), (author, rate_8000)]; let expected = Some(AuthorisationState::Live(rate_9000)); - assert_eq!(fold_authorisation(7, &author, &forward_order, &[]), expected); - assert_eq!(fold_authorisation(7, &author, &reverse_order, &[]), expected); + assert_eq!( + fold_authorisation(7, &author, &forward_order, &[]), + expected + ); + assert_eq!( + fold_authorisation(7, &author, &reverse_order, &[]), + expected + ); } #[test] diff --git a/pkgs/id/src/currency_poc/intent.rs b/pkgs/id/src/currency_poc/intent.rs index 2af73c1a4..6b94459be 100644 --- a/pkgs/id/src/currency_poc/intent.rs +++ b/pkgs/id/src/currency_poc/intent.rs @@ -451,11 +451,7 @@ fn same_file(a: &Path, b: &Path) -> bool { /// treating the conversion as absent would let `prepare()` pass its /// never-replace guard, and overwriting would destroy the occupant's /// only write-ahead record. -fn canonical_occupant_error( - conversion_id: u128, - canonical: &Path, - occupant_id: u128, -) -> io::Error { +fn canonical_occupant_error(conversion_id: u128, canonical: &Path, occupant_id: u128) -> io::Error { io::Error::new( io::ErrorKind::InvalidData, format!( diff --git a/pkgs/id/src/currency_poc/tests.rs b/pkgs/id/src/currency_poc/tests.rs index c205ff695..d0a77f900 100644 --- a/pkgs/id/src/currency_poc/tests.rs +++ b/pkgs/id/src/currency_poc/tests.rs @@ -1104,7 +1104,10 @@ fn uppercase_extension_alias_is_scanned_and_blocks_conflicting_put() { let alias = dir.join(format!("{:032x}.JSON", 10)); std::fs::rename(dir.join(canonical_name(10)), &alias).expect("rename to .JSON alias"); - assert_eq!(store.get(10).expect("get via .JSON alias"), Some(original.clone())); + assert_eq!( + store.get(10).expect("get via .JSON alias"), + Some(original.clone()) + ); let listed = store.unresolved().expect("listing via .JSON alias"); assert_eq!(listed, vec![original.clone()]); @@ -1116,7 +1119,9 @@ fn uppercase_extension_alias_is_scanned_and_blocks_conflicting_put() { .put(&conflicting) .expect_err("conflicting put over the .JSON alias must fail closed"); assert!( - error.to_string().contains("refusing to write conversion 10"), + error + .to_string() + .contains("refusing to write conversion 10"), "unexpected put error: {error}" ); // The alias still holds the original record, byte for byte. @@ -1165,16 +1170,22 @@ fn canonical_file_holding_another_conversions_record_blocks_get_and_put() { let get_error = store.get(10).expect_err("occupied get must fail closed"); assert!( - get_error.to_string().contains("currently stores conversion 9"), + get_error + .to_string() + .contains("currently stores conversion 9"), "unexpected get error: {get_error}" ); let intruder = bare_record( 10, vec![funding_transfer(601, ISSUER_SRC, USER_SRC, 10_000, SRC)], ); - let put_error = store.put(&intruder).expect_err("occupied put must fail closed"); + let put_error = store + .put(&intruder) + .expect_err("occupied put must fail closed"); assert!( - put_error.to_string().contains("currently stores conversion 9"), + put_error + .to_string() + .contains("currently stores conversion 9"), "unexpected put error: {put_error}" ); assert_eq!( @@ -1186,7 +1197,10 @@ fn canonical_file_holding_another_conversions_record_blocks_get_and_put() { // it, and the listing yields it exactly once. assert_eq!(store.get(9).expect("get occupant"), Some(occupant)); let listed = store.unresolved().expect("listing with an occupant"); - assert_eq!(listed.iter().map(|r| r.conversion_id).collect::>(), vec![9]); + assert_eq!( + listed.iter().map(|r| r.conversion_id).collect::>(), + vec![9] + ); let _ = std::fs::remove_dir_all(&dir); } @@ -1209,11 +1223,13 @@ fn state_only_divergent_copies_resolve_to_the_most_advanced_state() { submitted.state = IntentState::Submitted; let (other_dir, mut other_store) = empty_file_store("states4578-b"); other_store.put(&submitted).expect("seed submitted"); - std::fs::copy(other_dir.join(canonical_name(11)), dir.join(canonical_name(11))) - .expect("plant advanced canonical copy"); + std::fs::copy( + other_dir.join(canonical_name(11)), + dir.join(canonical_name(11)), + ) + .expect("plant advanced canonical copy"); let _ = std::fs::remove_dir_all(&other_dir); - std::fs::copy(dir.join(canonical_name(11)), dir.join("stray.json")) - .expect("plant stray copy"); + std::fs::copy(dir.join(canonical_name(11)), dir.join("stray.json")).expect("plant stray copy"); // Downgrade the stray to the Recorded copy's bytes: rewrite it // from a fresh store holding only the Recorded record. let (old_dir, mut old_store) = empty_file_store("states4578-c"); @@ -1259,7 +1275,9 @@ fn put_never_deletes_a_filesystem_alias_of_the_canonical_file() { let mut submitted = recorded.clone(); submitted.state = IntentState::Submitted; - store.put(&submitted).expect("state-advancing put over an alias"); + store + .put(&submitted) + .expect("state-advancing put over an alias"); assert_eq!( store.get(10).expect("get after alias put"), @@ -1489,7 +1507,12 @@ fn live_failed_conversion_recovery_reports_resubmission_rejected() { .expect("read intent") .expect("intent still stored"); assert_eq!(stored.state, IntentState::Submitted); - assert!(executor.backend.transfers_with_user_data_128(777).is_empty()); + assert!( + executor + .backend + .transfers_with_user_data_128(777) + .is_empty() + ); assert_eq!( executor .backend diff --git a/pkgs/id/src/directory_auth.rs b/pkgs/id/src/directory_auth.rs index 45840502c..a60ba3670 100644 --- a/pkgs/id/src/directory_auth.rs +++ b/pkgs/id/src/directory_auth.rs @@ -504,7 +504,10 @@ mod tests { .issue_code(purpose.clone(), "c@d.co", now() + CODE_RESEND_MS) .unwrap(); assert!(auth.codes.contains_key("a@b.co")); - assert!(auth.check_code("a@b.co", &code, now() + CODE_RESEND_MS).is_err()); + assert!( + auth.check_code("a@b.co", &code, now() + CODE_RESEND_MS) + .is_err() + ); assert_eq!( auth.check_code("c@d.co", &other, now() + CODE_RESEND_MS) .unwrap(), diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index 0881cde02..9853f0a95 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -833,16 +833,13 @@ fn decide_in( match stored_by_id(txn, &prev_id)? { Some(prev) => { let predecessor = author_of(&prev) == author - && prev - .header - .extensions - .checkpoint - .as_ref() - .is_some_and(|prev_checkpoint| { + && prev.header.extensions.checkpoint.as_ref().is_some_and( + |prev_checkpoint| { prev_checkpoint.header == checkpoint.header && prev_checkpoint.segment.segment_seq + 1 == checkpoint.segment.segment_seq - }); + }, + ); if !predecessor { return Ok(Decision::Refuse(Refusal::Malformed( "a session checkpoint's prev_checkpoint is not the previous segment's checkpoint of the same session" diff --git a/pkgs/id/src/event_store/range.rs b/pkgs/id/src/event_store/range.rs index 611e6dde9..c3072589f 100644 --- a/pkgs/id/src/event_store/range.rs +++ b/pkgs/id/src/event_store/range.rs @@ -512,10 +512,7 @@ impl<'a> Reader<'a> { // zero payload group, so a multi-byte spelling that ends // in one (0x81 0x00 for 1) is a second wire spelling of // the same value and is refused (#2596). - ensure!( - i == 0 || b != 0, - "varint is not minimally encoded" - ); + ensure!(i == 0 || b != 0, "varint is not minimally encoded"); return Ok(x); } } @@ -1036,8 +1033,14 @@ mod tests { // Overlong spellings of the same values. assert!(read(&[0x80, 0x00]).is_err(), "0 spelled in 2 bytes"); assert!(read(&[0x81, 0x00]).is_err(), "1 spelled in 2 bytes"); - assert!(read(&[0xff, 0xff, 0x00]).is_err(), "0x3fff spelled in 3 bytes"); - assert!(read(&[0x80, 0x80, 0x81, 0x00]).is_err(), "0x4000 spelled in 4 bytes"); + assert!( + read(&[0xff, 0xff, 0x00]).is_err(), + "0x3fff spelled in 3 bytes" + ); + assert!( + read(&[0x80, 0x80, 0x81, 0x00]).is_err(), + "0x4000 spelled in 4 bytes" + ); assert!(read(&[0xff, 0x80, 0x00]).is_err(), "127 spelled in 3 bytes"); // Position 1: the frame header entry count. diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index 16f7b1871..8cbffed43 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -1760,8 +1760,10 @@ mod tests { let (_db, mut b) = open(); populate(&mut a, &[(1, 4)]); let (before_a, before_b) = (ids(&a), ids(&b)); - let gate = testing::open_gate() - .with_blocks(testing::stub_blocks(&[*testing::key(0xd1).public().as_bytes()], &[])); + let gate = testing::open_gate().with_blocks(testing::stub_blocks( + &[*testing::key(0xd1).public().as_bytes()], + &[], + )); let (dialer, acceptor) = loopback_gated( &mut a, &mut b, @@ -1778,7 +1780,10 @@ mod tests { refused.downcast_ref::().is_some(), "{refused:#}" ); - assert!(dialer.is_err(), "the dialer's session ends with the refusal"); + assert!( + dialer.is_err(), + "the dialer's session ends with the refusal" + ); assert_eq!(ids(&b), before_b, "no event crossed to the blocked peer"); assert_eq!(ids(&a), before_a, "the server's store is unchanged"); } diff --git a/pkgs/id/src/hosted_binding.rs b/pkgs/id/src/hosted_binding.rs index 9376ed357..dd1a89ffb 100644 --- a/pkgs/id/src/hosted_binding.rs +++ b/pkgs/id/src/hosted_binding.rs @@ -74,7 +74,7 @@ use std::collections::{HashMap, HashSet}; -use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; +use base64::{Engine as _, engine::general_purpose::STANDARD as B64}; use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use rand::RngExt as _; use serde::{Deserialize, Serialize}; @@ -111,8 +111,7 @@ pub const CSE_OFFER_DISCLOSURE: &str = "Hosted storage is operator-readable at r /// Final-screen notice for the in-browser variant (§3.3a): a binding whose /// only key copy dies with a browser profile is a support incident scheduled /// in advance. -pub const BROWSER_KEY_EXPORT_NOTICE: &str = - "Export your Iroh root key now and keep the copy somewhere safe. If this browser \ +pub const BROWSER_KEY_EXPORT_NOTICE: &str = "Export your Iroh root key now and keep the copy somewhere safe. If this browser \ profile is lost without an exported copy, the binding cannot be recovered except \ through the delayed-rebind wait."; @@ -585,11 +584,7 @@ pub fn rebind_authorization_bytes( ) -> Vec { canonical_fields( REBIND_AUTHORIZATION_DOMAIN, - &[ - binding_id, - &hex_encode(new_iroh_id), - challenge_id, - ], + &[binding_id, &hex_encode(new_iroh_id), challenge_id], ) } @@ -1242,7 +1237,9 @@ impl HostedBindingService { return Err(error); }; let verifying = VerifyingKey::from_bytes(&key_array).map_err(|_| error.clone())?; - verifying.verify_strict(message, &signature).map_err(|_| error) + verifying + .verify_strict(message, &signature) + .map_err(|_| error) } /// The binding for `sub`, requiring an `active` status for paths that @@ -1311,8 +1308,7 @@ impl HostedBindingService { .attest_bytes(&mutated) .ok_or(RebindError::RecordEncoding)?, ); - self.bindings - .insert(mutated.binding_id.clone(), mutated); + self.bindings.insert(mutated.binding_id.clone(), mutated); let notice = RebindNotice { rebind_id: request.rebind_id.clone(), binding_id: request.binding_id.clone(), @@ -1373,7 +1369,8 @@ impl HostedBindingService { .attest_bytes(&binding) .ok_or(RebindError::RecordEncoding)?, ); - self.bindings.insert(binding.binding_id.clone(), binding.clone()); + self.bindings + .insert(binding.binding_id.clone(), binding.clone()); Ok(binding) } @@ -1551,12 +1548,8 @@ impl HostedBindingService { return Err(RebindError::NewKeyBoundElsewhere); } let mut record = record.clone(); - record.service_signature = hex_encode( - &self - .service_key - .sign(&record.canonical_bytes()) - .to_bytes(), - ); + record.service_signature = + hex_encode(&self.service_key.sign(&record.canonical_bytes()).to_bytes()); let mut binding = self .bindings .get(&record.binding_id) @@ -1582,7 +1575,8 @@ impl HostedBindingService { self.binding_by_iroh.remove(&record.old_iroh_id); self.binding_by_iroh .insert(record.new_iroh_id.clone(), record.binding_id.clone()); - self.bindings.insert(binding.binding_id.clone(), binding.clone()); + self.bindings + .insert(binding.binding_id.clone(), binding.clone()); self.rebind_records.push(record.clone()); Ok((binding, record)) } @@ -1855,7 +1849,7 @@ fn prune_before(log: &mut Vec, cutoff: u64) { mod tests { use super::*; use crate::groups::policy::{Policy, Template}; - use crate::groups::{fold, Body, Create, DeviceOp, Event, Key, Role}; + use crate::groups::{Body, Create, DeviceOp, Event, Key, Role, fold}; const SUB: &str = "108204481453987112345678"; const OTHER_SUB: &str = "209305592564098223456789"; @@ -2551,7 +2545,13 @@ mod tests { service.cancel_rebind(&request.rebind_id, &foreign.to_bytes()), Err(RebindError::BadOldKeySignature) ); - assert_eq!(service.pending_rebind_for_binding(&binding.binding_id).unwrap().status, RebindRequestStatus::Pending); + assert_eq!( + service + .pending_rebind_for_binding(&binding.binding_id) + .unwrap() + .status, + RebindRequestStatus::Pending + ); let old_key = root_key(21); let cancel = old_key.sign(&rebind_cancel_bytes(&request.rebind_id)); @@ -2690,7 +2690,10 @@ mod tests { Err(RebindError::NewKeyBoundElsewhere) ); assert_eq!(service.binding(&binding.binding_id), Some(&binding_before)); - assert_eq!(service.binding(&other_binding.binding_id), Some(&other_before)); + assert_eq!( + service.binding(&other_binding.binding_id), + Some(&other_before) + ); assert_eq!(service.binding_by_sub, by_sub_before); assert_eq!(service.binding_by_iroh, by_iroh_before); assert_eq!( @@ -2757,7 +2760,10 @@ mod tests { Err(RebindError::NewKeyBoundElsewhere) ); assert_eq!(service.binding(&binding.binding_id), Some(&binding_before)); - assert_eq!(service.binding(&other_binding.binding_id), Some(&other_before)); + assert_eq!( + service.binding(&other_binding.binding_id), + Some(&other_before) + ); assert_eq!(service.binding_by_sub, by_sub_before); assert_eq!(service.binding_by_iroh, by_iroh_before); assert_eq!( @@ -2796,7 +2802,10 @@ mod tests { Err(RebindError::NewKeyBoundElsewhere) ); assert_eq!(service.binding(&binding.binding_id), Some(&binding_before)); - assert_eq!(service.binding(&other_binding.binding_id), Some(&other_before)); + assert_eq!( + service.binding(&other_binding.binding_id), + Some(&other_before) + ); assert_eq!(service.binding_by_sub, by_sub_before); assert_eq!(service.binding_by_iroh, by_iroh_before); assert!(service.rebind_records().is_empty()); @@ -2905,8 +2914,14 @@ mod tests { ), Err(RebindError::NewKeyBoundElsewhere) ); - assert_eq!(service.binding(&other_binding.binding_id), Some(&other_binding)); - assert_eq!(service.binding_for_sub(SUB).unwrap().binding_id, binding.binding_id); + assert_eq!( + service.binding(&other_binding.binding_id), + Some(&other_binding) + ); + assert_eq!( + service.binding_for_sub(SUB).unwrap().binding_id, + binding.binding_id + ); assert_eq!(service.binding_by_sub, by_sub_before); assert_eq!(service.binding_by_iroh, by_iroh_before); assert_eq!( @@ -2973,6 +2988,10 @@ mod tests { // Nothing pends and nothing changed. let stored = service.binding_for_sub(SUB).unwrap(); assert_eq!(stored.status, BindingStatus::Active); - assert!(service.pending_rebind_for_binding(&stored.binding_id).is_none()); + assert!( + service + .pending_rebind_for_binding(&stored.binding_id) + .is_none() + ); } } diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 7287fa84a..e604d7bc0 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -183,7 +183,6 @@ pub mod directory_mail; pub mod directory_view; pub use id_core::discovery; pub mod didit; -mod peer_announcement; pub mod documents; #[cfg(feature = "world")] pub mod encryption; @@ -205,6 +204,7 @@ pub(crate) mod key_envelope; pub mod local; pub mod local_events; pub mod log_sync; +mod peer_announcement; pub use id_core::membership; pub mod match_audit; pub mod meta_client; @@ -223,9 +223,9 @@ pub mod sandbox; pub mod search; #[cfg(feature = "world")] pub mod seitan; -pub mod session_checkpoint; #[cfg(feature = "world")] pub mod server_config; +pub mod session_checkpoint; #[cfg(feature = "world")] pub mod shell_contract; pub mod store; @@ -293,9 +293,9 @@ pub use commands::{ create_serve_lock, get_serve_info, is_process_alive, remove_serve_lock, }; pub use discovery::{ - ANNOUNCE_INTERVAL, DEFAULT_TOPIC, DEFAULT_TOPIC_SECRET, Defaults, PeerAnnouncement, - MAX_PEERS, MAX_PEER_NAME_BYTES, PeerDiscovery, PeerInfo, ResolvedConfig, - STALE_CHECK_INTERVAL, STALE_THRESHOLD, defaults, parse_defaults, resolve_config, + 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 helpers::{ download_output_path, parse_get_spec, parse_put_spec, print_match_cli, print_match_repl, diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index f199090ac..0c9d75827 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -949,9 +949,11 @@ mod tests { assert_eq!(record.heads, vec![merged]); assert_eq!(record.revisions.len(), 4); // A parent that is not a revision of this note is refused before signing. - assert!(events - .revise_note(note, "text/markdown", b"bad", &[id(222)]) - .is_err()); + assert!( + events + .revise_note(note, "text/markdown", b"bad", &[id(222)]) + .is_err() + ); } #[test] @@ -990,9 +992,11 @@ mod tests { assert_eq!(notes.len(), 1); assert_eq!(notes[0].id, note); assert!(events.note_history(note).is_ok()); - assert!(events - .revise_note(note, "text/markdown", b"second", &[note]) - .is_ok()); + assert!( + events + .revise_note(note, "text/markdown", b"second", &[note]) + .is_ok() + ); } #[test] @@ -1150,11 +1154,13 @@ mod tests { ); // The returned ID is the final chunk's, the one that completes the clear. assert_eq!(chunks.last().unwrap().0, event); - assert!(events - .tags_on(subject) - .unwrap() - .iter() - .all(|claim| claim.name != "topic")); + assert!( + events + .tags_on(subject) + .unwrap() + .iter() + .all(|claim| claim.name != "topic") + ); // Other names, and the same name on other subjects, are untouched. assert_eq!(events.tags_on(subject).unwrap().len(), 1); assert_eq!(events.tags_on(other_subject).unwrap().len(), 1); diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index 1586ede00..e45b77910 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -1699,8 +1699,10 @@ mod tests { let (_db, store_b) = open(); ingest_all(&store_a, &chain_of(&alice, 4, topic)); let before = applied(&store_b, &[&alice], 3); - let gate = testing::open_gate() - .with_blocks(testing::stub_blocks(&[*testing::key(0xd5).public().as_bytes()], &[])); + let gate = testing::open_gate().with_blocks(testing::stub_blocks( + &[*testing::key(0xd5).public().as_bytes()], + &[], + )); let (server, _router, mut results) = responder_gated(&store_a, gate).await; let client = endpoint_as(testing::key(0xd5)).await; let error = sync_with( diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index dd27617c0..43d92da26 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -639,7 +639,10 @@ mod tests { // empty base filter silently muted every non-capped target in // environments that export RUST_LOG= , e.g. nix build sandboxes.) assert_eq!(resolve_log_level(false, None, Some(""), None, None), "warn"); - assert_eq!(resolve_log_level(false, None, Some(" "), None, None), "warn"); + assert_eq!( + resolve_log_level(false, None, Some(" "), None, None), + "warn" + ); assert_eq!( resolve_log_level(false, None, Some(""), Some("info"), None), "info" diff --git a/pkgs/id/src/note_links.rs b/pkgs/id/src/note_links.rs index 40208ecc3..7d6851ea0 100644 --- a/pkgs/id/src/note_links.rs +++ b/pkgs/id/src/note_links.rs @@ -235,11 +235,7 @@ impl LinkProjection { /// links, and an edge to an inaccessible target is dropped whole, so the /// target's existence does not leak through the link. #[must_use] - pub fn links_from_visible( - &self, - source: Hash, - visible: &HashSet, - ) -> Vec<&LinkRecord> { + pub fn links_from_visible(&self, source: Hash, visible: &HashSet) -> Vec<&LinkRecord> { if !visible.contains(&source) { return Vec::new(); } @@ -254,11 +250,7 @@ impl LinkProjection { /// backlinks, and a backlink from an inaccessible source is dropped with its /// authored surface, which is the source's content. #[must_use] - pub fn backlinks_to_visible( - &self, - target: Hash, - visible: &HashSet, - ) -> Vec<&LinkRecord> { + pub fn backlinks_to_visible(&self, target: Hash, visible: &HashSet) -> Vec<&LinkRecord> { if !visible.contains(&target) { return Vec::new(); } @@ -305,10 +297,12 @@ pub fn project_links( surface, pin, } = &link.op; - let source_note = by_note.get(source).ok_or(LinkProjectionError::UnknownSource { - link: link.id, - note: *source, - })?; + let source_note = by_note + .get(source) + .ok_or(LinkProjectionError::UnknownSource { + link: link.id, + note: *source, + })?; if source_note.revision(*revision).is_none() { return Err(LinkProjectionError::RevisionNotOfSource { link: link.id, @@ -319,10 +313,12 @@ pub fn project_links( if !source_note.heads.contains(revision) { continue; } - let target_note = by_note.get(target).ok_or(LinkProjectionError::UnknownTarget { - link: link.id, - target: *target, - })?; + let target_note = by_note + .get(target) + .ok_or(LinkProjectionError::UnknownTarget { + link: link.id, + target: *target, + })?; if let Some(pin) = pin { if target_note.revision(*pin).is_none() { return Err(LinkProjectionError::PinNotOfTarget { @@ -343,12 +339,18 @@ pub fn project_links( }); } edges.sort_by(|a, b| { - (*a.source.as_bytes(), *a.target.as_bytes(), &a.surface, *a.id.as_bytes()).cmp(&( - *b.source.as_bytes(), - *b.target.as_bytes(), - &b.surface, - *b.id.as_bytes(), - )) + ( + *a.source.as_bytes(), + *a.target.as_bytes(), + &a.surface, + *a.id.as_bytes(), + ) + .cmp(&( + *b.source.as_bytes(), + *b.target.as_bytes(), + &b.surface, + *b.id.as_bytes(), + )) }); Ok(LinkProjection { edges }) } @@ -436,8 +438,8 @@ mod tests { revise(21, 20, b"second", &[20]), ]); // The pin names revision 20 even though the target's head is 21. - let projection = project_links(&folded, &[link(40, 10, 10, 20, "[[Target]]", Some(20))]) - .unwrap(); + let projection = + project_links(&folded, &[link(40, 10, 10, 20, "[[Target]]", Some(20))]).unwrap(); assert_eq!(projection.edges().len(), 1); let edge = &projection.edges()[0]; assert_eq!(edge.target, hash(20)); @@ -689,13 +691,17 @@ mod tests { // A viewer who cannot access target 20 learns nothing from note 10's links: // the edge is dropped, not returned with its target redacted. let only_source: HashSet = HashSet::from([hash(10)]); - assert!(projection - .links_from_visible(hash(10), &only_source) - .is_empty()); + assert!( + projection + .links_from_visible(hash(10), &only_source) + .is_empty() + ); // And an inaccessible target has no visible backlinks at all. - assert!(projection - .backlinks_to_visible(hash(20), &only_source) - .is_empty()); + assert!( + projection + .backlinks_to_visible(hash(20), &only_source) + .is_empty() + ); } #[test] diff --git a/pkgs/id/src/publications.rs b/pkgs/id/src/publications.rs index ea722922f..8dfb7b7c3 100644 --- a/pkgs/id/src/publications.rs +++ b/pkgs/id/src/publications.rs @@ -63,8 +63,20 @@ use serde::{Deserialize, Serialize}; /// with a fresher list can pass their own — this constant is the /// fallback for the boot path, which runs before any router exists. pub const KNOWN_EXPLORER_ROUTES: &[&str] = &[ - "/", "/api", "/assets", "/blob", "/edit", "/explore", "/files", "/hash", "/invite", "/peers", "/settings", - "/view", "/world", "/ws", + "/", + "/api", + "/assets", + "/blob", + "/edit", + "/explore", + "/files", + "/hash", + "/invite", + "/peers", + "/settings", + "/view", + "/world", + "/ws", ]; /// Where a published program is placed. @@ -325,10 +337,8 @@ impl Registry { } let json = serde_json::to_string_pretty(self).context("serialising publications")?; let temp = path.with_extension("json.tmp"); - std::fs::write(&temp, json) - .with_context(|| format!("writing {}", temp.display()))?; - std::fs::rename(&temp, path) - .with_context(|| format!("replacing {}", path.display()))?; + std::fs::write(&temp, json).with_context(|| format!("writing {}", temp.display()))?; + std::fs::rename(&temp, path).with_context(|| format!("replacing {}", path.display()))?; Ok(()) } @@ -355,9 +365,8 @@ impl Registry { return Ok(Self::default()); } Err(error) => { - return Err(error).with_context(|| { - format!("reading publications from {}", path.display()) - }); + return Err(error) + .with_context(|| format!("reading publications from {}", path.display())); } }; let registry: Self = serde_json::from_str(&text) @@ -461,10 +470,7 @@ mod tests { shadowed_explorer_route("/world", routes).as_deref(), Some("/world") ); - assert_eq!( - shadowed_explorer_route("/", routes).as_deref(), - Some("/") - ); + assert_eq!(shadowed_explorer_route("/", routes).as_deref(), Some("/")); assert_eq!( shadowed_explorer_route("/api", routes).as_deref(), Some("/api") @@ -525,11 +531,7 @@ mod tests { .unwrap(); let mut other = mount("/arena", false); other.world = "other".to_string(); - assert!( - registry - .publish(other, KNOWN_EXPLORER_ROUTES) - .is_err() - ); + assert!(registry.publish(other, KNOWN_EXPLORER_ROUTES).is_err()); assert_eq!(registry.publications.len(), 1); } @@ -557,10 +559,7 @@ mod tests { #[test] fn save_load_round_trips_and_missing_file_is_empty() { - let dir = std::env::temp_dir().join(format!( - "id-publications-test-{}", - std::process::id() - )); + let dir = std::env::temp_dir().join(format!("id-publications-test-{}", std::process::id())); let file = dir.join("publications.json"); let missing = Registry::load(&file).unwrap(); assert!(missing.publications.is_empty()); diff --git a/pkgs/id/src/pull_policy.rs b/pkgs/id/src/pull_policy.rs index e6260ea02..44bb5e02c 100644 --- a/pkgs/id/src/pull_policy.rs +++ b/pkgs/id/src/pull_policy.rs @@ -372,9 +372,18 @@ mod tests { WORLD, live(docs_world(key(1).public(), key(2).public(), false)), ) - .with_blocks(super::testing::stub_blocks(&[*key(9).public().as_bytes()], &[])); - assert!(!gate.admits(&key(9).public()), "the blocked peer is refused"); - assert!(gate.admits(&key(2).public()), "an unblocked peer still pulls"); + .with_blocks(super::testing::stub_blocks( + &[*key(9).public().as_bytes()], + &[], + )); + assert!( + !gate.admits(&key(9).public()), + "the blocked peer is refused" + ); + assert!( + gate.admits(&key(2).public()), + "an unblocked peer still pulls" + ); } /// #2245: a blocked topic tag is not pulled — a gate whose world is a @@ -387,8 +396,14 @@ mod tests { live(docs_world(key(1).public(), key(2).public(), false)), ) .with_blocks(super::testing::stub_blocks(&[], &[WORLD])); - assert!(!gate.admits(&key(2).public()), "a member of a blocked topic"); - assert!(!gate.admits(&key(1).public()), "the founder of a blocked topic"); + assert!( + !gate.admits(&key(2).public()), + "a member of a blocked topic" + ); + assert!( + !gate.admits(&key(1).public()), + "the founder of a blocked topic" + ); } /// #2245, against the real store-backed list: a permanent block diff --git a/pkgs/id/src/references.rs b/pkgs/id/src/references.rs index 095dd2373..829dbe775 100644 --- a/pkgs/id/src/references.rs +++ b/pkgs/id/src/references.rs @@ -455,25 +455,31 @@ impl LocalIndex { ClaimState::Uncontested } }; - let candidate = |match_kind: MatchKind, surface: String, author: AuthorKey, state: ClaimState| { - Candidate { - target_id: object.id, - kind: sigil, - match_kind, - provenance: Provenance { - store: self.store.clone(), - author, - claim_state: state, - }, - surface, - } - }; + let candidate = + |match_kind: MatchKind, surface: String, author: AuthorKey, state: ClaimState| { + Candidate { + target_id: object.id, + kind: sigil, + match_kind, + provenance: Provenance { + store: self.store.clone(), + author, + claim_state: state, + }, + surface, + } + }; // Tier 1: the viewer's petname, `@` only. if sigil == Sigil::Actor { if let Some(petname) = self.petnames.get(&object.id) { if fold(petname) == folded { let state = claim_state(MatchKind::Petname, petname); - return Some(candidate(MatchKind::Petname, petname.clone(), object.author, state)); + return Some(candidate( + MatchKind::Petname, + petname.clone(), + object.author, + state, + )); } } } @@ -484,11 +490,21 @@ impl LocalIndex { .find(|claim| fold(&claim.text) == folded) { let state = claim_state(MatchKind::ExactClaim, &claim.text); - return Some(candidate(MatchKind::ExactClaim, object.current_label().to_owned(), claim.author, state)); + return Some(candidate( + MatchKind::ExactClaim, + object.current_label().to_owned(), + claim.author, + state, + )); } if fold(&object.title) == folded { let state = claim_state(MatchKind::ExactTitle, &object.title); - return Some(candidate(MatchKind::ExactTitle, object.current_label().to_owned(), object.author, state)); + return Some(candidate( + MatchKind::ExactTitle, + object.current_label().to_owned(), + object.author, + state, + )); } // Tier 3: prefix, then token, then full-text. A prefix that matches an alias claim // keeps that claim's author as provenance — the claim, not the object, is what the @@ -498,16 +514,40 @@ impl LocalIndex { .iter() .find(|claim| fold(&claim.text).starts_with(folded)) { - return Some(candidate(MatchKind::Prefix, object.current_label().to_owned(), claim.author, ClaimState::Uncontested)); + return Some(candidate( + MatchKind::Prefix, + object.current_label().to_owned(), + claim.author, + ClaimState::Uncontested, + )); } if fold(&object.title).starts_with(folded) { - return Some(candidate(MatchKind::Prefix, object.current_label().to_owned(), object.author, ClaimState::Uncontested)); + return Some(candidate( + MatchKind::Prefix, + object.current_label().to_owned(), + object.author, + ClaimState::Uncontested, + )); } - if object.title.split_whitespace().any(|word| fold(word.trim_matches(|chr: char| !chr.is_alphanumeric())) == folded) { - return Some(candidate(MatchKind::Token, object.current_label().to_owned(), object.author, ClaimState::Uncontested)); + if object + .title + .split_whitespace() + .any(|word| fold(word.trim_matches(|chr: char| !chr.is_alphanumeric())) == folded) + { + return Some(candidate( + MatchKind::Token, + object.current_label().to_owned(), + object.author, + ClaimState::Uncontested, + )); } if fold(&object.title).contains(folded) { - return Some(candidate(MatchKind::FullText, object.current_label().to_owned(), object.author, ClaimState::Uncontested)); + return Some(candidate( + MatchKind::FullText, + object.current_label().to_owned(), + object.author, + ClaimState::Uncontested, + )); } None } @@ -636,7 +676,13 @@ mod tests { [n; 32] } - fn object(seed: &[u8], kind: Sigil, title: &str, claims: Vec<(&str, u8)>, by: u8) -> IndexedObject { + fn object( + seed: &[u8], + kind: Sigil, + title: &str, + claims: Vec<(&str, u8)>, + by: u8, + ) -> IndexedObject { IndexedObject { id: Hash::digest(seed), kind, @@ -689,19 +735,25 @@ mod tests { let resolution = index.resolve(Sigil::Actor, "ann"); assert_eq!(resolution.candidates.len(), 2); - assert!(resolution - .candidates - .iter() - .all(|candidate| candidate.match_kind == MatchKind::Petname)); - assert!(resolution - .candidates - .iter() - .all(|candidate| candidate.contested())); + assert!( + resolution + .candidates + .iter() + .all(|candidate| candidate.match_kind == MatchKind::Petname) + ); + assert!( + resolution + .candidates + .iter() + .all(|candidate| candidate.contested()) + ); assert!(resolution.is_contested()); assert_eq!(resolution.single(), None); - assert!(index - .insert_unambiguous(Sigil::Actor, "ann", author(9)) - .is_err()); + assert!( + index + .insert_unambiguous(Sigil::Actor, "ann", author(9)) + .is_err() + ); } #[test] @@ -743,10 +795,12 @@ mod tests { MatchKind::FullText ] ); - assert!(resolution - .candidates - .iter() - .all(|candidate| candidate.provenance.store == StoreId::local())); + assert!( + resolution + .candidates + .iter() + .all(|candidate| candidate.provenance.store == StoreId::local()) + ); } #[test] @@ -782,14 +836,18 @@ mod tests { ]); let resolution = index.resolve(Sigil::Actor, "sam"); assert_eq!(resolution.candidates.len(), 2); - assert!(resolution - .candidates - .iter() - .all(|candidate| candidate.contested())); + assert!( + resolution + .candidates + .iter() + .all(|candidate| candidate.contested()) + ); assert_eq!(resolution.single(), None); - assert!(index - .insert_unambiguous(Sigil::Actor, "sam", author(9)) - .is_err()); + assert!( + index + .insert_unambiguous(Sigil::Actor, "sam", author(9)) + .is_err() + ); } #[test] @@ -918,12 +976,16 @@ mod tests { let actor = index.resolve(Sigil::Actor, "atlas"); assert!(!actor.is_contested()); assert!(actor.single().is_some()); - assert!(index - .insert_unambiguous(Sigil::Actor, "atlas", author(9)) - .is_ok()); - assert!(index - .insert_unambiguous(Sigil::Topic, "atlas", author(9)) - .is_ok()); + assert!( + index + .insert_unambiguous(Sigil::Actor, "atlas", author(9)) + .is_ok() + ); + assert!( + index + .insert_unambiguous(Sigil::Topic, "atlas", author(9)) + .is_ok() + ); } #[test] diff --git a/pkgs/id/src/repl/input.rs b/pkgs/id/src/repl/input.rs index 22af52f79..962dac70c 100644 --- a/pkgs/id/src/repl/input.rs +++ b/pkgs/id/src/repl/input.rs @@ -539,7 +539,6 @@ fn has_trailing_placeholder(cmd: &str) -> bool { t == "-" || t.ends_with(" -") } - /// `cmd` with every here-string (`<<<` plus its content) removed. /// Here-string content is literal data, not command syntax: a `-` /// payload (`<<< -`) is not a trailing placeholder, and a quoted @@ -1047,11 +1046,13 @@ mod tests { for quote in ['\'', '"'] { let line = format!("echo $(exit 3) <<< {quote}literal |> -{quote} |> put name -"); let error = preprocess_repl_line(&line).unwrap_err().to_string(); - assert!(error.contains("trailing '-' content placeholder"), "{error}"); + assert!( + error.contains("trailing '-' content placeholder"), + "{error}" + ); } } - #[test] fn test_pipe_rhs_here_string_dash_payload_is_literal() { // Codex review, PR #3096: a real pipe before a here-string @@ -1120,15 +1121,10 @@ mod tests { // the placeholder error must win and the file must not exist: // rejection precedes every stage that executes shell code // (Codex review, PR #3096). - let marker = std::env::temp_dir().join(format!( - "mcpx-repl-side-effect-{}", - std::process::id() - )); + let marker = + std::env::temp_dir().join(format!("mcpx-repl-side-effect-{}", std::process::id())); let _ = std::fs::remove_file(&marker); - let line = format!( - "echo $(touch {}) |> put name -", - marker.display() - ); + let line = format!("echo $(touch {}) |> put name -", marker.display()); let result = preprocess_repl_line(&line); assert!( result diff --git a/pkgs/id/src/repl/runner.rs b/pkgs/id/src/repl/runner.rs index 04051f5b5..7360d2d45 100644 --- a/pkgs/id/src/repl/runner.rs +++ b/pkgs/id/src/repl/runner.rs @@ -41,8 +41,8 @@ use std::io::Write; use super::{ReplInput, continue_heredoc, preprocess_repl_line}; use crate::{ - FindMatch, MatchKind, PeekOptions, ReplContext, SearchOptions, download_output_path, is_node_id, - print_match_repl, + FindMatch, MatchKind, PeekOptions, ReplContext, SearchOptions, download_output_path, + is_node_id, print_match_repl, }; /// Run the interactive REPL. @@ -737,9 +737,7 @@ fn parse_find_args<'a>(rest: &[&'a str], default_format: &'a str) -> Resultout.txt` keeps // the default limit of 1. - if i + 1 < rest.len() - && !rest[i + 1].starts_with('-') - && !rest[i + 1].starts_with('>') + if i + 1 < rest.len() && !rest[i + 1].starts_with('-') && !rest[i + 1].starts_with('>') { let value = rest[i + 1]; args.first = @@ -753,9 +751,7 @@ fn parse_find_args<'a>(rest: &[&'a str], default_format: &'a str) -> Result') + if i + 1 < rest.len() && !rest[i + 1].starts_with('-') && !rest[i + 1].starts_with('>') { let value = rest[i + 1]; args.last = @@ -1132,8 +1128,7 @@ async fn output_all_matches_filtered( return Ok(()); } }; - if let Some(previous) = destinations.insert(output_path.clone(), m.name.as_str()) - { + if let Some(previous) = destinations.insert(output_path.clone(), m.name.as_str()) { println!( "refusing bulk download: destination collision between matches {:?} and {:?} at {:?}", previous, m.name, output_path @@ -1426,9 +1421,7 @@ fn parse_peek_args<'a>(rest: &[&'a str]) -> Result<(FindArgs<'a>, PeekOptions)> // A `>file` redirection token is not the number (handled // by the output branch above), so `--first >out.txt` // keeps the default limit of 1. - if i + 1 < rest.len() - && !rest[i + 1].starts_with('-') - && !rest[i + 1].starts_with('>') + if i + 1 < rest.len() && !rest[i + 1].starts_with('-') && !rest[i + 1].starts_with('>') { let value = rest[i + 1]; find_args.first = @@ -1441,9 +1434,7 @@ fn parse_peek_args<'a>(rest: &[&'a str]) -> Result<(FindArgs<'a>, PeekOptions)> } } else if arg == "--last" { // Same redirection exclusion as --first. - if i + 1 < rest.len() - && !rest[i + 1].starts_with('-') - && !rest[i + 1].starts_with('>') + if i + 1 < rest.len() && !rest[i + 1].starts_with('-') && !rest[i + 1].starts_with('>') { let value = rest[i + 1]; find_args.last = @@ -1459,9 +1450,7 @@ fn parse_peek_args<'a>(rest: &[&'a str]) -> Result<(FindArgs<'a>, PeekOptions)> } else if arg == "--lines" || arg == "-n" { // Same redirection exclusion: `--lines >out.txt` keeps // the default line count and lets the `>` branch run. - if i + 1 < rest.len() - && !rest[i + 1].starts_with('-') - && !rest[i + 1].starts_with('>') + if i + 1 < rest.len() && !rest[i + 1].starts_with('-') && !rest[i + 1].starts_with('>') { let value = rest[i + 1]; let n = value @@ -1819,10 +1808,7 @@ mod tests { async fn test_interactive_dir_refuses_basename_collisions_without_partial_writes() { // Distinct matches reducing to the same final component are refused // as a batch before any write (consistent with #2178 CLI batching). - let matches = vec![ - test_find_match("a/same.txt"), - test_find_match("b/same.txt"), - ]; + let matches = vec![test_find_match("a/same.txt"), test_find_match("b/same.txt")]; let mut rec = RecordingGetter::default(); output_selected_matches_to_dir(&mut rec, &[1, 2], &matches, "downloads").await; assert!( diff --git a/pkgs/id/src/sandbox.rs b/pkgs/id/src/sandbox.rs index e105bf2ed..a800f5cee 100644 --- a/pkgs/id/src/sandbox.rs +++ b/pkgs/id/src/sandbox.rs @@ -1138,27 +1138,42 @@ mod tests { let read_output = |store: &mut Store<()>, ptr: i32| -> Vec { let len = out_len.call(&mut *store, ()).unwrap(); - assert!(len > 0, "export output must leave a positive `plaza_out_len`"); + assert!( + len > 0, + "export output must leave a positive `plaza_out_len`" + ); let mut buf = vec![0u8; usize::try_from(len).unwrap()]; - memory.read(&*store, usize::try_from(ptr).unwrap(), &mut buf).unwrap(); + memory + .read(&*store, usize::try_from(ptr).unwrap(), &mut buf) + .unwrap(); buf }; let model = init.call(&mut store, 7).unwrap(); // Host -> guest input: allocate, write, call, free the allocation. let event = b"inc"; - let in_ptr = alloc.call(&mut store, i32::try_from(event.len()).unwrap()).unwrap(); + let in_ptr = alloc + .call(&mut store, i32::try_from(event.len()).unwrap()) + .unwrap(); assert!(in_ptr > 0, "`plaza_alloc` must return a usable pointer"); - memory.write(&mut store, usize::try_from(in_ptr).unwrap(), event).unwrap(); + memory + .write(&mut store, usize::try_from(in_ptr).unwrap(), event) + .unwrap(); let model = update - .call(&mut store, (model, 1, in_ptr, i32::try_from(event.len()).unwrap())) + .call( + &mut store, + (model, 1, in_ptr, i32::try_from(event.len()).unwrap()), + ) + .unwrap(); + free.call(&mut store, (in_ptr, i32::try_from(event.len()).unwrap())) .unwrap(); - free.call(&mut store, (in_ptr, i32::try_from(event.len()).unwrap())).unwrap(); let view_ptr = view.call(&mut store, model).unwrap(); let view_bytes = read_output(&mut store, view_ptr); assert!( - String::from_utf8(view_bytes.clone()).unwrap().contains("count=1"), + String::from_utf8(view_bytes.clone()) + .unwrap() + .contains("count=1"), "view after one inc: {}", String::from_utf8_lossy(&view_bytes) ); @@ -1182,10 +1197,17 @@ mod tests { .call(&mut store, i32::try_from(snapshot_bytes.len()).unwrap()) .unwrap(); memory - .write(&mut store, usize::try_from(snap_ptr).unwrap(), &snapshot_bytes) + .write( + &mut store, + usize::try_from(snap_ptr).unwrap(), + &snapshot_bytes, + ) .unwrap(); let restored = restore - .call(&mut store, (snap_ptr, i32::try_from(snapshot_bytes.len()).unwrap())) + .call( + &mut store, + (snap_ptr, i32::try_from(snapshot_bytes.len()).unwrap()), + ) .unwrap(); free.call( &mut store, @@ -1274,22 +1296,23 @@ mod tests { bytes: bytes.to_vec(), }); }; - let host = |live: &mut WorldInstance, events: &mut Vec, event: serde_json::Value| { - WorldProgram::update( - live, - &WorldEvent { - sequence: 0, - participant_id: 0, - kind: WorldEventKind::System { - event: event.to_string(), + let host = + |live: &mut WorldInstance, events: &mut Vec, event: serde_json::Value| { + WorldProgram::update( + live, + &WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: event.to_string(), + }, }, - }, - ) - .unwrap(); - events.push(FixtureEvent::System { - event: event.to_string(), - }); - }; + ) + .unwrap(); + events.push(FixtureEvent::System { + event: event.to_string(), + }); + }; // Type "hi" and submit: the guest requests `chat.say` as r0, and // the document must satisfy the capability schema in world_caps. @@ -1299,7 +1322,10 @@ mod tests { let wants = WorldProgram::wants(&mut live).unwrap().unwrap(); let parsed = crate::world_caps::parse_wants(&wants).unwrap(); assert!( - parsed.requests.iter().any(|r| r.id == "r0" && r.cap == "chat.say"), + parsed + .requests + .iter() + .any(|r| r.id == "r0" && r.cap == "chat.say"), "expected a chat.say request r0 in wants: {wants}" ); host( @@ -1361,7 +1387,10 @@ mod tests { "fixture replay diverged: {:?}", verification.divergence ); - assert!(verification.steps > 0, "verify must compare per-event records"); + assert!( + verification.steps > 0, + "verify must compare per-event records" + ); } #[test] diff --git a/pkgs/id/src/server_config/parse.rs b/pkgs/id/src/server_config/parse.rs index 39fec87d9..23d7222ac 100644 --- a/pkgs/id/src/server_config/parse.rs +++ b/pkgs/id/src/server_config/parse.rs @@ -348,19 +348,31 @@ fn budget_policy( other => Ok(other), } }; - if let Some(v) = checked("app_inbound_bytes_per_second", raw.app_inbound_bytes_per_second)? { + if let Some(v) = checked( + "app_inbound_bytes_per_second", + raw.app_inbound_bytes_per_second, + )? { policy.app_inbound[0] = BudgetLimit::bytes(1_000, v); } if let Some(v) = checked("app_inbound_bytes_per_hour", raw.app_inbound_bytes_per_hour)? { policy.app_inbound[1] = BudgetLimit::bytes(3_600_000, v); } - if let Some(v) = checked("app_outbound_bytes_per_second", raw.app_outbound_bytes_per_second)? { + if let Some(v) = checked( + "app_outbound_bytes_per_second", + raw.app_outbound_bytes_per_second, + )? { policy.app_outbound[0] = BudgetLimit::bytes(1_000, v); } - if let Some(v) = checked("app_outbound_bytes_per_hour", raw.app_outbound_bytes_per_hour)? { + if let Some(v) = checked( + "app_outbound_bytes_per_hour", + raw.app_outbound_bytes_per_hour, + )? { policy.app_outbound[1] = BudgetLimit::bytes(3_600_000, v); } - if let Some(v) = checked("per_peer_burst_bytes_per_minute", raw.per_peer_burst_bytes_per_minute)? { + if let Some(v) = checked( + "per_peer_burst_bytes_per_minute", + raw.per_peer_burst_bytes_per_minute, + )? { policy.per_peer[0] = BudgetLimit::bytes(60_000, v); } if let Some(v) = checked("per_peer_bytes_per_hour", raw.per_peer_bytes_per_hour)? { @@ -1104,7 +1116,10 @@ mod tests { ); assert_eq!(overrides[1].0, key(3)); // The resolved override is the one the evaluator consults. - assert_eq!(parsed.budgets().limits_for_peer(&key(1)), overrides[0].1.as_slice()); + assert_eq!( + parsed.budgets().limits_for_peer(&key(1)), + overrides[0].1.as_slice() + ); } #[test] diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index b400db249..03ad97d5c 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -311,8 +311,7 @@ impl BlockList for SharedEventStore { /// invents no block. fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { self.read(|store| { - Ok(EventStore::is_blocked(store, kind, value, crate::time::unix_ms()) - .unwrap_or(false)) + Ok(EventStore::is_blocked(store, kind, value, crate::time::unix_ms()).unwrap_or(false)) }) .unwrap_or(false) } diff --git a/pkgs/id/src/structured_logging.rs b/pkgs/id/src/structured_logging.rs index ba0228c92..c0b1f90eb 100644 --- a/pkgs/id/src/structured_logging.rs +++ b/pkgs/id/src/structured_logging.rs @@ -185,10 +185,7 @@ pub struct Rfc3339TzTimer { } impl FormatTime for Rfc3339TzTimer { - fn format_time( - &self, - writer: &mut Writer<'_>, - ) -> std::fmt::Result { + fn format_time(&self, writer: &mut Writer<'_>) -> std::fmt::Result { write!(writer, "{}", self.zone.format_timestamp(SystemTime::now())) } } diff --git a/pkgs/id/src/tags.rs b/pkgs/id/src/tags.rs index 789d4e3cb..0f4628e6a 100644 --- a/pkgs/id/src/tags.rs +++ b/pkgs/id/src/tags.rs @@ -1651,9 +1651,7 @@ fn parse_single_term(s: &str) -> Result { // silently widening the search (unquoted `name:` / `:value` // keep their key-only / value-only meaning). if left == "\"\"" || right == "\"\"" { - return Err(SearchQueryError::EmptyQuotedComponent { - term: s.to_owned(), - }); + return Err(SearchQueryError::EmptyQuotedComponent { term: s.to_owned() }); } let key = strip_quotes(&left); let value = strip_quotes(&right); @@ -2738,7 +2736,11 @@ mod tests { ]; for sep in [" ", "\t", "\n", "\r\n", "\u{00A0}"] { let query = format!("name:foo{sep}bar{sep}baz:"); - assert_eq!(parse_search_query(&query).unwrap(), expected, "separator {sep:?}"); + assert_eq!( + parse_search_query(&query).unwrap(), + expected, + "separator {sep:?}" + ); } } diff --git a/pkgs/id/src/web/explore.rs b/pkgs/id/src/web/explore.rs index 10ef1574e..60191fb7d 100644 --- a/pkgs/id/src/web/explore.rs +++ b/pkgs/id/src/web/explore.rs @@ -354,8 +354,8 @@ fn label_html(label: &Label) -> String { } async fn invite_handler(uri: axum::http::Uri) -> Response { - let page = Invite::from_query(uri.query().unwrap_or("")) - .and_then(|invite| invite_page(&invite)); + let page = + Invite::from_query(uri.query().unwrap_or("")).and_then(|invite| invite_page(&invite)); match page { Ok(body) => respond(StatusCode::OK, &body, None), Err(error) => respond( diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index b51478151..cc77273db 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -1081,13 +1081,16 @@ mod tests { // sets them decodes to the same bytes, so a token had up to // 16 alias strings that all verified. Decode refuses the // non-canonical spellings outright. - const ALPHABET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; let alias = |encoded: &str, mask: u32| -> String { let mut bytes = encoded.as_bytes().to_vec(); let last = bytes.len() - 1; let value = ALPHABET.iter().position(|&c| c == bytes[last]).unwrap() as u32; - assert_eq!(value & mask, 0, "canonical encoding zeroes the trailing bits"); + assert_eq!( + value & mask, + 0, + "canonical encoding zeroes the trailing bits" + ); bytes[last] = ALPHABET[(value | mask) as usize]; String::from_utf8(bytes).unwrap() }; @@ -1145,8 +1148,7 @@ mod tests { // verify, while the canonical spelling still does. The token // byte length fixes the final group: %4==3 chars -> low 2 bits // unused, %4==2 chars -> low 4 bits unused. - const ALPHABET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; let store = IdentityStore::new_ephemeral(); let (token, _) = store.register(Some("Alice".to_owned())).await.unwrap(); assert!(store.verify_token(&token).await.is_some()); @@ -1158,7 +1160,11 @@ mod tests { let mut bytes = token.as_bytes().to_vec(); let last = bytes.len() - 1; let value = ALPHABET.iter().position(|&c| c == bytes[last]).unwrap() as u32; - assert_eq!(value & mask, 0, "canonical spelling zeroes the trailing bits"); + assert_eq!( + value & mask, + 0, + "canonical spelling zeroes the trailing bits" + ); bytes[last] = ALPHABET[(value | mask) as usize]; let alias = String::from_utf8(bytes).unwrap(); assert_ne!(alias, token); @@ -1191,7 +1197,9 @@ mod tests { let mut handles = Vec::new(); for i in 0..16 { let s = Arc::clone(&store); - handles.push(tokio::spawn(async move { s.register(Some(format!("racer-{i}"))).await })); + handles.push(tokio::spawn(async move { + s.register(Some(format!("racer-{i}"))).await + })); } let mut ok = 0; let mut refused = 0; diff --git a/pkgs/id/src/web/markdown.rs b/pkgs/id/src/web/markdown.rs index 10b544ff8..7b55bb608 100644 --- a/pkgs/id/src/web/markdown.rs +++ b/pkgs/id/src/web/markdown.rs @@ -157,11 +157,7 @@ fn markdown_to_prosemirror_inner(markdown: &str, recover_orphans: bool) -> Value // source and append them as the same PM nodes the referenced path // produces. if recover_orphans { - preserve_unreferenced_footnote_definitions( - &mut doc, - &protected, - newline_token.as_deref(), - ); + preserve_unreferenced_footnote_definitions(&mut doc, &protected, newline_token.as_deref()); } doc } @@ -263,12 +259,68 @@ enum HtmlBlockEnd { /// The CommonMark type-6 block-level tag names. const HTML_BLOCK_TAGS: &[&str] = &[ - "address", "article", "aside", "base", "basefont", "blockquote", "body", "caption", "center", - "col", "colgroup", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", - "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", - "h6", "head", "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu", - "menuitem", "nav", "noframes", "ol", "optgroup", "option", "p", "param", "search", "section", - "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul", + "address", + "article", + "aside", + "base", + "basefont", + "blockquote", + "body", + "caption", + "center", + "col", + "colgroup", + "dd", + "details", + "dialog", + "dir", + "div", + "dl", + "dt", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hr", + "html", + "iframe", + "legend", + "li", + "link", + "main", + "menu", + "menuitem", + "nav", + "noframes", + "ol", + "optgroup", + "option", + "p", + "param", + "search", + "section", + "summary", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "title", + "tr", + "track", + "ul", ]; /// Whether `trimmed` (a whole line, both ends trimmed) is exactly @@ -303,7 +355,10 @@ fn is_complete_html_tag(trimmed: &str) -> bool { } let name_start = pos; pos += 1; - while b.get(pos).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-') { + while b + .get(pos) + .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-') + { pos += 1; } // Type 1 names never open a type 7 block with an OPENING tag @@ -477,7 +532,10 @@ impl HtmlBlockTracker { } } if rest.starts_with('!') - && rest[1..].chars().next().is_some_and(|c| c.is_ascii_uppercase()) + && rest[1..] + .chars() + .next() + .is_some_and(|c| c.is_ascii_uppercase()) { // Declaration (type 5 covers '). @@ -729,8 +787,7 @@ fn is_thematic_break(stripped: &str) -> bool { /// A setext heading underline: only `=`s (level 1) or `-`s (level 2). fn is_setext_underline(stripped: &str) -> bool { let t = stripped.trim(); - (!t.is_empty() && t.chars().all(|c| c == '=')) - || (!t.is_empty() && t.chars().all(|c| c == '-')) + (!t.is_empty() && t.chars().all(|c| c == '=')) || (!t.is_empty() && t.chars().all(|c| c == '-')) } /// Whether a line starts a new block and so cannot be a lazy @@ -743,10 +800,12 @@ fn is_setext_underline(stripped: &str) -> bool { fn is_atx_heading(stripped: &str) -> bool { let hashes = stripped.bytes().take_while(|&b| b == b'#').count(); (1..=6).contains(&hashes) - && matches!(stripped.as_bytes().get(hashes), None | Some(b' ') | Some(b'\t')) + && matches!( + stripped.as_bytes().get(hashes), + None | Some(b' ') | Some(b'\t') + ) } - /// Whether the character after a block-level tag name is a valid /// name boundary: whitespace, `/`, `>`, or end-of-line (CommonMark /// type 6). `` has no boundary after `div`, so it is @@ -817,7 +876,10 @@ fn is_non_interrupting_ordered_marker(stripped: &str) -> bool { if !matches!(stripped.as_bytes().get(digits), Some(b'.') | Some(b')')) { return false; } - if !matches!(stripped.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t')) { + if !matches!( + stripped.as_bytes().get(digits + 1), + Some(b' ') | Some(b'\t') + ) { return false; } stripped[..digits].parse::().ok() != Some(1) @@ -1019,8 +1081,7 @@ fn scan_footnote_definition_blocks(markdown: &str) -> Vec') - || (indent == 0 && !stripped.is_empty())) + && (html_prefix.contains('>') || (indent == 0 && !stripped.is_empty())) { html.reset(); html_prefix.clear(); @@ -1033,14 +1094,14 @@ fn scan_footnote_definition_blocks(markdown: &str) -> Vec Vec') - || (indent == 0 && !stripped.is_empty())) + && (fence_prefix.contains('>') || (indent == 0 && !stripped.is_empty())) { fence.reset(); fence_prefix.clear(); @@ -1176,21 +1236,19 @@ fn scan_footnote_definition_blocks(markdown: &str) -> Vec Vec<(usize, String)> { && !html_prefix.is_empty() && !stripped.starts_with(&html_prefix) && strip_container_prefixes(stripped) == stripped - && (html_prefix.contains('>') - || (indent == 0 && !stripped.is_empty())) + && (html_prefix.contains('>') || (indent == 0 && !stripped.is_empty())) { html.reset(); html_prefix.clear(); @@ -1762,14 +1819,14 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { let was_in_html = html.in_html(); if !fence.in_fence() && (indent <= 3 || html.in_html()) - && (html.feed(html_line, at_block_start) || html.feed(container_stripped, at_block_start)) + && (html.feed(html_line, at_block_start) + || html.feed(container_stripped, at_block_start)) { if !was_in_html && html.in_html() { // Opened on this line (via the container-stripped // form when a container prefix is present): remember // the prefix for the block's interior lines. - html_prefix = - stripped[..stripped.len() - container_stripped.len()].to_string(); + html_prefix = stripped[..stripped.len() - container_stripped.len()].to_string(); } if !html.in_html() { html_prefix.clear(); @@ -1814,8 +1871,7 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { && !fence_prefix.is_empty() && !carries_container_prefix(stripped, &fence_prefix) && strip_container_prefixes(stripped) == stripped - && (fence_prefix.contains('>') - || (indent == 0 && !stripped.is_empty())) + && (fence_prefix.contains('>') || (indent == 0 && !stripped.is_empty())) { fence.reset(); fence_prefix.clear(); @@ -1856,8 +1912,7 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { // (Codex P2 on #1565's twenty-ninth cut). Mirrors // scan_footnote_definition_blocks' opening-body rule. let opening_body = stripped[label.len() + 4..].trim_start_matches(' '); - in_footnote_block = - !opening_body.trim().is_empty() && !starts_new_block(opening_body); + in_footnote_block = !opening_body.trim().is_empty() && !starts_new_block(opening_body); at_block_start = true; i += 1; continue; @@ -1968,8 +2023,8 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { // block in progress (Codex P2 on #1565's fifteenth cut). A // non-1 ordered marker is excepted: it cannot interrupt a // paragraph (thirteenth cut), so it starts no item here. - let new_list_item = starts_with_list_marker(stripped) - && !is_non_interrupting_ordered_marker(stripped); + let new_list_item = + starts_with_list_marker(stripped) && !is_non_interrupting_ordered_marker(stripped); if (at_block_start || new_list_item) && (!in_footnote_block || new_list_item) && (single_start.is_some() || multiline_start.is_some()) @@ -2038,8 +2093,7 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { t.starts_with('<') && !contains_unescaped(&t[1..], '>') }; if (after.trim().is_empty() - || (pending_angle_destination - && !contains_unescaped(next_stripped, '>'))) + || (pending_angle_destination && !contains_unescaped(next_stripped, '>'))) && (footnote_definition_label(next_stripped).is_some() || is_link_reference_definition_start(next_stripped) || is_atx_heading(next_stripped) @@ -2147,20 +2201,19 @@ fn collect_link_reference_definitions(markdown: &str) -> Vec<(usize, String)> { // context. Only item content that itself ends or starts a // block leaves the next line eligible, mirroring the // blockquote rule above. - let list_eligible = if quote_eligible.is_none() - && strip_container_prefixes(stripped) != stripped - { - let c = container_stripped; - Some( - c.trim().is_empty() - || is_atx_heading(c) - || is_thematic_break(c) - || (is_setext_underline(c) && !at_block_start) - || starts_new_block(c), - ) - } else { - None - }; + let list_eligible = + if quote_eligible.is_none() && strip_container_prefixes(stripped) != stripped { + let c = container_stripped; + Some( + c.trim().is_empty() + || is_atx_heading(c) + || is_thematic_break(c) + || (is_setext_underline(c) && !at_block_start) + || starts_new_block(c), + ) + } else { + None + }; at_block_start = is_atx_heading(stripped) || quote_eligible .or(list_eligible) @@ -2345,16 +2398,17 @@ fn protect_newline_destinations(markdown: &str) -> (String, Option) { let indent = j - i; let line_blank = j >= bytes.len() || bytes[j] == b'\n'; // Fences are recognised at up to 3 spaces of indent. - let fence_run = if indent <= 3 && j < bytes.len() && (bytes[j] == b'`' || bytes[j] == b'~') { - let ch = bytes[j]; - let mut n = 0; - while j + n < bytes.len() && bytes[j + n] == ch { - n += 1; - } - if n >= 3 { Some((ch, n)) } else { None } - } else { - None - }; + let fence_run = + if indent <= 3 && j < bytes.len() && (bytes[j] == b'`' || bytes[j] == b'~') { + let ch = bytes[j]; + let mut n = 0; + while j + n < bytes.len() && bytes[j + n] == ch { + n += 1; + } + if n >= 3 { Some((ch, n)) } else { None } + } else { + None + }; let was_in_fence = fence.is_some(); match (fence, fence_run) { (None, Some(open)) => fence = Some(open), @@ -2371,7 +2425,10 @@ fn protect_newline_destinations(markdown: &str) -> (String, Option) { prev_line_blank = line_blank; } let literal_line = fence.is_some() || in_indented || fence_line; - if !literal_line && span.is_none() && (markdown[i..].starts_with("](<") || markdown[i..].starts_with("]: <")) { + if !literal_line + && span.is_none() + && (markdown[i..].starts_with("](<") || markdown[i..].starts_with("]: <")) + { let lt = if markdown[i..].starts_with("](<") { i + 2 } else { @@ -2392,7 +2449,9 @@ fn protect_newline_destinations(markdown: &str) -> (String, Option) { b'<' => break, b'\n' => { let mut m = k + 1; - while m < bytes.len() && (bytes[m] == b' ' || bytes[m] == b'\t' || bytes[m] == b'\r') { + while m < bytes.len() + && (bytes[m] == b' ' || bytes[m] == b'\t' || bytes[m] == b'\r') + { m += 1; } if m >= bytes.len() || bytes[m] == b'\n' { @@ -4247,8 +4306,8 @@ fn force_fenced_code_blocks_in_blockquotes<'a>(root: &'a AstNode<'a>) -> Vec = Vec::new(); let mut stack: Vec<(&AstNode<'a>, bool)> = vec![(root, false)]; while let Some((node, ancestor_is_blockquote)) = stack.pop() { - let in_blockquote = ancestor_is_blockquote - || matches!(node.data.borrow().value, NodeValue::BlockQuote); + let in_blockquote = + ancestor_is_blockquote || matches!(node.data.borrow().value, NodeValue::BlockQuote); for child in node.children() { stack.push((child, in_blockquote)); } @@ -4513,9 +4572,9 @@ fn json_to_ast<'a>(arena: &'a Arena<'a>, json: &Value) -> Result<&'a AstNode<'a> // #1369: YAML front matter (`---` delimiter only; comrak has no // TOML `+++` support) carried verbatim in the `text` attr. - "front_matter" => NodeValue::FrontMatter( - json["attrs"]["text"].as_str().unwrap_or("").to_owned(), - ), + "front_matter" => { + NodeValue::FrontMatter(json["attrs"]["text"].as_str().unwrap_or("").to_owned()) + } "bullet_list" => { let tight = json["attrs"]["tight"].as_bool().unwrap_or(false); @@ -5574,10 +5633,7 @@ mod tests { .iter() .find(|m| m["type"] == "link") .unwrap(); - assert_eq!( - link_mark["attrs"]["href"], - "https://example.com/path?a=1" - ); + assert_eq!(link_mark["attrs"]["href"], "https://example.com/path?a=1"); } #[test] @@ -6392,7 +6448,10 @@ mod tests { // keeps it literal text (no link mark is invented). let broken = "[x]()\n"; let (protected, token) = protect_newline_destinations(broken); - assert_eq!(protected, broken, "scan crossed a whitespace-only blank line"); + assert_eq!( + protected, broken, + "scan crossed a whitespace-only blank line" + ); assert!(token.is_none()); let doc = markdown_to_prosemirror(broken); assert!( @@ -6403,7 +6462,10 @@ mod tests { // protected, and a genuine one after a literal block is too. let (protected, token) = protect_newline_destinations("[x]()\n"); assert!(token.is_some(), "genuine destination unprotected"); - assert!(protected.contains("idweb-newline"), "genuine destination not tokenised: {protected:?}"); + assert!( + protected.contains("idweb-newline"), + "genuine destination not tokenised: {protected:?}" + ); let mixed = "```\n[x]()\n```\n\n[y]()\n"; let (protected, token) = protect_newline_destinations(mixed); assert!(token.is_some(), "destination after fence unprotected"); @@ -6521,8 +6583,7 @@ mod tests { // #1565: the referenced definition keeps today's exact path; // the unreferenced one is appended by the pre-scan, not // duplicated or dropped. - let original = - "Text.[^used]\n\n[^used]: Used note.\n\n[^unused]: Unused note.\n"; + let original = "Text.[^used]\n\n[^used]: Used note.\n\n[^unused]: Unused note.\n"; let doc = markdown_to_prosemirror(original); let labels: Vec<&str> = doc["content"] .as_array() @@ -6614,8 +6675,7 @@ mod tests { // the collector's single-line eligibility check rejected // it, so the recovered footnote's [target][long label] // saved as literal brackets instead of a hyperlink. - let original = - "[^orphan]: [target][long label]\n\n[long\nlabel]: https://example.com\n"; + let original = "[^orphan]: [target][long label]\n\n[long\nlabel]: https://example.com\n"; let (first, second) = two_saves(original); assert!( first.contains("[target](https://example.com)"), @@ -6661,12 +6721,10 @@ mod tests { // not a link reference definition, so the orphan // footnote's literal [target][url] must NOT resolve into // a hyperlink. - let original = - "- Body\n [url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "- Body\n [url]: https://example.com\n\n[^orphan]: [target][url]\n"; let (first, second) = two_saves(original); assert!( - !first.contains("](https://example.com)") - && first.contains("\\[target\\]"), + !first.contains("](https://example.com)") && first.contains("\\[target\\]"), "list-continued reference stays literal (no link formed): {first:?}" ); assert_eq!(first, second, "list-paragraph round-trip is a fixpoint"); @@ -6714,15 +6772,16 @@ mod tests { // a blockquote paragraph is paragraph text, not a link // reference definition, so the orphan footnote's literal // [target][url] must NOT resolve into a hyperlink. - let original = - "> Body\n> [url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "> Body\n> [url]: https://example.com\n\n[^orphan]: [target][url]\n"; let (first, second) = two_saves(original); assert!( - !first.contains("](https://example.com)") - && first.contains("\\[target\\]"), + !first.contains("](https://example.com)") && first.contains("\\[target\\]"), "unresolved reference stays literal (no link formed): {first:?}" ); - assert_eq!(first, second, "container paragraph round-trip is a fixpoint"); + assert_eq!( + first, second, + "container paragraph round-trip is a fixpoint" + ); } #[test] @@ -6807,7 +6866,6 @@ mod tests { assert_eq!(first, second, "ordered continuation is a fixpoint"); } - #[test] fn test_empty_bullet_ends_footnote_like_comrak() { // #1565 nineteenth cut (Codex P2, DECLINED with evidence): @@ -6826,9 +6884,7 @@ mod tests { let original = "[^a]: First.\n* \nsecond line.\n"; let (first, second) = two_saves(original); assert!( - first.contains("First.") - && first.contains("second line.") - && first.contains("- "), + first.contains("First.") && first.contains("second line.") && first.contains("- "), "all lines survive the round trip: {first:?}" ); assert_eq!(first, second, "empty-bullet round-trip is a fixpoint"); @@ -6843,7 +6899,8 @@ mod tests { // colon, so the unterminated angle destination consumed // both lines and the whole candidate was discarded, // leaving the orphan's link literal. - let original = "[bad]: = saved_doc["content"] @@ -7172,7 +7256,10 @@ mod tests { "blockquote multiline destination resolves the orphan link: {orphan}" ); let (first, second) = two_saves(original); - assert_eq!(first, second, "blockquote-definition round-trip is a fixpoint"); + assert_eq!( + first, second, + "blockquote-definition round-trip is a fixpoint" + ); } #[test] @@ -7218,7 +7305,10 @@ mod tests { !first.contains("[target]("), "malformed-candidate reference is not promoted to a link: {first:?}" ); - assert_eq!(first, second, "malformed-candidate round-trip is a fixpoint"); + assert_eq!( + first, second, + "malformed-candidate round-trip is a fixpoint" + ); } #[test] @@ -7248,7 +7338,10 @@ mod tests { first.contains("paragraph"), "footnote paragraph survives: {first:?}" ); - assert_eq!(first, second, "overindented-html footnote round-trip is a fixpoint"); + assert_eq!( + first, second, + "overindented-html footnote round-trip is a fixpoint" + ); } #[test] @@ -7273,7 +7366,10 @@ mod tests { "only the real orphan definition is synthesized: {doc}" ); let (first, second) = two_saves(original); - assert_eq!(first, second, "overindented-closer round-trip is a fixpoint"); + assert_eq!( + first, second, + "overindented-closer round-trip is a fixpoint" + ); } #[test] @@ -7290,7 +7386,10 @@ mod tests { first.contains("[x](/target)"), "reference after a heading-body footnote resolves: {first:?}" ); - assert_eq!(first, second, "heading-body reference round-trip is a fixpoint"); + assert_eq!( + first, second, + "heading-body reference round-trip is a fixpoint" + ); } #[test] @@ -7457,7 +7556,10 @@ mod tests { "only the real orphan definition is synthesized: {doc}" ); let (first, second) = two_saves(original); - assert_eq!(first, second, "heading-body footnote round-trip is a fixpoint"); + assert_eq!( + first, second, + "heading-body footnote round-trip is a fixpoint" + ); } #[test] @@ -7523,7 +7625,10 @@ mod tests { first.contains("[^real]:"), "recovered definition survives the save: {first:?}" ); - assert_eq!(first, second, "indented-continuation round-trip is a fixpoint"); + assert_eq!( + first, second, + "indented-continuation round-trip is a fixpoint" + ); } #[test] @@ -7546,7 +7651,10 @@ mod tests { !first.contains("[target]("), "trailing-text reference is not promoted to a link: {first:?}" ); - assert_eq!(first, second, "trailing-text-after-title round-trip is a fixpoint"); + assert_eq!( + first, second, + "trailing-text-after-title round-trip is a fixpoint" + ); } #[test] @@ -7556,7 +7664,8 @@ mod tests { // marker is optional, so byte-exact prefix matching left // the fence open and suppressed the reference definition // after it, degrading the orphan's link to literal text. - let original = "> ```\n> code\n>```\n> [url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = + "> ```\n> code\n>```\n> [url]: https://example.com\n\n[^orphan]: [target][url]\n"; let (first, second) = two_saves(original); assert!( first.contains("](https://example.com)"), @@ -7594,14 +7703,16 @@ mod tests { // item is document-global even though the first item's // content is paragraph text; the orphan footnote's // reference-style link must resolve on save. - let original = - "- Body\n- [url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "- Body\n- [url]: https://example.com\n\n[^orphan]: [target][url]\n"; let (first, second) = two_saves(original); assert!( first.contains("](https://example.com)"), "reference in a new list item resolves to a link: {first:?}" ); - assert_eq!(first, second, "list item reference round-trip is a fixpoint"); + assert_eq!( + first, second, + "list item reference round-trip is a fixpoint" + ); } #[test] @@ -7760,7 +7871,10 @@ mod tests { .unwrap() .iter() .any(|n| n["type"] == "footnote_definition"); - assert!(!found, "fence interior stays literal past a container-shaped line"); + assert!( + !found, + "fence interior stays literal past a container-shaped line" + ); } #[test] @@ -7770,8 +7884,7 @@ mod tests { // reference definition; the synthesis context must not // promote it, or the recovered footnote's bracketed text // becomes a hyperlink the document never had. - let original = - "Body line\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "Body line\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; let doc = markdown_to_prosemirror(original); let orphan = doc["content"] .as_array() @@ -7802,7 +7915,6 @@ mod tests { assert!(found, "definition after a blockquote fence is recovered"); } - #[test] fn test_lowercase_cdata_does_not_suppress_footnote() { // #1565 sixteenth cut (Codex P2): a CDATA block requires @@ -7840,8 +7952,7 @@ mod tests { // an indented code block (tab = columns to the next // multiple of 4), so a reference definition on the next // line starts a new block and is collected. - let original = - "\tcode\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "\tcode\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; let doc = markdown_to_prosemirror(original); let orphan = doc["content"] .as_array() @@ -7861,8 +7972,7 @@ mod tests { // HTML block must reach the HTML tracker, or the collector // treats every later line as HTML and returns no reference // definitions, degrading the orphan's reference-style link. - let original = - "
\n
\n\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; + let original = "
\n
\n\n[url]: https://example.com\n\n[^orphan]: [target][url]\n"; let doc = markdown_to_prosemirror(original); let orphan = doc["content"] .as_array() @@ -7895,7 +8005,10 @@ mod tests { "multiline destination resolves the orphan link: {orphan}" ); let (first, second) = two_saves(original); - assert_eq!(first, second, "multiline-definition round-trip is a fixpoint"); + assert_eq!( + first, second, + "multiline-definition round-trip is a fixpoint" + ); } #[test] @@ -7918,7 +8031,6 @@ mod tests { ); } - #[test] fn test_autolink_line_does_not_suppress_footnote() { // #1565 seventeenth cut (Codex P2): `` @@ -7991,8 +8103,7 @@ mod tests { // marker ends the real HTML comment, but the collector's // indent gate never fed it to the tracker, so the tracker // stayed open and suppressed the valid definition after it. - let original = - "[^orphan]: [target][url]\n\n\n\n[url]: https://example.com\n"; + let original = "[^orphan]: [target][url]\n\n\n\n[url]: https://example.com\n"; let doc = markdown_to_prosemirror(original); let orphan = doc["content"] .as_array() @@ -8018,7 +8129,10 @@ mod tests { .unwrap() .iter() .any(|n| n["type"] == "footnote_definition"); - assert!(found, "definition after an indented comment close is recovered"); + assert!( + found, + "definition after an indented comment close is recovered" + ); } #[test] @@ -8143,13 +8257,17 @@ mod tests { .filter(|n| n["type"] == "footnote_definition") .map(|n| n["attrs"]["label"].as_str().unwrap()) .collect(); - assert_eq!(labels, ["real"], "definition after blockquote HTML is recovered"); + assert_eq!( + labels, + ["real"], + "definition after blockquote HTML is recovered" + ); let (first, second) = two_saves(original); assert!(first.contains("The note."), "note survives save: {first:?}"); assert_eq!(first, second, "blockquote-html round-trip is a fixpoint"); } - #[test] + #[test] fn test_footnote_after_blockquote_fence_container_end_recovered() { // Codex P2 on #1565's tenth cut: a fence opened inside a // blockquote ends implicitly when the quote ends (blank @@ -8164,7 +8282,11 @@ mod tests { .filter(|n| n["type"] == "footnote_definition") .map(|n| n["attrs"]["label"].as_str().unwrap()) .collect(); - assert_eq!(labels, ["real"], "definition after blockquote fence is recovered"); + assert_eq!( + labels, + ["real"], + "definition after blockquote fence is recovered" + ); let (first, second) = two_saves(original); assert!(first.contains("The note."), "note survives save: {first:?}"); assert_eq!(first, second, "blockquote-fence round-trip is a fixpoint"); @@ -8182,7 +8304,10 @@ mod tests { first.contains("https://example.com"), "blockquote reference definition resolves in recovered footnote: {first:?}" ); - assert_eq!(first, second, "blockquote-definition round-trip is a fixpoint"); + assert_eq!( + first, second, + "blockquote-definition round-trip is a fixpoint" + ); } #[test] @@ -8193,9 +8318,18 @@ mod tests { // of ending it. let original = "[^a]: First line.\n#hashtag\n"; let (first, second) = two_saves(original); - assert!(first.contains("First line."), "first line survives: {first:?}"); - assert!(first.contains("#hashtag"), "hashtag continuation survives: {first:?}"); - assert_eq!(first, second, "hashtag-continuation round-trip is a fixpoint"); + assert!( + first.contains("First line."), + "first line survives: {first:?}" + ); + assert!( + first.contains("#hashtag"), + "hashtag continuation survives: {first:?}" + ); + assert_eq!( + first, second, + "hashtag-continuation round-trip is a fixpoint" + ); } #[test] @@ -8220,7 +8354,7 @@ mod tests { assert_eq!(first, second, "self-closing-pre round-trip is a fixpoint"); } -#[test] + #[test] fn test_reference_after_lone_setext_marker_not_a_definition() { // Codex P2 on #1565's ninth cut: a lone `=` with no // preceding paragraph is paragraph text, so the @@ -8275,7 +8409,11 @@ mod tests { .filter(|n| n["type"] == "footnote_definition") .map(|n| n["attrs"]["label"].as_str().unwrap()) .collect(); - assert_eq!(labels, ["real"], "definition after invalid fence is recovered"); + assert_eq!( + labels, + ["real"], + "definition after invalid fence is recovered" + ); let (first, second) = two_saves(original); assert!(first.contains("The note."), "note survives save: {first:?}"); assert_eq!(first, second, "invalid-fence round-trip is a fixpoint"); @@ -8318,7 +8456,10 @@ mod tests { .expect("unreferenced definition carried into the PM doc"); assert_eq!(definition["attrs"]["label"], "a"); let (first, second) = two_saves(original); - assert!(first.contains("First line."), "first line survives: {first:?}"); + assert!( + first.contains("First line."), + "first line survives: {first:?}" + ); assert!( first.contains("second line."), "lazy continuation survives save: {first:?}" @@ -8336,7 +8477,10 @@ mod tests { !first.contains("idweb-newline"), "no placeholder token in saved output: {first:?}" ); - assert_eq!(first, second, "newline-destination round-trip is a fixpoint"); + assert_eq!( + first, second, + "newline-destination round-trip is a fixpoint" + ); } fn test_footnote_multi_paragraph_definition_fixpoint() { @@ -9484,7 +9628,8 @@ Some text #[test] fn test_mixed_case_inline_img_tag_imports_as_image() { - let doc = markdown_to_prosemirror("before \"Mixed\" after\n"); + let doc = + markdown_to_prosemirror("before \"Mixed\" after\n"); let content = doc["content"][0]["content"] .as_array() .expect("paragraph content"); @@ -9524,7 +9669,19 @@ Some text // #2180: values with no lossless numeric-pixel form are // refused (attr absent; the import path warns) -- never // silently truncated or reinterpreted. - for raw in ["50%", "200.5", "200.5px", "10em", "2rem", "abc", "", "-5", "200pxpx", "200", "200px"] { + for raw in [ + "50%", + "200.5", + "200.5px", + "10em", + "2rem", + "abc", + "", + "-5", + "200pxpx", + "200", + "200px", + ] { let node = parse_img_tag(&format!("")) .expect("img parses"); assert!( @@ -9567,7 +9724,10 @@ Some text assert_eq!(img["type"], "image"); assert_eq!(img["attrs"]["width"], 200); let out = prosemirror_to_markdown(&doc).unwrap(); - assert!(out.contains("width=\"200\""), "px form re-emits bare: {out}"); + assert!( + out.contains("width=\"200\""), + "px form re-emits bare: {out}" + ); } #[test] @@ -10280,10 +10440,8 @@ Some text fn test_front_matter_misplaced_is_rejected() { // #1369: `front_matter` is legal only as the first child of // `doc`; anywhere else is a MisplacedNode. - let fm = - || json!({"type": "front_matter", "attrs": {"text": "---\na: b\n---\n"}}); - let para = - || json!({"type": "paragraph", "content": [{"type": "text", "text": "x"}]}); + let fm = || json!({"type": "front_matter", "attrs": {"text": "---\na: b\n---\n"}}); + let para = || json!({"type": "paragraph", "content": [{"type": "text", "text": "x"}]}); let cases: &[(&str, Value)] = &[ ( "second child of doc", @@ -10314,9 +10472,6 @@ Some text } // First child of doc saves verbatim. let ok = json!({"type": "doc", "content": [fm(), para()]}); - assert_eq!( - prosemirror_to_markdown(&ok).unwrap(), - "---\na: b\n---\nx\n" - ); + assert_eq!(prosemirror_to_markdown(&ok).unwrap(), "---\na: b\n---\nx\n"); } } diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index c05618867..0a854e957 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -74,12 +74,12 @@ use tokio::sync::Mutex; use crate::discovery::PeerDiscovery; use crate::tags::TagStore; +pub use app_interface::{WebInterface, WebInterfaceError, WebMode, web_interface_from_app_toml}; pub use assets::static_handler; pub use collab::CollabState; pub use identity::IdentityStore; #[doc(hidden)] pub use identity::crash_gate; -pub use app_interface::{WebInterface, WebInterfaceError, WebMode, web_interface_from_app_toml}; pub use routes::{create_router, create_router_for_app}; pub use security::WebSecurity; pub use templates::{AssetUrls, render_page}; @@ -152,8 +152,10 @@ impl SaveRateLimiter { /// so a failed save never strands the filename. pub async fn acquire(&self, name: &str) -> Result { self.check(name).await?; - let mut flight = - self.in_flight.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut flight = self + .in_flight + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); if !flight.insert(name.to_owned()) { return Err(self.cooldown); } @@ -481,7 +483,15 @@ pub async fn web_routers( .await? } None => { - AppState::new(store, peers, node_id, tag_store, secret_key, identity_db_path).await? + AppState::new( + store, + peers, + node_id, + tag_store, + secret_key, + identity_db_path, + ) + .await? } }; Ok(securities @@ -531,7 +541,11 @@ mod tests { let limiter = SaveRateLimiter::new(Duration::from_secs(5)); let _permit = limiter.acquire("a.txt").await.expect("first save proceeds"); let remaining = limiter.acquire("a.txt").await.unwrap_err(); - assert_eq!(remaining, Duration::from_secs(5), "in-flight refusal quotes the cooldown"); + assert_eq!( + remaining, + Duration::from_secs(5), + "in-flight refusal quotes the cooldown" + ); assert!( limiter.acquire("b.txt").await.is_ok(), "a different file is not refused" @@ -541,10 +555,7 @@ mod tests { #[tokio::test] async fn test_save_limiter_concurrent_acquires_admit_exactly_one() { let limiter = SaveRateLimiter::new(Duration::from_secs(5)); - let (first, second) = tokio::join!( - limiter.acquire("a.txt"), - limiter.acquire("a.txt") - ); + let (first, second) = tokio::join!(limiter.acquire("a.txt"), limiter.acquire("a.txt")); let admitted = [first.is_ok(), second.is_ok()] .into_iter() .filter(|ok| *ok) diff --git a/pkgs/id/src/web/templates.rs b/pkgs/id/src/web/templates.rs index 5a5ef8396..7cf4a3495 100644 --- a/pkgs/id/src/web/templates.rs +++ b/pkgs/id/src/web/templates.rs @@ -185,9 +185,7 @@ pub fn render_file_list(page: &FileListPage) -> String { ); } if page.show_deleted { - html.push_str( - "", - ); + html.push_str(""); } html.push_str("