Skip to content
This repository has been archived by the owner on Mar 11, 2020. It is now read-only.

A proposal regarding over-complicated connection API. #26

Closed
serzero2007 opened this issue May 31, 2018 · 2 comments
Closed

A proposal regarding over-complicated connection API. #26

serzero2007 opened this issue May 31, 2018 · 2 comments
Labels

Comments

@serzero2007
Copy link

For now Connection API is a ES6 class with a lot of methods, used inconsistently along the codebase. I have experimented for some time with a different ways how to change the design, and would like to share my findings.

  1. Treat connections as a generic objects without defining a class.
  2. From the typescript point of view these objects should provide Duplex Stream interface and Peer Info interface (have properties peerInfo and a method getObservedAddrs).
  3. Creating new connection objects using factories and transformation functions.

Why this approach is interesting? Well, see:

  1. Factory
function attachPeerInfo (stream: Duplex, peerInfo: PeerInfo): Connection {
  stream.peerInfo = peerInfo
  if (stream.observer) stream.observer(stream, peerInfo, 'new', 'peerInfo')
  return stream // Actually a connection
}
  1. Attaching the observer to the connection, so that observer function is called for each message:
import { tap } from 'pull-tap'

export function observeDuplexStream (stream, observer) {
  stream.observer = observer

  // This will allow to easely get stream.peerInfo
  let _out = tap(msg => stream.observer(stream, stream.peerInfo, 'out', msg))
  let _in  = tap(msg => stream.observer(stream, stream.peerInfo, 'in',  msg))

  // Monkey-patching the underlying streams
  stream.source = pull(stream.source, _out)
  stream.sink   = pull(_in, stream.sink)

  return stream
}

That's all. There is no need to define a complex interaction on the data. Observer will see the peerInfo on the stream when it appears.
3) The proxy stream with an observer and a different peerInfo attached:

const { duplex } = require('pull-defer')

function createProxyConnection (swarm): Connection {
  let proxy = duplex()
  // Basically a mixins that define the connection behaviour
  observeDuplexStream(proxy, swarm.observer)
  attachPeerInfo(proxy, swarm.peerInfo)
  // it's created! 
  return proxy
}

What do you think?

Also this would allow to add any number of annotations. ES6 Symbols can be used to get rid of name collision problems.

@serzero2007
Copy link
Author

Also I have found this https://github.com/stampit-org/stamp that could simplify a lot dealing with a prototypical inheritance.

@jacobheun
Copy link
Contributor

The API has changed to an async iterators based api, and has significantly changed. Closing this as it no longer applies to the current API.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants