Skip to content
This repository has been archived by the owner on Aug 29, 2023. It is now read-only.

Commit

Permalink
chore: callbacks -> async / await
Browse files Browse the repository at this point in the history
BREAKING CHANGE: All places in the API that used callbacks are now replaced with async/await
  • Loading branch information
dirkmc committed Apr 2, 2019
1 parent 3ab43a3 commit d22c9ed
Show file tree
Hide file tree
Showing 11 changed files with 268 additions and 109 deletions.
53 changes: 27 additions & 26 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
# Warning: This file is automatically synced from https://github.com/ipfs/ci-sync so if you want to change it, please change it there and ask someone to sync all repositories.
sudo: false
language: node_js
cache: npm

matrix:
include:
- node_js: 6
env: CXX=g++-4.8
- node_js: 8
env: CXX=g++-4.8
# - node_js: stable
# env: CXX=g++-4.8
stages:
- check
- test
- cov

node_js:
- '10'

script:
- npm run lint
- npm run test
- npm run coverage
os:
- linux
- osx

before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
script: npx nyc -s npm run test:node -- --bail
after_success: npx nyc report --reporter=text-lcov > coverage.lcov && npx codecov

jobs:
include:
- os: windows
filter_secrets: false
cache: false

after_success:
- npm run coverage-publish
- stage: check
script:
- npx aegir build --bundlesize
- npx aegir commitlint --travis
- npx aegir dep-check
- npm run lint

addons:
firefox: 'latest'
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
notifications:
email: false
21 changes: 12 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
"main": "src/index.js",
"scripts": {
"lint": "aegir lint",
"test": "aegir test -t node -f test/**/*.js",
"release": "aegir release -t node --no-build",
"release-minor": "aegir release -t node --type minor --no-build",
"release-major": "aegir-release -t node --type major --no-build",
"test": "aegir test -t node",
"test:node": "aegir test -t node",
"build": "aegir build",
"docs": "aegir docs",
"release": "aegir release --docs -t node",
"release-minor": "aegir release --type minor --docs -t node",
"release-major": "aegir release --type major --docs -t node",
"coverage": "aegir coverage",
"coverage-publish": "aegir coverage --provider coveralls"
"coverage-publish": "aegir-coverage publish"
},
"pre-push": [
"lint",
Expand All @@ -34,24 +37,24 @@
"npm": ">=3.0.0"
},
"devDependencies": {
"aegir": "^15.1.0",
"aegir": "^18.1.1",
"chai": "^4.1.2",
"dirty-chai": "^2.0.1",
"interface-transport": "~0.3.6",
"lodash.isfunction": "^3.0.9",
"pull-stream": "^3.6.9"
},
"dependencies": {
"async-iterator-to-pull-stream": "^1.3.0",
"class-is": "^1.1.0",
"debug": "^3.1.0",
"err-code": "^1.1.2",
"interface-connection": "~0.3.2",
"ip-address": "^5.8.9",
"lodash.includes": "^4.3.0",
"lodash.isfunction": "^3.0.9",
"mafmt": "^6.0.2",
"multiaddr": "^5.0.0",
"once": "^1.4.0",
"stream-to-pull-stream": "^1.7.2"
"multiaddr": "^5.0.0"
},
"contributors": [
"Alan Shaw <alan@tableflip.io>",
Expand Down
80 changes: 80 additions & 0 deletions src/adapter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
'use strict'

const { Connection } = require('interface-connection')
const withIs = require('class-is')
const toPull = require('async-iterator-to-pull-stream')
const error = require('pull-stream/sources/error')
const drain = require('pull-stream/sinks/drain')
const TCP = require('./')
const noop = () => {}

function callbackify (fn) {
return async function (...args) {
let cb = args.pop()
if (typeof cb !== 'function') {
args.push(cb)
cb = noop
}
let res
try {
res = await fn(...args)
} catch (err) {
return cb(err)
}
cb(null, res)
}
}

// Legacy adapter to old transport & connection interface
class TcpAdapter extends TCP {
dial (ma, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}

callback = callback || noop

const conn = new Connection()

super.dial(ma, options)
.then(socket => {
conn.setInnerConn(toPull.duplex(socket))
conn.getObservedAddrs = callbackify(socket.getObservedAddrs.bind(socket))
conn.close = callbackify(socket.close.bind(socket))
callback(null, conn)
})
.catch(err => {
conn.setInnerConn({ sink: drain(), source: error(err) })
callback(err)
})

return conn
}

createListener (options, handler) {
if (typeof options === 'function') {
handler = options
options = {}
}

const server = super.createListener(options, socket => {
const conn = new Connection(toPull.duplex(socket))
conn.getObservedAddrs = callbackify(socket.getObservedAddrs.bind(socket))
handler(conn)
})

const proxy = {
listen: callbackify(server.listen.bind(server)),
close: callbackify(server.close.bind(server)),
getAddrs: callbackify(server.getAddrs.bind(server)),
getObservedAddrs: callbackify(() => server.getObservedAddrs())
}

return new Proxy(server, { get: (_, prop) => proxy[prop] || server[prop] })
}
}
module.exports = withIs(TcpAdapter, {
className: 'TCP',
symbolName: '@libp2p/js-libp2p-tcp/tcp'
})
8 changes: 8 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict'

