-
Notifications
You must be signed in to change notification settings - Fork 63
/
gremlinclient.js
307 lines (256 loc) · 7.92 KB
/
gremlinclient.js
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*jslint -W079 */
/*jslint node: true */
import { EventEmitter } from 'events';
import WebSocket from 'ws';
import uuid from 'node-uuid';
import _ from 'lodash';
import highland from 'highland';
import MessageStream from './messagestream';
import executeHandler from './executehandler';
import * as Utils from './utils';
class GremlinClient extends EventEmitter {
constructor(port = 8182, host = 'localhost', options) {
super();
this.port = port;
this.host = host;
this.options = {
language: 'gremlin-groovy',
session: false,
op: 'eval',
processor: '',
accept: 'application/json',
executeHandler,
...options
}
this.useSession = this.options.session;
if (this.useSession) {
this.sessionId = uuid.v1();
}
this.connected = false;
this.queue = [];
this.commands = {};
// Open websocket connection
this.ws = new WebSocket('ws://'+ this.host +':'+ this.port);
this.ws.onopen = this.onConnectionOpen.bind(this);
this.ws.onerror = (err) => {
this.handleError(err)
};
this.ws.onmessage = (message) => this.handleProtocolMessage(message);
this.ws.onclose = (event) => this.handleDisconnection(event);
}
handleError(err) {
this.connected = false,
this.emit('error', err);
}
/**
* Process all incoming raw message events sent by Gremlin Server, and dispatch
* to the appropriate command.
*
* @param {MessageEvent} event
*/
handleProtocolMessage(message) {
const rawMessage = JSON.parse(message.data || message); // Node.js || Browser API
const {
requestId,
status: {
code: statusCode,
message: statusMessage
}
} = rawMessage;
const { messageStream } = this.commands[requestId];
switch (statusCode) {
case 200: // SUCCESS
delete this.commands[requestId]; // TODO: optimize performance
messageStream.push(rawMessage);
messageStream.push(null);
break;
case 204: // NO_CONTENT
messageStream.push(null);
break;
case 206: // PARTIAL_CONTENT
messageStream.push(rawMessage);
break;
default:
messageStream.emit('error', new Error(statusMessage + ' (Error '+ statusCode +')'));
break;
}
}
/**
* Handle the WebSocket onOpen event, flag the client as connected and
* process command queue.
*/
onConnectionOpen() {
this.connected = true;
this.emit('connect');
this.executeQueue();
};
/**
* @param {CloseEvent} event
*/
handleDisconnection(event) {
this.cancelPendingCommands({
message: 'WebSocket closed',
details: event
});
};
/**
* Process the current command queue, sending commands to Gremlin Server
* (First In, First Out).
*/
executeQueue() {
while (this.queue.length > 0) {
let { message } = this.queue.shift();
this.sendMessage(message);
}
};
/**
* @param {Object} reason
*/
cancelPendingCommands({ message, details }) {
const commands = this.commands;
let command;
const error = new Error(message);
error.details = details;
// Empty queue
this.queue.length = 0;
this.commands = {};
Object.keys(commands).forEach((key) => {
command = commands[key];
command.messageStream.emit('error', error);
});
};
/**
* For a given script string and optional bound parameters, build a protocol
* message object to be sent to Gremlin Server.
*
* @param {String|Function} script
* @param {Object} bindings
* @param {Object} message
*/
buildMessage(script, rawBindings = {}, baseMessage = {}) {
const gremlin = (typeof script === 'function') ? Utils.extractFunctionBody(script) : script;
const { processor, op, accept, language } = this.options;
// Remap 'undefined' bindings as 'null' values that would otherwise result
// in missing/unbound variables in the Gremlin script execution context.
const bindings = _.mapValues(rawBindings, (value) => _.isUndefined(value) ? null : value);
const baseArgs = { gremlin, bindings, accept, language };
const args = _.defaults(baseMessage.args || {}, baseArgs);
const message = {
requestId: uuid.v1(),
processor,
op,
args,
...baseMessage
};
if (this.useSession) {
// Assume that people want to use the 'session' processor unless specified
message.processor = message.processor || processor || 'session';
message.args.session = this.sessionId;
}
return message;
};
sendMessage(message) {
this.ws.send(JSON.stringify(message));
};
/**
* Asynchronously send a script to Gremlin Server for execution and fire
* the provided callback when all results have been fetched.
*
* This method internally uses a stream to handle the potential concatenation
* of results.
*
* Callback signature: (Error, Array<result>)
*
* @public
* @param {String|Function} script
* @param {Object} bindings
* @param {Object} message
* @param {Function} callback
*/
execute(script, bindings = {}, message = {}, ...args) {
let callback = args[args.length - 1];
if (typeof message === 'function') {
callback = message;
message = {};
}
const messageStream = this.messageStream(script, bindings, message);
// TO CHECK: errors handling could be improved
// See https://groups.google.com/d/msg/nodejs/lJYT9hZxFu0/L59CFbqWGyYJ
// for an example using domains
const { executeHandler } = this.options;
executeHandler(messageStream, callback);
};
/**
* Execute the script and return a stream of distinct/single results.
* This method reemits a distinct data event for each returned result, which
* makes the stream behave as if `resultIterationBatchSize` was set to 1.
*
* If you do not wish this behavior, please use client.messageStream() instead.
*
* Even though this method uses Highland.js internally, it does not return
* a high level Highland readable stream so we do not risk having to deal
* with unexpected API breaking changes as Highland.js evolves.
*
* @return {ReadableStream} A Node.js Stream2
*/
stream(script, bindings, message) {
const messageStream = this.messageStream(script, bindings, message);
const _ = highland; // override lo-dash locally
// Create a local highland 'through' pipeline so we don't expose
// a Highland stream to the end user, but a standard Node.js Stream2
const through = _.pipeline(
_.map(({ result: { data }}) => data),
_.sequence()
);
let rawStream = messageStream.pipe(through);
messageStream.on('error', (e) => {
rawStream.emit('error', new Error(e));
});
return rawStream;
};
/**
* Execute the script and return a stream of raw messages returned by Gremlin
* Server.
* This method does not reemit one distinct data event per result. It directly
* emits the raw messages returned by Gremlin Server as they are received.
*
* Although public, this is a low level method intended to be used for
* advanced usages.
*
* @public
* @param {String|Function} script
* @param {Object} bindings
* @param {Object} message
* @return {MessageStream}
*/
messageStream(script, bindings, rawMessage) {
let stream = new MessageStream({ objectMode: true });
const command = {
message: this.buildMessage(script, bindings, rawMessage),
messageStream: stream
};
this.sendCommand(command); //todo improve for streams
return stream;
};
/**
* Send a command to Gremlin Server, or add it to queue if the connection
* is not established.
*
* @param {Object} command
*/
sendCommand(command) {
const {
message,
message: {
requestId
}
} = command;
this.commands[requestId] = command;
if (this.connected) {
this.sendMessage(message);
} else {
this.queue.push(command);
}
};
}
export default GremlinClient;