All files index.js

89.23% Statements 116/130
82.35% Branches 70/85
88.46% Functions 23/26
91.53% Lines 108/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262  3x   3x                               89x 68x       105x 76x     3x   22x 22x   22x 22x 60x 22x 22x 22x 22x 19x   22x 22x 22x   22x 22x   111x 76x       2x 2x 2x       88x       22x 10x 10x 10x       22x         89x   68x 22x 22x 22x   20x 8x   8x     12x   20x   20x         68x 12x 12x 12x 12x       12x 12x     12x   12x   12x             22x                     22x     29x   49x               49x 105x 105x 87x                 13x 13x   74x       16x 16x       105x 29x       29x 30x                 30x 30x 30x   30x   30x   17x 14x 12x 12x 12x   2x 1x 1x   1x       13x 13x     12x 12x 12x       30x 30x                 10x         10x 10x 10x   10x     3x 3x 4x 2x 2x       8x   8x 6x 5x 5x     8x              
'use strict'
var Obv = require('obv')
 
var STATES = {
  queried: 1,
  checking: 2,
  checked: 3,
 
  //I realized that this state is maybe not necessary
  //since we actually track this on a per peer basis.
  //requesting: 4,
 
  responded: 5, //we have received at least one response
 
  processing: 6,
  processed: 7 //now we can broadcast this
}
 
function each (obj, fn) {
  for(var k in obj)
    fn(obj[k], k, obj)
}
 
function isEmpty (o) {
  for(var k in o) return false
  return true
}
 
module.exports = function (opts) {
  //opts has {check, process, increment, isQuery, isResponse}
  var state = {}
  var localCbs = {}
 
  var initialWeight = opts.initialWeight || -1
  var increment = opts.increment || function (n) { return Number(n) - 1 }
  var isRequest = opts.isRequest || function (value) { return typeof value === 'number' && value < 0 }
  var isResponse = opts.isResponse || function (value) { return !isRequest(value) }
  var isQuery = opts.isQuery || function () { return true }
  var process = opts.process || function (k, v, cb) { cb (null, v) }
  var compare = opts.compare || function (a, b) {
    return b - a
  }
  var maximum = opts.maximum || -3
  var timeout = opts.timeout || 30e3
  var nextTimeout = 0
 
  var obv = Obv()
  obv.set(state)
  function next (fn) {
    if(!fn) obv.set(state)
    else obv.once(fn, false)
  }
 
  function ErrorTimeout() {
    var err = new Error('gossip-query: request timed out')
    err.name = 'request_timeout'
    return err
  }
 
  function setTimestamp() {
    return Date.now()
  }
 
  function callback (k, value, err) {
    if (localCbs[k]) {
      var cbs = localCbs[k]
      delete localCbs[k]
      while (cbs.length) cbs.shift()(err, value)
    }
  }
 
  obv(function () {
    //XXX: I think there could be some bugs in this because
    //obv.set is triggered from inside the loop (if check/process)
    //callback sync, which can happen.
 
    each(state, function (item, k) {
      //check the local store when new queries are added
      if(item.state === STATES.queried) {
        item.state = STATES.checking
        item.ts = setTimestamp()
        opts.check(k, function (_, value) {
          //igore error
          if(value && !item.value) {
            item.state = STATES.processed
            //UPDATE VALUE
            callback(k, item.value = value)
          }
          else
            item.state = STATES.checked
 
          item.ts = setTimestamp()
 
          obv.set(state)
        })
      }
 
      //process items received
      if(item.value != null && item.state === STATES.responded) {
        item.state = STATES.processing
        item.ts = setTimestamp()
        process(k, item.value, function (err, value) {
          Iif(err) {
            //stay in processing state
            return
          }
          item.state = STATES.processed
          item.ts = setTimestamp()
          //this is the only place that localCbs is called,
          //except for in query(key, cb) if key is already ready.
          Eif(value)
            //UPDATE VALUE
            callback(k, item.value = value)
 
          obv.set(state)
        })
      }
    })
  })
 
  function initial (weight) {
    return {
      state: STATES.queried,
      weight: weight,
      value: null,
      requestedBy: {},
      requestedFrom: {},
      respondedTo: {},
      ts: setTimestamp()
    }
  }
 
  return {
    state: state,
    createStream: function (peerId) {
      return {
        source: function (end, cb) {
          Iif(end) {
            for(var k in state) {
              delete state[k].respondedTo[peerId]
              delete state[k].requestedFrom[peerId]
            }
            return
          }
          //read the next pieces of data from the state object.
          ;(function read () {
            var data = {}
            for(var k in state) {
              if(
                //this item has been received & processed, respond to any other peers
                //idea: make respondedTo be a counter, for queries with multiple answers.
                state[k].state === STATES.processed &&
                state[k].requestedBy[peerId] &&
                //responded to != state[k].value.length
                !state[k].respondedTo[peerId]
              ) {
                // change bool to integer, and send data since that index
                state[k].respondedTo[peerId] = true
                data[k] = state[k].value
              }
              else if(
                state[k].state === STATES.checked &&
                !state[k].requestedFrom[peerId]
              ) {
                state[k].requestedFrom[peerId] = true
                data[k] = state[k].weight //the number of hops, etc
              }
            }
            //next(read) calls read again when something changes in the state.
            if(isEmpty(data)) next(read)
            else cb(null, data)
          })()
        },
        sink: function (read) {
          read(null, function more (end, data) {
            Iif(end) {
              for(var k in state) {
                delete state[k].requestedBy[peerId]
              }
              //Q: how does the source decide to end?
              //A: the network connection aborts the stream.
              return
            }
            //process this message and possibly update the state.
            var update = false
            for(var k in data) {
              var value = data[k]
               //ignore invalid requests
              Iif(!isQuery(k) || !(isRequest(value) || isResponse(value, k)))
                ;
              else if(isRequest(data[k])) {
                //if we already have seen this query:
                if(compare(data[k], maximum) < 0) {
                  if(!state[k]) {
                    update = true
                    state[k] = initial(increment(data[k]))
                    state[k].requestedBy[peerId] = true
                  }
                  else if (compare(data[k], state[k].weight) < 0){
                    update = true
                    state[k].requestedBy[peerId] = true
                    //update the weight if this peer is closer to us
                    state[k].weight = increment(data[k])
                  }
                }
              }
              else Eif(isResponse(data[k])) {
                if(state[k].state == STATES.checked) {
                  //what states can it be in here?
                  //what if we are currently processing something and a new response arrives?
                  state[k].state = STATES.responded
                  state[k].value = data[k]
                  update = true
                }
              }
            }
            if(update) next()
            read(null, more)
          })
        }
      }
    },
 
    query: function (k, cb) {
      var update
      //add to state object and update
      Iif(state[k]) {
        if(state[k].state == STATES.processed) cb(null, state[k].value)
        else (localCbs[k] = localCbs[k] || []).push(cb)
      }
      else {
        update = true
        state[k] = initial(initialWeight)
        localCbs[k] = [cb]
      }
     Eif(update) next()
    },
    checkTimeout: function () {
      var ts = Date.now()
      for(var k in state)
        if(state[k].ts + timeout < ts) {
          callback(k, null, ErrorTimeout(k))
          delete state[k]
        }
    },
    progress: function () {
      var prog = {start: 0, current: 0, target: 0}
 
      for(var k in state) {
        if(Date.now() - state[k].ts < timeout) {
          prog.current += state[k].state
          prog.target += STATES.processed
        }
      }
      return prog
    }
  }
}