main

@exports tickle
@function tickle
@param {Object} req - client request
@param {Object} [res] - response to client
@param {next} [next] - continue routes
@return {Integer|Functions}
339818
function tickle(req, res, next) {

  req.tickle = global.tickle.add(req.url);
  return next !== undefined ? next() : req.tickle;
}
1041759
function requestHandler(req, res, next) {
  const params = req && req.params;
  const start = Date.now();
  let source;
  let opts;

  return Promise.try(() => {
    source = core.getPublicSource(params.src);

    if (!_.contains(source.formats, params.format)) {
      throw new Err('Format %s is not known', params.format).metrics('err.req.format');
    }

    params.z = core.validateZoom(params.z, source);
    params.scale = core.validateScale(params.scale, source);

    params.x = checkType.strToInt(params.x);
    params.y = checkType.strToInt(params.y);
    if (
      !qidx.isValidCoordinate(params.x, params.z) || !qidx.isValidCoordinate(params.y, params.z)
    ) {
      throw new Err('x,y coordinates are not valid, or not allowed for this zoom').metrics('err.req.coords');
    }

    opts = {
      z: params.z,
      x: params.x,
      y: params.y,
    };
    if (params.format !== 'pbf') {
      // Ensure that PNGs are not 32bit
      // TODO: this should be source-configurable
      opts.format = params.format === 'png' ? 'png8:m=h' : params.format;
      if (params.scale) {
        opts.scale = params.scale;
      }
    }
    if (req.query && req.query.lang) {
      if (!langCodeRe.test(req.query.lang)) {
        throw new Err('lang param is not valid').metrics('err.req.lang');
      }
      opts.lang = req.query.lang;
    }

    // fixme: Force all tiles to be treated as vector
    opts.treatAsVector = true;

    return source.getHandler().getAsync(opts);
  }).then((result) => {
    let mx;

    core.setResponseHeaders(res, source, result.headers);

    if (params.format === 'json') {
      // Allow JSON to be shortened to simplify debugging
      res.json(filterJson(req.query, result.data));
    } else {
      res.send(result.data);
    }

    mx = util.format('req.%s.%s.%s', params.src, params.z, params.format);
    if (params.scale) {
      // replace '.' with ',' -- otherwise grafana treats it as a divider
      mx += `.${params.scale.toString().replace('.', ',')}`;
    }
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
825156
def main(
    context: click.core.Context, method: str, request_type: str, id: Any, send: str
) -> None:
    
    exit_status = 0
    # Extract the jsonrpc arguments
    positional = [a for a in context.args if "=" not in a]
    named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a}
    # Create the request
    if request_type == "notify":
        req = Notification(method, *positional, **named)
    else:
        req = Request(method, *positional, request_id=id, **named)  # type: ignore
    # Sending?
    if send:
        client = HTTPClient(send)
        try:
            response = client.send(req)
        except JsonRpcClientError as e:
            click.echo(str(e), err=True)
            exit_status = 1
        else:
            click.echo(response.text)
    # Otherwise, simply output the JSON-RPC request.
    else:
        click.echo(str(req))
    sys.exit(exit_status)
1083450
function (req, res, err) {
    if (isResHeaderSent(res)) { //request has already been closed
        //console.log('cannot throw error on an already closed request')
        return;
    }
    if (typeof (err.stack) == 'string') {
        err.stack = err.stack.split(' at '); //stack string to array
    }
    var isHtml = new reqres(res, req).isHtml();
    if (isHtml) {
        ack.router().htmlCloseError({ debug: isProductionMode })(err, req, res);
    }
    else {
        ack.router().jsonCloseError({ debug: isProductionMode })(err, req, res);
    }
    resMarkClosed(res);
}
1358273
function(req, res, next) {
                if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
                  req.url = '/index.html'; // eslint-disable-line no-param-reassign
                }
                next();
              }
465187
function (req, res) {
		LOG.warn('handle_request');

		// attach custom res methods (borrowed from express)
		res = UTIL.mixin(res, response);

		LOG.sys('HTTP req received, header', 'SR.REST');
		LOG.sys(req.headers, 'SR.REST');
		
		var content_type = req.headers['content-type'];

		// NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly
		if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { 
			LOG.warn('parsing form request...', 'SR.REST');
			route(req, res);
			return;
		}
		
		// temp buffer for incoming request
		var data = '';
		var JSONobj = undefined;
		
		req.on('data', function (chunk) {
			data += chunk;
		});

		req.on('end', function () {
			
			var JSONobj = undefined;
			
			try {
				if (data !== '') {
						
					if (content_type.startsWith('application/x-www-form-urlencoded')) {
						JSONobj = qs.parse(data);
					} else if (content_type.startsWith('application/json')) {
						JSONobj = UTIL.convertJSON(decodeURIComponent(data));
					} else if (content_type.startsWith('application/sdp')) {
						JSONobj = data;
					} else {
						var msg = 'content type not known: ' + content_type;
						LOG.warn(msg, 'SR.REST');
						SR.REST.reply(res, msg);
						//res.writeHead(200, {'Content-Type': 'text/plain'});
						//res.end(msg);
						return;
					}
				}
			} catch (e) {
				var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type;
				LOG.error(msg, 'SR.REST');
				//res.writeHead(200, {'Content-Type': 'text/plain'});
				//res.end(msg);
				SR.REST.reply(res, msg);
				return;
			}

			route(req, res, JSONobj);
		})
	}
187143
function execute(req, res) {
  this.state.pubsub.punsubscribe(req.conn, req.args);
}
705176
function handler(req, res) {
    // Support both the ?url= mode and the X-WTF-URL header.
    var targetUrl;
    if (req.headers['x-wtf-url']) {
      targetUrl = req.headers['x-wtf-url'];
    } else {
      var parsedUrl = url.parse(req.url, true);
      var query = parsedUrl.query;
      targetUrl = query.url;
    }
    if (!targetUrl || targetUrl.indexOf('http') != 0) {
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end();
      return;
    }

    res.on('error', function(e) {
      console.log('ERROR (source): ' + e);
    });

    var targetModule = targetUrl.indexOf('https') == 0 ? https : http;
    targetModule.get(targetUrl, function(originalRes) {
      // Eat errors, otherwise the app will die.
      originalRes.on('error', function(e) {
        console.log('ERROR (target): ' + e);
      });

      // Pull out content type to see if we are interested in it.
      var supportedContentType = false;
      var contentType = originalRes.headers['content-type'];
      if (contentType && contentType.indexOf(';') != 0) {
        contentType = contentType.substr(0, contentType.indexOf(';'));
      }
      switch (contentType) {
        case 'text/javascript':
        case 'application/javascript':
          supportedContentType = true;
          break;
      }

      // Also parse the URL - some servers don't return content type for some
      // reason.
      var supportedPath = false;
      var contentUrl = url.parse(targetUrl);
      if (path.extname(contentUrl.pathname) == '.js') {
        supportedPath = true;
      }

      if (supportedContentType || supportedPath) {
        var headers = [];
        for (var key in originalRes.headers) {
          if (key == 'content-length') {
            continue;
          }
          headers.push([key, originalRes.headers[key]]);
        }
        res.writeHead(originalRes.statusCode, headers);
        injectStream(targetUrl, originalRes, res);
      } else {
        console.log('Pass-through: ' + targetUrl, contentType);
        res.writeHead(originalRes.statusCode, originalRes.headers);
        originalRes.pipe(res);
      }
    }).on('error', function(e) {
      console.log(e);
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end(e.message);
    });
  }
1198280
function requestHandler(req, res, next) {
  const start = Date.now();
  let source;

  return Promise.try(() => {
    source = core.getPublicSource(req.params.src);
    return source.getHandler().getInfoAsync().then(info => [info, infoHeaders]);
  }).spread((data, dataHeaders) => {
    core.setResponseHeaders(res, source, dataHeaders);

    if (req.query && req.query.format) {
      const escapedText = JSON.stringify(data, null, ' ').replace(/&/g, '&amp;').replace(/</g, '&lt;');
      res.send(`<pre>${escapedText}</pre>`);
    } else {
      res.json(data);
    }

    const mx = util.format('req.%s.info', req.params.src);
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
773029
function request( next ) {
	/* jshint validthis: true */
	var self = this,
		body = '',
		req;

	this.req.opts.agent = agent;

	// TODO: record request headers
	// TODO: record request header length
	// TODO: record request body length

	req = http.request( this.req.opts, onResponse );
	req.on( 'error', onError );

	this.start = Date.now();
	this.timer = process.hrtime();

	if ( this.req.body ) {
		req.write( this.req.body );
	}
	req.end();

	cache[ this.rid ] = req;

	/**
	* FUNCTION: onConnect( response, socket, head )
	*	Callback invoked upon connecting to a server.
	*
	* @private
	* @param {Object} response - HTTP response object
	* @param {Socket} socket - TCP socket
	* @param {Object} head - HTTP response head
	*/
	function onConnect( response, socket, head ) {
		// Do something...
	}

	/**
	* FUNCTION: onResponse( response )
	*	Callback invoked upon receiving an HTTP response.
	*
	* @private
	* @param {Object} response - HTTP response object
	*/
	function onResponse( res ) {
		self.res.status = res.statusCode;
		self.res.headers = res.headers;

		// TODO: record headers length

		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}

	/**
	* FUNCTION: onError( error )
	*	Callback invoked if an error is encountered while making a request.
	*
	* @private
	* @param {Error} error - error object
	*/
	function onError( error ) {
		self.req.error = error;
		if ( process.connected ) {
			// TODO: log (or not; serialize in output message?)
			console.error( process.pid, 'request', error );
		}
	}

	/**
	* FUNCTION: onData( chunk )
	*	Callback invoked after receiving a chunk of response data.
	*
	* @private
	* @param {Buffer} chunk - response data
	*/
	function onData( chunk ) {
		self.res.bytes += chunk.length;
		body += chunk.toString();
	}

	/**
	* FUNCTION: onEnd()
	*	Callback invoked after a response ends.
	*
	* @private
	*/
	function onEnd() {
		self.elapsed = process.hrtime( self.timer );
		self.end = Date.now();
		self.res.body = body;
		delete cache[ self.rid ];
		delete self.req.opts[ 'agent' ];
		next();
	}
}
10168
function exec(scope, req, res) {
  var replies = [], item;

  // NOTE: incrby invalid amount will trigger EXECABORT
  // NOTE: wrong number of args are returned to the client
  // NOTE: but other types of validation errors (argument type coercion)
  // NOTE: trigger EXECABORT

  if(this.error) return this.destroy(req, res, ExecAbort);
  if(this.conflict) return this.destroy(req, res, null, null);

  function onReply(err, reply) {
    replies.push(err || reply);
  }

  onReply = onReply.bind(this);

  // fifo queue, maintain order
  while((item = this.queue.shift()) !== undefined) {
    if(item.err) {
      replies.push(item.err);
    }else{
      item.res.cb = onReply;

      // execute via the server so that these command
      // executions are included in slowlog/monitor
      scope.execute(item.req.exec, item.req, item.res);
    }
  }

  // reply and destroy this transaction
  this.destroy(req, res, null, replies);
}
58550
function send () {
      sent = true;
      // next tick it to avoid express catching runtime error in the callback
      //   getting caught by express and triggering app's error handler
      process.nextTick(function () {
        res.emit('finish');
        cb(null, res, body);
      });
    }
884006
function Router(req, res, next) {
        const server = this;
        const state = {
            method: req.method.toUpperCase(),
            params: {},
            routes: routes.concat(),
            routeUnhandled: true,
            server: server,
        };
        run(state, req, res, err => {
            req.params = {};
            if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
            next(err);
        });
    }
612222
function handler(req, res, next) {
  var userAgent = req.headers["user-agent"];

  //-- set device
  req.device = new Device(userAgent);

  return next();
}
257932
function router(rpc, handlers, req, res) {
  var $       = rpc.$;
  var api     = rpc.api;
  var request = api.handle(req.method, req.url);
  var dom     = domain.create();

  // the request handler doesn't exit
  // TODO: hoist response logic
  if (!request) {
    res.statusCode = 404;
    res.end();
    return;
  }

  var context = new Context(); // TODO: hoist to own module
  var handle  = request.handle;
  var params  = {};

  // TODO: hoist logic to 'union' module
  var key;
  for(key in request.params) params[key] = request.params[key];
  for(key in request.query)  params[key] = request.query[key];

  var future = $.future();

  future.setWritable(res);
  future.setReadable(req);

  // TODO: extract request making logic
  res.setHeader('Transfer-Encoding' , 'chunked');
  res.setHeader('Content-Type'      , 'application/json');

  dom.on('error', function (err) {
    var statusCode = err.statusCode;

    // only catch known errors, re-throw unexpected errors
    if (!statusCode) throw err;

    // TODO: hoist response logic
    res.statusCode = statusCode;
    res.write(JSON.stringify(err));
    res.end();
  });

  // domain should handle all route errors
  dom.run(function () {
    handlers[handle](future, params, context);
  });
}
906222
function markerHandler(req, res, next) {
  const start = Date.now();
  const { params } = req;

  return Promise.try(() => {
    if (params.color.length !== 3 && params.color.length !== 6) {
      throw new Err('Bad color').metrics('err.marker.color');
    }
    let isRetina;
    if (params.scale === undefined) {
      isRetina = false;
    } else if (params.scale === '2') {
      isRetina = true;
    } else {
      throw new Err('Only retina @2x scaling is allowed for marks').metrics('err.marker.scale');
    }

    return makizushi({
      base: params.base, // "pin"
      size: params.size, // s|m|l
      symbol: params.symbol, // undefined, digit, letter, or maki symol name - https://www.mapbox.com/maki/
      tint: params.color, // in hex - "abc" or "aabbcc"
      retina: isRetina, // true|false
    });
  }).then((data) => {
    core.setResponseHeaders(res);
    res.type('png').send(data);
    core.metrics.endTiming('marker', start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
1103202
function catchClientError(req, res, next) {
  const { end } = res;

  res.end = function() {
    // console.log(`Catch client response : ${req.url} ${res.statusCode}`);
    const errorRoute = Route
      .routes('err')
      .filter((obj) => {
        return obj.extra.status === res.statusCode && obj.route !== req.url;
      });

    if(errorRoute.length > 0 && !isRedirect) {
      return redirect(errorRoute[0], req, res, next);
    }

    isRedirect = false;
    end.apply(res, arguments);
  };

  next();
}