libp2p / go-libp2p

libp2p implementation in Go
MIT License
6.08k stars 1.07k forks source link

Per-request event bus #852

Open Stebalien opened 4 years ago

Stebalien commented 4 years ago

Currently, the DHT has a useful but very DHT specific routing query events system for returning events related to current query. This works by attaching an event listener to the context higher up in the application and extracting it from the context down in libp2p.

The downsides are:

  1. Specific to routing/DHT events and doesn't generalize well.
  2. Only allows one subsystem to register for events.

Instead, we should consider stashing a per-request event bus in the context. This would allow multiple services to emit request-specific events on the event bus, and multiple consumers to consume these events.

package eventctx

// NullEmitter consumes and drops all emitted events.
var NullEmitter = ...

// Subscribe subscribes to the given events, attaching a new event bus to the context if necessary.
func Subscribe(ctx context.Context, evtTypes interface{}, opts ...event.SubscriptionOpt) (context.Context, event.Subscription, error) { ... }

// Emitter registers a new emitter for the given events on the context's event bus. If no event bus has been registered, this function returns a NullEmitter.
func Emitter(ctx context.Context, evtTypes interface{}, opts ...event.EmitterOpt) (event.Emitter, error) { ... }
Stebalien commented 4 years ago

cc @petar