Resolves conflicts after remote delta actions have been applied

@param {Object|null} err - error object
@param {Object} snycedNode - node with applied actions from database
@param {Function} callback - callback function
@returns {void} - no return value
541322
function resolveConflicts(err, syncedNode, callback) {
  if(err) return callback(err);
  if(!syncedNode) return callback(null);

  async.series([
    (cb) => {
      if(syncedNode.directory === true) {
        resolveDirectoryConflicts(syncedNode, cb);
      } else {
        resolveFileConflicts(syncedNode, cb);
      }
    },
    (cb) => {
      findLocalConflict(syncedNode, cb);
    }
  ], (err, res) => {
    if(err) return callback(err);

    callback(null);
  });
}
180820
function deleteNode(node, immediate, callback) {
  node.localActions = {delete: {
    remoteId: node.remoteId,
    actionInitialized: new Date(),
    immediate
  }};

  syncDb.update(node._id, node, callback);
}
1147679
function step(err, res) {
  if (!err && res && res.error) {
    console.log('ERR', res);
    err = res.error;
  }
  var nextStep = steps.shift();
  if (err && curStep !== 'delIndex') {
    console.log('failing on', curStep, err);
    console.trace();
    callback(err);
    return;
  }
  if (nextStep) {
    curStep = nextStep;
    var data = stepDefs[curStep].data;
    utils.doPostJson(stepDefs[curStep], data, step);
  } else {
    callback(err, res);
  }
}
1032933
function reqRegionForNetworkingError(resp, done) {
    if (!AWS.util.isBrowser()) {
      return done();
    }
    var error = resp.error;
    var request = resp.request;
    var bucket = request.params.Bucket;
    if (!error || error.code !== 'NetworkingError' || !bucket ||
        request.httpRequest.region === 'us-east-1') {
      return done();
    }
    var service = request.service;
    var bucketRegionCache = service.bucketRegionCache;
    var cachedRegion = bucketRegionCache[bucket] || null;

    if (cachedRegion && cachedRegion !== request.httpRequest.region) {
      service.updateReqBucketRegion(request, cachedRegion);
      done();
    } else if (!service.dnsCompatibleBucketName(bucket)) {
      service.updateReqBucketRegion(request, 'us-east-1');
      if (bucketRegionCache[bucket] !== 'us-east-1') {
        bucketRegionCache[bucket] = 'us-east-1';
      }
      done();
    } else if (request.httpRequest.virtualHostedBucket) {
      var getRegionReq = service.listObjects({Bucket: bucket, MaxKeys: 0});
      service.updateReqBucketRegion(getRegionReq, 'us-east-1');
      getRegionReq._requestRegionForBucket = bucket;

      getRegionReq.send(function() {
        var region = service.bucketRegionCache[bucket] || null;
        if (region && region !== request.httpRequest.region) {
          service.updateReqBucketRegion(request, region);
        }
        done();
      });
    } else {
      // DNS-compatible path-style
      // (s3ForcePathStyle or bucket name with dot over https)
      // Cannot obtain region information for this case
      done();
    }
   }
930483
function onRequestError(error, result, endCallback) {
      result.currentRetries++;
      async.parallel([
        async.apply(recrawlError, error, result),
        async.apply(retrySameUrl,error, result)
      ],function(error){
          endCallback(error);
      });

  }
721970
function (callback) {
    return function (err, stdout, stderr) {
        if (err) {
            throw err;
        } else if (stderr) {
            log('sync error', 'failed with the following output:');
            console.log('\n', stderr, '\n');
        } else {
            log('sync', 'completed successfully');
            log();
            if (callback) callback();
        }
    };
}
1008171
public void unableToSend(String nodeID, LinkedList<byte[]> packets, Throwable cause) {
		if (nodeID != null) {
			executor.execute(() -> {

				// Debug
				if (debug) {
					logger.warn("Unable to send message to \"" + nodeID + "\".", cause);
				}

				// Mark endpoint as offline
				NodeDescriptor node = nodes.get(nodeID);
				boolean disconnected = false;
				if (node != null) {
					node.writeLock.lock();
					try {
						if (node != null && node.markAsOffline()) {

							// Remove actions and listeners
							registry.removeActions(nodeID);
							eventbus.removeListeners(nodeID);
							writer.close(node.nodeID);
							disconnected = true;

						}
					} catch (Exception error) {
						logger.warn("Unable to turn off node!", error);
					} finally {
						node.writeLock.unlock();
					}
				}
				if (node != null && disconnected) {

					// Notify listeners (unexpected disconnection)
					logger.info("Node \"" + nodeID + "\" disconnected.");
					broadcastNodeDisconnected(node.info, true);
				}

				// Send error back to the source
				if (packets != null) {
					FastBuildTree errorMap = null;
					if (cause != null) {

						// Convert to Throwable to MoleculerError
						MoleculerError moleculerError;
						if (cause instanceof MoleculerError) {
							moleculerError = (MoleculerError) cause;
						} else {
							String message = String.valueOf(cause.getMessage());
							message = message.replace('\r', ' ').replace('\n', ' ').trim();
							moleculerError = new MoleculerError(message, cause, "MoleculerError", nodeID, false, 500,
									"UNKNOWN_ERROR");
						}

						// Convert MoleculerError to JSON
						errorMap = new FastBuildTree(8);
						moleculerError.toTree(errorMap);
					}
					for (byte[] packet : packets) {
						try {

							// Remove header
							if (packet != null && packet.length > 6) {
								byte[] copy = new byte[packet.length - 6];
								System.arraycopy(packet, 6, copy, 0, copy.length);

								// Deserialize packet
								Tree message = serializer.read(copy);

								// Get request's unique ID
								String id = message.get("id", (String) null);
								if (id == null || id.isEmpty()) {

									// Not a request
									return;
								}

								// Create response message
								FastBuildTree response = new FastBuildTree(6);
								response.putUnsafe("id", id);
								response.putUnsafe("ver", ServiceBroker.PROTOCOL_VERSION);
								response.putUnsafe("sender", nodeID);
								response.putUnsafe("success", false);
								response.putUnsafe("data", (String) null);
								if (errorMap != null) {
									response.putUnsafe("error", errorMap);
								}
								registry.receiveResponse(response);
							}
						} catch (Exception error) {
							logger.warn("Unable to handle error!", error);
						}
					}
				}
			});
		}
	}
53286
function(callback) {
        var self = this;

        this.loadbalancer.updateNode(self, function(err, nodes) {
            if (err) {
                callback(err);
                return;
            }

            nodes.forEach(function(node) {
                if (node.id == self.id) {
                    self = node;
                }
            });

            callback(err);
        });
    }
782752
function callbacks(err) {
      var fn = route.callbacks[i++];
      try {
        if ('route' == err) {
          nextRoute();
        } else if (err && fn) {
          if (fn.length < 4) return callbacks(err);
          fn(err, req, res, callbacks);
        } else if (fn) {
          if (fn.length < 4) return fn(req, res, callbacks);
          callbacks();
        } else {
          nextRoute(err);
        }
      } catch (err) {
        callbacks(err);
      }
    }
1294055
function (err) {
                if (_.isNull(err)) {
                    // Call complete with all the args except for err
                    complete.apply(null, Array.prototype.slice.call(arguments, 1));
                } else {
                    error(err);
                }
            }
1297413
function cb(err) {
        if (callback) {
            if (err) return callback(err);
            callback(null, rec);
        }
        callback = null;
        if (!err) {
            that.emit('logged', rec);
        }
    }
32294
function updateNode(node, callback) {
  syncDb.update(node._id, node, (err, result) => {
    if(err) return callback(err);

    callback(null, node);
  });
}
403637
function callback(err, response, body)
    {
      if (err)
      {
        // if we haven't exceeded the maximum number of retries yet and the
        // server came back with a retryable error code.
        if (numRetries < maxNumRetries && isRetryableError(response, err))
        {
          // increment the number of retries
          numRetries++;

          // use exponential backoff with decorrelated jitter to compute the
          // next sleep time:
          var cap = connectionConfig.getRetryLargeResultSetMaxSleepTime();
          sleep = Util.nextSleepTime(1, cap, sleep);

          // wait the appropriate amount of time before retrying the request
          setTimeout(sendRequest, sleep * 1000);
        }
        else
        {
          // wrap the error into a network error
          err = Errors.createNetworkError(
            ErrorCodes.ERR_LARGE_RESULT_SET_NETWORK_COULD_NOT_CONNECT, err);
        }
      }
      // if the response contains xml, build an S3/Blob error from the response
      else if (response.getResponseHeader('Content-Type') ===
        'application/xml')
      {
        err = Errors.createLargeResultSetError(
          ErrorCodes.ERR_LARGE_RESULT_SET_RESPONSE_FAILURE, response);
      }

      // if we have an error, clear the body
      if (err)
      {
        body = null;
      }

      // if a callback was specified, invoke it
      if (Util.isFunction(options.callback))
      {
        options.callback(err, body);
      }
    }
32112
function onServerPreHandler (ctx, err, value) {
  if (err) {
    if (err instanceof SuperError) {
      ctx._response.error = err.rootCause || err.cause || err;
    } else {
      ctx._response.error = err;
    }

    const internalError = new Errors.MostlyError(
        Constants.EXTENSION_ERROR, ctx.errorDetails).causedBy(err);
    ctx.log.error(internalError);

    return ctx.finish();
  }

  // reply value from extension
  if (value) {
    ctx._response.payload = value;
    return ctx.finish();
  }

  try {
    let action = ctx._actMeta.action.bind(ctx);

    // execute add middlewares
    ctx._actMeta.dispatch(ctx._request, ctx._response, (err) => {
      // middleware error
      if (err) {
        if (err instanceof SuperError) {
          ctx._response.error = err.rootCause || err.cause || err;
        } else {
          ctx._response.error = err;
        }

        let internalError = new Errors.MostlyError(
            Constants.ADD_MIDDLEWARE_ERROR, ctx.errorDetails).causedBy(err);
        ctx.log.error(internalError);

        return ctx.finish();
      }

      // if request type is 'pubsub' we dont have to reply back
      if (ctx._request.payload.request.type === Constants.REQUEST_TYPE_PUBSUB) {
        action(ctx._request.payload.pattern);
        return ctx.finish();
      }

      // execute RPC action
      if (ctx._actMeta.isPromisable) {
        action(ctx._request.payload.pattern)
          .then(x => ctx._actionHandler(null, x))
          .catch(e => ctx._actionHandler(e));
      } else {
        action(ctx._request.payload.pattern, ctx._actionHandler.bind(ctx));
      }
    });
  } catch (err) {
    if (err instanceof SuperError) {
      ctx._response.error = err.rootCause || err.cause || err;
    } else {
      ctx._response.error = err;
    }

    // service should exit
    ctx._shouldCrash = true;

    ctx.finish();
  }
}
979896
function(callback) {
    //process first all directories and then all files.
    async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => {
      syncDb[nodeSource]((err, nodes) => {
        async.eachSeries(nodes, (node, cb) => {

          // If a node has to be redownloaded do not delete it remotely
          // See: https://github.com/gyselroth/balloon-node-sync/issues/17
          if(node.downloadOriginal) return cb();

          var nodePath = utility.joinPath(node.parent, node.name);

          process.nextTick(() => {
            var nodePath = utility.joinPath(node.parent, node.name);

            if(fsWrap.existsSync(nodePath) === false) {
              //Node doesn't exist localy -> delete it remotely
              deleteNode(node, false, cb);
            } else {
              try {
                var stat = fsWrap.lstatSync(nodePath);
              } catch(e) {
                logger.warning('findDeletedNodes got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code});
                throw new BlnDeltaError(e.message);
              }

              if(stat.ino === node.ino) {
                //node still exists at given path
                return cb();
              } else {
                deleteNode(node, true, cb);
              }
            }
          });
        }, cbMap);
      });
    }, callback);
  }
145696
function _handleResult(callback, err, res) {
    return callback(null, {
        error:  err,
        result: res
    });
}
882837
function golr_callback_action(resp){

		// Gather out info from the first doc since we called
		// by ID.
		var doc = resp.get_doc(0) || {};
		var ans = common_doc(mustache.to_html(tmpl, doc));
		response.resolve(ans);
	    }