Skip to content

Feat: Add system-wide stream handler unregister method. #1227

Description

@ItshMoh

Summary

py-libp2p supports registering protocol stream handlers via set_stream_handler, but does not provide a guaranteed, system-wide way to unregister them.

This creates inconsistent service lifecycle behavior across modules.

Motivation

We need lifecycle symmetry for stream protocols in existing service lifecycle methods:

  • service startup path should register handler(s)
  • service shutdown path should unregister handler(s).

Without a standard unregister API, services currently use module-specific workarounds, which makes behavior inconsistent and harder to reason about on long-running hosts.

Current state

Core interfaces currently expose registration but not guaranteed removal:

  • IHost.set_stream_handler(...):
    link
  • IMultiselectMuxer.add_handler(...):
    link

No required remove_stream_handler / remove_handler contract exists at those interface levels.

Existing workaround patterns

  1. Flags-only stop (service marked stopped, handler still registered)

    • Bitswap stop path:
      link
  2. Empty handler replacement as pseudo-unregister

    • DCUtR sets an empty_handler:
      link
  3. Optional unregister with fallback if method is missing

    • Relay protocol tries remove_stream_handler, falls back on AttributeError:
      link

Proposed change (stream scope only)

  1. Add interface methods:
  • IHost.remove_stream_handler(protocol_id: TProtocol) -> None
  • IMultiselectMuxer.remove_handler(protocol: TProtocol) -> None
  1. Implement in core:
  • BasicHost.remove_stream_handler(...) delegates to multiselect
  • Multiselect.remove_handler(...) removes the protocol from handler map
  1. Service migration (follow-up in same or separate PRs):
  • Update services that register handlers to unregister on stop/teardown
    (perf, bitswap, kad_dht, relay/DCUtR, etc.)

Expected impact

  • Consistent register/unregister semantics for stream protocols during service startup/shutdown
  • Fewer ad-hoc unregister workarounds
  • Cleaner behavior for long-lived hosts and protocol restarts

Are you planning to do it yourself in a pull request ?

yes

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions