Skip to content

CLI for parse-live-query-server #2765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bin/parse-live-query-server
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

require("../lib/cli/parse-live-query-server");
15 changes: 13 additions & 2 deletions src/LiveQuery/ParseLiveQueryServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,13 @@ class ParseLiveQueryServer {
// to the subscribers and the handler will be called.
this.subscriber.on('message', (channel, messageStr) => {
logger.verbose('Subscribe messsage %j', messageStr);
let message = JSON.parse(messageStr);
let message;
try {
message = JSON.parse(messageStr);
} catch(e) {
logger.error('unable to parse message', messageStr, e);
return;
}
this._inflateParseObject(message);
if (channel === 'afterSave') {
this._onAfterSave(message);
Expand Down Expand Up @@ -229,7 +235,12 @@ class ParseLiveQueryServer {
_onConnect(parseWebsocket: any): void {
parseWebsocket.on('message', (request) => {
if (typeof request === 'string') {
request = JSON.parse(request);
try {
request = JSON.parse(request);
} catch(e) {
logger.error('unable to parse request', request, e);
return;
}
}
logger.verbose('Request: %j', request);

Expand Down
48 changes: 48 additions & 0 deletions src/cli/definitions/parse-live-query-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {
numberParser,
numberOrBoolParser,
objectParser,
arrayParser,
moduleOrObjectParser,
booleanParser,
nullParser
} from '../utils/parsers';


export default {
"appId": {
required: true,
help: "Required. This string should match the appId in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same appId."
},
"masterKey": {
required: true,
help: "Required. This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey."
},
"serverURL": {
required: true,
help: "Required. This string should match the serverURL in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same serverURL."
},
"redisURL": {
help: "Optional. This string should match the masterKey in use by your Parse Server. If you deploy the LiveQuery server alongside Parse Server, the LiveQuery server will try to use the same masterKey."
},
"keyPairs": {
help: "Optional. A JSON object that serves as a whitelist of keys. It is used for validating clients when they try to connect to the LiveQuery server. Check the following Security section and our protocol specification for details."
},
"websocketTimeout": {
help: "Optional. Number of milliseconds between ping/pong frames. The WebSocket server sends ping/pong frames to the clients to keep the WebSocket alive. This value defines the interval of the ping/pong frame from the server to clients. Defaults to 10 * 1000 ms (10 s).",
action: numberParser("websocketTimeout")
},
"cacheTimeout": {
help: "Optional. Number in milliseconds. When clients provide the sessionToken to the LiveQuery server, the LiveQuery server will try to fetch its ParseUser's objectId from parse server and store it in the cache. The value defines the duration of the cache. Check the following Security section and our protocol specification for details. Defaults to 30 * 24 * 60 * 60 * 1000 ms (~30 days).",
action: numberParser("cacheTimeout")
},
"logLevel": {
help: "Optional. This string defines the log level of the LiveQuery server. We support VERBOSE, INFO, ERROR, NONE. Defaults to INFO.",
},
"port": {
env: "PORT",
help: "The port to run the ParseServer. defaults to 1337.",
default: 1337,
action: numberParser("port")
},
};
82 changes: 30 additions & 52 deletions src/cli/cli-definitions.js → src/cli/definitions/parse-server.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,13 @@
function numberParser(key) {
return function(opt) {
opt = parseInt(opt);
if (!Number.isInteger(opt)) {
throw new Error(`The ${key} is invalid`);
}
return opt;
}
}
import {
numberParser,
numberOrBoolParser,
objectParser,
arrayParser,
moduleOrObjectParser,
booleanParser,
nullParser
} from '../utils/parsers';

function numberOrBoolParser(key) {
return function(opt) {
if (typeof opt === 'boolean') {
return opt;
}
return numberParser(key)(opt);
}
}

function objectParser(opt) {
if (typeof opt == 'object') {
return opt;
}
return JSON.parse(opt)
}

function moduleOrObjectParser(opt) {
if (typeof opt == 'object') {
return opt;
}
try {
return JSON.parse(opt);
} catch(e) {}
return opt;
}

function booleanParser(opt) {
if (opt == true || opt == "true" || opt == "1") {
return true;
}
return false;
}

function nullParser(opt) {
if (opt == 'null') {
return null;
}
return opt;
}

export default {
"appId": {
Expand Down Expand Up @@ -128,9 +89,7 @@ export default {
env: "PARSE_SERVER_FACEBOOK_APP_IDS",
help: "Comma separated list for your facebook app Ids",
type: "list",
action: function(opt) {
return opt.split(",")
}
action: arrayParser
},
"enableAnonymousUsers": {
env: "PARSE_SERVER_ENABLE_ANON_USERS",
Expand Down Expand Up @@ -239,5 +198,24 @@ export default {
"cluster": {
help: "Run with cluster, optionally set the number of processes default to os.cpus().length",
action: numberOrBoolParser("cluster")
}
},
"liveQuery.classNames": {
help: "parse-server's LiveQuery configuration object",
action: objectParser
},
"liveQuery.classNames": {
help: "parse-server's LiveQuery classNames",
action: arrayParser
},
"liveQuery.redisURL": {
help: "parse-server's LiveQuery redisURL",
},
"startLiveQueryServer": {
help: "Starts the liveQuery server",
action: booleanParser
},
"liveQueryServerOptions": {
help: "Live query server configuration options (will start the liveQuery server)",
action: objectParser
},
};
15 changes: 15 additions & 0 deletions src/cli/parse-live-query-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import definitions from './definitions/parse-live-query-server';
import runner from './utils/runner';
import { ParseServer } from '../index';
import express from 'express';

runner({
definitions,
start: function(program, options, logOptions) {
logOptions();
var app = express();
var httpServer = require('http').createServer(app);
httpServer.listen(options.port);
ParseServer.createLiveQueryServer(httpServer, options);
}
})
118 changes: 60 additions & 58 deletions src/cli/parse-server.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import path from 'path';
import express from 'express';
import { ParseServer } from '../index';
import definitions from './cli-definitions';
import program from './utils/commander';
import { mergeWithOptions } from './utils/commander';
import definitions from './definitions/parse-server';
import cluster from 'cluster';
import os from 'os';
import runner from './utils/runner';

program.loadDefinitions(definitions);

program
.usage('[options] <path/to/configuration.json>');

program.on('--help', function(){
const help = function(){
console.log(' Get Started guide:');
console.log('');
console.log(' Please have a look at the get started guide!')
Expand All @@ -32,41 +26,17 @@ program.on('--help', function(){
console.log(' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL');
console.log(' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL');
console.log('');
});

program.parse(process.argv, process.env);

let options = program.getOptions();

if (!options.serverURL) {
options.serverURL = `http://localhost:${options.port}${options.mountPath}`;
}

if (!options.appId || !options.masterKey || !options.serverURL) {
program.outputHelp();
console.error("");
console.error('\u001b[31mERROR: appId and masterKey are required\u001b[0m');
console.error("");
process.exit(1);
}

function logStartupOptions(options) {
for (let key in options) {
let value = options[key];
if (key == "masterKey") {
value = "***REDACTED***";
}
console.log(`${key}: ${value}`);
}
}
};

function startServer(options, callback) {
const app = express();
const api = new ParseServer(options);
app.use(options.mountPath, api);

var server = app.listen(options.port, callback);

if (options.startLiveQueryServer || options.liveQueryServerOptions) {
ParseServer.createLiveQueryServer(server, options.liveQueryServerOptions);
}
var handleShutdown = function() {
console.log('Termination signal received. Shutting down.');
server.close(function () {
Expand All @@ -77,27 +47,59 @@ function startServer(options, callback) {
process.on('SIGINT', handleShutdown);
}

if (options.cluster) {
const numCPUs = typeof options.cluster === 'number' ? options.cluster : os.cpus().length;
if (cluster.isMaster) {
logStartupOptions(options);
for(var i = 0; i < numCPUs; i++) {
cluster.fork();

runner({
definitions,
help,
usage: '[options] <path/to/configuration.json>',
start: function(program, options, logOptions) {
if (!options.serverURL) {
options.serverURL = `http://localhost:${options.port}${options.mountPath}`;
}

if (!options.appId || !options.masterKey || !options.serverURL) {
program.outputHelp();
console.error("");
console.error('\u001b[31mERROR: appId and masterKey are required\u001b[0m');
console.error("");
process.exit(1);
}

if (options["liveQuery.classNames"]) {
options.liveQuery = options.liveQuery || {};
options.liveQuery.classNames = options["liveQuery.classNames"];
delete options["liveQuery.classNames"];
}
if (options["liveQuery.redisURL"]) {
options.liveQuery = options.liveQuery || {};
options.liveQuery.redisURL = options["liveQuery.redisURL"];
delete options["liveQuery.redisURL"];
}

if (options.cluster) {
const numCPUs = typeof options.cluster === 'number' ? options.cluster : os.cpus().length;
if (cluster.isMaster) {
for(var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died... Restarting`);
cluster.fork();
});
} else {
startServer(options, () => {
console.log('['+process.pid+'] parse-server running on '+options.serverURL);
});
}
} else {
startServer(options, () => {
logOptions();
console.log('');
console.log('['+process.pid+'] parse-server running on '+options.serverURL);
});
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died... Restarting`);
cluster.fork();
});
} else {
startServer(options, () => {
console.log('['+process.pid+'] parse-server running on '+options.serverURL);
});
}
} else {
startServer(options, () => {
logStartupOptions(options);
console.log('');
console.log('['+process.pid+'] parse-server running on '+options.serverURL);
});
}
})



Loading