Skip to content

refactor: House keeping of PeerId#146

Merged
artrixdotdev merged 5 commits intomainfrom
fix/strip-peer-id
Sep 13, 2025
Merged

refactor: House keeping of PeerId#146
artrixdotdev merged 5 commits intomainfrom
fix/strip-peer-id

Conversation

@artrixdotdev
Copy link
Owner

@artrixdotdev artrixdotdev commented Sep 13, 2025

Allows for pre-released tag stripping and fixes up some Display and Debug implementations.

Fixes: #145

Summary by CodeRabbit

  • Bug Fixes

    • Improved peer identifier version encoding to extract and enforce a 4-digit numeric segment, increasing compatibility and preventing invalid version representations.
    • Display formatting simplified: peers now show "client_name version" (or just name) instead of including raw ID.
  • Tests

    • Updated tests to match the new digits-only version extraction and ID layout expectations.
  • Documentation

    • Minor punctuation fix in protocol format comment.

@artrixdotdev artrixdotdev linked an issue Sep 13, 2025 that may be closed by this pull request
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 13, 2025

Walkthrough

PeerId default generation now extracts only ASCII digits from the core VERSION (before '-' or '+'), pads to 4 digits, and inserts those four digits into the Azureus-format ID slot (maintaining 20 bytes). Display and Debug formatting for PeerId were adjusted and tests updated.

Changes

Cohort / File(s) Summary
PeerId implementation & tests
crates/libtortillas/src/peer/id.rs, crates/libtortillas/tests/*
Parse VERSION up to first '-' or '+', collect ASCII digits only, pad to 4 digits, write as the -XX####- segment in the 20-byte Azureus-style ID; removed Debug from derive and added explicit fmt::Debug; changed fmt::Display to "client_name version" output; updated tests and added assertions for digit/hyphen positions; minor doc comment punctuation fix.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Caller (PeerId::default)
  participant V as VERSION (env/const)
  participant P as PeerId builder

  C->>P: request default PeerId
  P->>V: read VERSION string
  Note over P: Take substring before '-' or '+'\nCollect only ASCII digits
  alt digits < 4
    P->>P: pad digits with '0' to length 4
  end
  P->>P: insert 4-digit segment into Azureus-format positions\n(enforce hyphens at expected bytes)
  P-->>C: return constructed PeerId
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested labels

high prio

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR also introduces changes outside the stated objective: Display output semantics were altered (no longer including hex-encoded ID), Debug was removed from derive and reimplemented (changing the public trait surface), and derive/formatting adjustments affect public-facing behavior; these edits are not required by issue [#145] and may impact consumers. Either split the formatting/Debug/derive changes into a separate PR or add an explicit justification and changelog/semver note in this PR, and ensure tests cover the public-output changes so reviewers can assess compatibility.
Title Check ❓ Inconclusive The current title "refactor: House keeping of PeerId" mentions PeerId but is vague and does not clearly state the primary change (stripping prerelease/commit suffixes from PeerId::default) or the bugfix context. Recommend a concise, descriptive title that names the main change and linked issue, for example: "fix(peer-id): strip prerelease and commit suffixes from PeerId::default (fixes #145)".
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues Check ✅ Passed The PR updates PeerId generation to take the version core up to the first non-digit/non-dot, extract and pad ASCII digits into a fixed four-digit segment, and updates tests accordingly, which strips prerelease tags and commit hashes as required by issue [#145]; this directly satisfies the linked coding objective to avoid embedding prerelease/commit text in PeerId::default.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/strip-peer-id

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 813070e and 9081950.

📒 Files selected for processing (1)
  • crates/libtortillas/src/peer/id.rs (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-28T06:33:16.003Z
Learnt from: artrixdotdev
PR: artrixdotdev/tortillas#125
File: crates/libtortillas/src/torrent/actor.rs:151-171
Timestamp: 2025-08-28T06:33:16.003Z
Learning: In the torrent actor's append_peer function in crates/libtortillas/src/torrent/actor.rs, when a PeerStream is provided, the peer has already been pre-handshaked by the engine. The engine handles the initial handshake validation, info hash verification, and peer ID extraction before passing the stream to the torrent actor. Therefore, the peer.id should already be populated when a stream is provided.

Applied to files:

  • crates/libtortillas/src/peer/id.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build_and_test
🔇 Additional comments (1)
crates/libtortillas/src/peer/id.rs (1)

359-359: Doc punctuation change — LGTM.

@artrixdotdev artrixdotdev changed the title refactor: Refactor PeerId::default to strip prerelease tags from version refactor: Refactor PeerId::default to strip prerelease tags from version Sep 13, 2025
@artrixdotdev artrixdotdev changed the title refactor: Refactor PeerId::default to strip prerelease tags from version refactor: House keeping of PeerId Sep 13, 2025
@coderabbitai coderabbitai bot added the high prio GET DONE ASAP!! label Sep 13, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
crates/libtortillas/src/peer/id.rs (2)

419-428: Prefer hex for Debug instead of lossy UTF-8.

Lossy UTF-8 can show � and is hard to grep. Hex is standard for peer IDs.

Apply:

 impl fmt::Debug for PeerId {
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-    write!(
-      f,
-      "{} ({})",
-      self.client_name(),
-      String::from_utf8_lossy(self.id())
-    )
+    write!(f, "{} (", self.client_name())?;
+    for (i, b) in self.id().iter().enumerate() {
+      if i > 0 { /* optional: group */ }
+      write!(f, "{:02x}", b)?;
+    }
+    write!(f, ")")
   }
 }

