CartoDB-SQL-API/app/server.js

212 lines
6.9 KiB
JavaScript
Raw Normal View History

2018-10-24 21:42:33 +08:00
'use strict';
// CartoDB SQL API
//
// all requests expect the following URL args:
// - `sql` {String} SQL to execute
//
// for private (read/write) queries:
// - OAuth. Must have proper OAuth 1.1 headers. For OAuth 1.1 spec see Google
//
// eg. /api/v1/?sql=SELECT 1 as one (with a load of OAuth headers or URL arguments)
//
// for public (read only) queries:
// - sql only, provided the subdomain exists in CartoDB and the table's sharing options are public
//
// eg. vizzuality.cartodb.com/api/v1/?sql=SELECT * from my_table
2012-07-24 16:29:47 +08:00
//
var express = require('express');
2016-10-04 20:40:04 +08:00
var Profiler = require('./stats/profiler-proxy');
var _ = require('underscore');
2018-08-30 18:27:34 +08:00
var fs = require('fs');
var mkdirp = require('mkdirp');
var TableCacheFactory = require('./utils/table_cache_factory');
var RedisPool = require('redis-mpool');
2016-10-17 21:02:34 +08:00
var cartodbRedis = require('cartodb-redis');
var UserDatabaseService = require('./services/user_database_service');
2018-03-01 18:31:35 +08:00
var UserLimitsService = require('./services/user_limits');
2016-10-12 00:28:46 +08:00
var JobPublisher = require('../batch/pubsub/job-publisher');
var JobQueue = require('../batch/job_queue');
var JobBackend = require('../batch/job_backend');
var JobCanceller = require('../batch/job_canceller');
2016-05-16 07:22:47 +08:00
var JobService = require('../batch/job_service');
const Logger = require('./services/logger');
2016-05-16 07:22:47 +08:00
var cors = require('./middlewares/cors');
var GenericController = require('./controllers/generic_controller');
var QueryController = require('./controllers/query_controller');
var CopyController = require('./controllers/copy_controller');
var JobController = require('./controllers/job_controller');
var CacheStatusController = require('./controllers/cache_status_controller');
var HealthCheckController = require('./controllers/health_check_controller');
var VersionController = require('./controllers/version_controller');
var batchFactory = require('../batch');
process.env.PGAPPNAME = process.env.PGAPPNAME || 'cartodb_sqlapi';
2015-12-04 01:25:35 +08:00
// override Date.toJSON
2015-12-04 01:33:17 +08:00
require('./utils/date_to_json');
2017-03-30 22:13:17 +08:00
// jshint maxcomplexity:9
function App(statsClient) {
var app = express();
2016-10-17 21:02:34 +08:00
var redisPool = new RedisPool({
name: 'sql-api',
host: global.settings.redis_host,
port: global.settings.redis_port,
max: global.settings.redisPool,
idleTimeoutMillis: global.settings.redisIdleTimeoutMillis,
reapIntervalMillis: global.settings.redisReapIntervalMillis
2016-10-17 21:02:34 +08:00
});
var metadataBackend = cartodbRedis({ pool: redisPool });
// Set default configuration
global.settings.db_pubuser = global.settings.db_pubuser || "publicuser";
global.settings.bufferedRows = global.settings.bufferedRows || 1000;
global.settings.ratelimits = Object.assign(
{
rateLimitsEnabled: false,
endpoints: {
query: false,
job_create: false,
job_get: false,
job_delete: false
}
2018-08-30 18:27:34 +08:00
},
global.settings.ratelimits
);
2018-08-30 18:27:34 +08:00
global.settings.tmpDir = global.settings.tmpDir || '/tmp';
if (!fs.existsSync(global.settings.tmpDir)) {
mkdirp.sync(global.settings.tmpDir);
}
var tableCache = new TableCacheFactory().build(global.settings);
2014-03-13 18:52:40 +08:00
if ( global.log4js ) {
var loggerOpts = {
buffer: true,
// log4js provides a tokens solution as expess but in does not provide the request/response in the callback.
// Thus it is not possible to extract relevant information from them.
// This is a workaround to be able to access request/response.
format: function(req, res, format) {
var logFormat = global.settings.log_format ||
':remote-addr :method :req[Host]:url :status :response-time ms -> :res[Content-Type]';
return format(logFormat);
2014-03-20 18:22:13 +08:00
}
};
app.use(global.log4js.connectLogger(global.log4js.getLogger(), _.defaults(loggerOpts, {level:'info'})));
}
2014-03-20 01:34:21 +08:00
app.use(cors());
// Use step-profiler
2016-10-04 21:12:46 +08:00
app.use(function bootstrap$prepareRequestResponse(req, res, next) {
res.locals = res.locals || {};
2016-10-04 21:12:46 +08:00
if (global.settings.api_hostname) {
res.header('X-Served-By-Host', global.settings.api_hostname);
}
2016-10-04 20:40:04 +08:00
var profile = global.settings.useProfiler;
req.profiler = new Profiler({
profile: profile,
2017-03-30 22:13:17 +08:00
statsd_client: statsClient
2016-10-04 20:40:04 +08:00
});
next();
2016-10-04 20:40:04 +08:00
});
2012-04-21 02:34:18 +08:00
// Set connection timeout
if ( global.settings.hasOwnProperty('node_socket_timeout') ) {
var timeout = parseInt(global.settings.node_socket_timeout);
app.use(function(req, res, next) {
req.connection.setTimeout(timeout);
next();
});
}
app.enable('jsonp callback');
app.set("trust proxy", true);
app.disable('x-powered-by');
app.disable('etag');
// basic routing
var userDatabaseService = new UserDatabaseService(metadataBackend);
2018-08-30 18:27:34 +08:00
2018-03-01 18:31:35 +08:00
const userLimitsServiceOptions = {
limits: {
rateLimitsEnabled: global.settings.ratelimits.rateLimitsEnabled
}
};
const userLimitsService = new UserLimitsService(metadataBackend, userLimitsServiceOptions);
const dataIngestionLogger = new Logger(global.settings.dataIngestionLogPath, 'data-ingestion');
app.dataIngestionLogger = dataIngestionLogger;
2016-10-17 21:02:34 +08:00
var jobPublisher = new JobPublisher(redisPool);
var jobQueue = new JobQueue(metadataBackend, jobPublisher);
2016-08-31 01:04:21 +08:00
var jobBackend = new JobBackend(metadataBackend, jobQueue);
var jobCanceller = new JobCanceller();
2016-05-16 07:22:47 +08:00
var jobService = new JobService(jobBackend, jobCanceller);
var genericController = new GenericController();
2015-12-04 01:43:13 +08:00
genericController.route(app);
2018-03-01 21:47:34 +08:00
var queryController = new QueryController(
2018-08-30 18:27:34 +08:00
metadataBackend,
userDatabaseService,
tableCache,
statsClient,
2018-03-01 21:47:34 +08:00
userLimitsService
);
2015-12-04 01:43:13 +08:00
queryController.route(app);
var copyController = new CopyController(
2018-08-30 18:27:34 +08:00
metadataBackend,
userDatabaseService,
userLimitsService,
dataIngestionLogger
);
copyController.route(app);
2018-08-30 18:27:34 +08:00
2018-03-01 21:47:34 +08:00
var jobController = new JobController(
2018-08-30 18:27:34 +08:00
metadataBackend,
userDatabaseService,
jobService,
statsClient,
2018-03-01 21:47:34 +08:00
userLimitsService
);
jobController.route(app);
var cacheStatusController = new CacheStatusController(tableCache);
2015-12-04 01:43:13 +08:00
cacheStatusController.route(app);
var healthCheckController = new HealthCheckController();
2015-12-04 01:43:13 +08:00
healthCheckController.route(app);
var versionController = new VersionController();
2015-12-04 01:43:13 +08:00
versionController.route(app);
var isBatchProcess = process.argv.indexOf('--no-batch') === -1;
if (global.settings.environment !== 'test' && isBatchProcess) {
var batchName = global.settings.api_hostname || 'batch';
app.batch = batchFactory(
2017-03-30 22:13:17 +08:00
metadataBackend, redisPool, batchName, statsClient, global.settings.batch_log_filename
);
app.batch.start();
}
return app;
}
module.exports = App;