// IPFS multi-address code
module.exports.IPFS_MA_CODE = 421

// Time to wait for a connection to close gracefully before destroying it
// manually
module.exports.CLOSE_TIMEOUT = 2000
63 changes: 34 additions & 29 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,61 @@
'use strict'

const net = require('net')
const toPull = require('stream-to-pull-stream')
const mafmt = require('mafmt')
const withIs = require('class-is')
const includes = require('lodash.includes')
const isFunction = require('lodash.isfunction')
const Connection = require('interface-connection').Connection
const once = require('once')
const errcode = require('err-code')
const debug = require('debug')
const log = debug('libp2p:tcp:dial')

const Libp2pSocket = require('./socket')
const createListener = require('./listener')

function noop () {}

class TCP {
dial (ma, options, callback) {
if (isFunction(options)) {
callback = options
options = {}
}

callback = once(callback || noop)

async dial (ma, options) {
const cOpts = ma.toOptions()
log('Connecting to %s %s', cOpts.port, cOpts.host)
log('Connecting to %s:%s', cOpts.host, cOpts.port)

const rawSocket = net.connect(cOpts)
const rawSocket = await this._connect(cOpts)
return new Libp2pSocket(rawSocket, ma, options)
}

rawSocket.once('timeout', () => {
log('timeout')
rawSocket.emit('error', new Error('Timeout'))
})
_connect (cOpts) {
return new Promise((resolve, reject) => {
const start = Date.now()
const rawSocket = net.connect(cOpts)

rawSocket.once('error', callback)
const onError = (err) => {
const msg = `Error connecting to ${cOpts.host}:${cOpts.port}: ${err.message}`
done(errcode(msg, err.code))
}

rawSocket.once('connect', () => {
rawSocket.removeListener('error', callback)
callback()
})
const onTimeout = () => {
log('Timeout connecting to %s:%s', cOpts.host, cOpts.port)
const err = errcode(`Timeout after ${Date.now() - start}ms`, 'ETIMEDOUT')
rawSocket.emit('error', err)
}

const socket = toPull.duplex(rawSocket)
const onConnect = () => {
log('Connected to %s:%s', cOpts.host, cOpts.port)
done(null, rawSocket)
}

const conn = new Connection(socket)
const done = (err, res) => {
rawSocket.removeListener('error', onError)
rawSocket.removeListener('timeout', onTimeout)
rawSocket.removeListener('connect', onConnect)

conn.getObservedAddrs = (callback) => {
return callback(null, [ma])
}
err ? reject(err) : resolve(res)
}

return conn
rawSocket.once('error', onError)
rawSocket.once('timeout', onTimeout)
rawSocket.once('connect', onConnect)
})
}

createListener (options, handler) {
Expand All @@ -59,7 +65,6 @@ class TCP {
}

handler = handler || noop

return createListener(handler)
}

Expand Down
Loading

0 comments on commit d22c9ed

Please sign in to comment.