472-474: Add an assertion that version bytes are digits.

Small safety net against regressions that might introduce non-digits into [3..7].

Apply:

   assert_eq!(peer.as_bytes()[0], b'-');
   assert_eq!(&peer.as_bytes()[1..3], b"TO");
   assert_eq!(peer.as_bytes()[7], b'-');
+  assert!(peer.as_bytes()[3..7].iter().all(|b| b.is_ascii_digit()));
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9081950 and 7ccfc95.

📒 Files selected for processing (1)
  • crates/libtortillas/src/peer/id.rs (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-28T06:33:16.003Z
Learnt from: artrixdotdev
PR: artrixdotdev/tortillas#125
File: crates/libtortillas/src/torrent/actor.rs:151-171
Timestamp: 2025-08-28T06:33:16.003Z
Learning: In the torrent actor's append_peer function in crates/libtortillas/src/torrent/actor.rs, when a PeerStream is provided, the peer has already been pre-handshaked by the engine. The engine handles the initial handshake validation, info hash verification, and peer ID extraction before passing the stream to the torrent actor. Therefore, the peer.id should already be populated when a stream is provided.

Applied to files:

  • crates/libtortillas/src/peer/id.rs
🧬 Code graph analysis (1)
crates/libtortillas/src/peer/id.rs (2)
crates/libtortillas/src/protocol/messages.rs (1)
  • fmt (129-161)
crates/libtortillas/src/peer/mod.rs (2)
  • fmt (46-55)
  • fmt (72-74)
🔇 Additional comments (5)
crates/libtortillas/src/peer/id.rs (5)

359-359: Doc tweak LGTM.


373-386: Azureus version slot fix is correct and robust.

Digits-only, pad/truncate to 4, and fixed placement at [3..7] with id[7] = b'-' solves the prior OOB and format drift.


412-415: Display no longer includes the raw ID; update call sites that expect it.

Handshake logging currently uses Display (see PeerMessages::Handshake). If you still want the ID in logs, switch those sites to {:?} (uses your new Debug).

Proposed change (in messages.rs):

- PeerMessages::Handshake(handshake) => write!(f, "Handshake({})", handshake.peer_id),
+ PeerMessages::Handshake(handshake) => write!(f, "Handshake({:?})", handshake.peer_id),

454-467: Test now mirrors production derivation—good.


63-67: Confirm PeerId Debug formatting unchanged

You replaced #[derive(Debug)] on PeerId with a manual Debug impl — confirm the manual impl preserves the derived Debug output because tests, snapshots, logs or downstream crates may depend on the exact formatting.

  • Changed location: crates/libtortillas/src/peer/id.rs:63-67.
  • Verify formatting/usage sites: crates/libtortillas/src/torrent/messages.rs:63-69 (uses "{peer_id:?}" / KillPeer/AddPeer), crates/libtortillas/src/errors.rs:315-328 (error formatting), crates/libtortillas/src/tracker/http.rs:149-151 and 190-197 (debug!/URI encoding), crates/libtortillas/src/protocol/messages.rs:131 (Handshake display).

@artrixdotdev artrixdotdev merged commit 96705c9 into main Sep 13, 2025
3 checks passed
@artrixdotdev artrixdotdev deleted the fix/strip-peer-id branch September 13, 2025 06:10
@artrixdotdev artrixdotdev restored the fix/strip-peer-id branch September 14, 2025 05:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

high prio GET DONE ASAP!!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor PeerId::default to strip prerelease tags from version

1 participant