UNPKG

257 kBJavaScriptView Raw
1module.exports =
2/******/ (function(modules) { // webpackBootstrap
3/******/ // The module cache
4/******/ var installedModules = {};
5/******/
6/******/ // The require function
7/******/ function __webpack_require__(moduleId) {
8/******/
9/******/ // Check if module is in cache
10/******/ if(installedModules[moduleId]) {
11/******/ return installedModules[moduleId].exports;
12/******/ }
13/******/ // Create a new module (and put it into the cache)
14/******/ var module = installedModules[moduleId] = {
15/******/ i: moduleId,
16/******/ l: false,
17/******/ exports: {}
18/******/ };
19/******/
20/******/ // Execute the module function
21/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22/******/
23/******/ // Flag the module as loaded
24/******/ module.l = true;
25/******/
26/******/ // Return the exports of the module
27/******/ return module.exports;
28/******/ }
29/******/
30/******/
31/******/ // expose the modules object (__webpack_modules__)
32/******/ __webpack_require__.m = modules;
33/******/
34/******/ // expose the module cache
35/******/ __webpack_require__.c = installedModules;
36/******/
37/******/ // define getter function for harmony exports
38/******/ __webpack_require__.d = function(exports, name, getter) {
39/******/ if(!__webpack_require__.o(exports, name)) {
40/******/ Object.defineProperty(exports, name, {
41/******/ configurable: false,
42/******/ enumerable: true,
43/******/ get: getter
44/******/ });
45/******/ }
46/******/ };
47/******/
48/******/ // getDefaultExport function for compatibility with non-harmony modules
49/******/ __webpack_require__.n = function(module) {
50/******/ var getter = module && module.__esModule ?
51/******/ function getDefault() { return module['default']; } :
52/******/ function getModuleExports() { return module; };
53/******/ __webpack_require__.d(getter, 'a', getter);
54/******/ return getter;
55/******/ };
56/******/
57/******/ // Object.prototype.hasOwnProperty.call
58/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
59/******/
60/******/ // __webpack_public_path__
61/******/ __webpack_require__.p = "";
62/******/
63/******/ // Load entry module and return exports
64/******/ return __webpack_require__(__webpack_require__.s = 36);
65/******/ })
66/************************************************************************/
67/******/ ([
68/* 0 */
69/***/ (function(module, exports) {
70
71module.exports = require("util");
72
73/***/ }),
74/* 1 */
75/***/ (function(module, exports) {
76
77const TcpCommand = Object.freeze({
78 HeartbeatRequestCommand: 0x01,
79 HeartbeatResponseCommand: 0x02,
80
81 Ping: 0x03,
82 Pong: 0x04,
83
84 PrepareAck: 0x05,
85 CommitAck: 0x06,
86
87 SlaveAssignment: 0x07,
88 CloneAssignment: 0x08,
89
90 SubscribeReplica: 0x10,
91 ReplicaLogPositionAck: 0x11,
92 CreateChunk: 0x12,
93 RawChunkBulk: 0x13,
94 DataChunkBulk: 0x14,
95 ReplicaSubscriptionRetry: 0x15,
96 ReplicaSubscribed: 0x16,
97
98 // CLIENT COMMANDS
99 // CreateStream: 0x80,
100 // CreateStreamCompleted: 0x81,
101
102 WriteEvents: 0x82,
103 WriteEventsCompleted: 0x83,
104
105 TransactionStart: 0x84,
106 TransactionStartCompleted: 0x85,
107 TransactionWrite: 0x86,
108 TransactionWriteCompleted: 0x87,
109 TransactionCommit: 0x88,
110 TransactionCommitCompleted: 0x89,
111
112 DeleteStream: 0x8A,
113 DeleteStreamCompleted: 0x8B,
114
115 ReadEvent: 0xB0,
116 ReadEventCompleted: 0xB1,
117 ReadStreamEventsForward: 0xB2,
118 ReadStreamEventsForwardCompleted: 0xB3,
119 ReadStreamEventsBackward: 0xB4,
120 ReadStreamEventsBackwardCompleted: 0xB5,
121 ReadAllEventsForward: 0xB6,
122 ReadAllEventsForwardCompleted: 0xB7,
123 ReadAllEventsBackward: 0xB8,
124 ReadAllEventsBackwardCompleted: 0xB9,
125
126 SubscribeToStream: 0xC0,
127 SubscriptionConfirmation: 0xC1,
128 StreamEventAppeared: 0xC2,
129 UnsubscribeFromStream: 0xC3,
130 SubscriptionDropped: 0xC4,
131 ConnectToPersistentSubscription: 0xC5,
132 PersistentSubscriptionConfirmation: 0xC6,
133 PersistentSubscriptionStreamEventAppeared: 0xC7,
134 CreatePersistentSubscription: 0xC8,
135 CreatePersistentSubscriptionCompleted: 0xC9,
136 DeletePersistentSubscription: 0xCA,
137 DeletePersistentSubscriptionCompleted: 0xCB,
138 PersistentSubscriptionAckEvents: 0xCC,
139 PersistentSubscriptionNakEvents: 0xCD,
140 UpdatePersistentSubscription: 0xCE,
141 UpdatePersistentSubscriptionCompleted: 0xCF,
142
143 ScavengeDatabase: 0xD0,
144 ScavengeDatabaseCompleted: 0xD1,
145
146 BadRequest: 0xF0,
147 NotHandled: 0xF1,
148 Authenticate: 0xF2,
149 Authenticated: 0xF3,
150 NotAuthenticated: 0xF4,
151 IdentifyClient: 0xF5,
152 ClientIdentified: 0xF6,
153
154 getName: function(v) {
155 return _reverseLookup[v];
156 }
157});
158
159var _reverseLookup = {};
160for(var n in TcpCommand) {
161 if (n === 'getName') continue;
162 var v = TcpCommand[n];
163 _reverseLookup[v] = n;
164}
165
166module.exports = TcpCommand;
167
168/***/ }),
169/* 2 */
170/***/ (function(module, exports) {
171
172module.exports = require("../src/messages/clientMessage");
173
174/***/ }),
175/* 3 */
176/***/ (function(module, exports, __webpack_require__) {
177
178var guidParse = __webpack_require__(13);
179var Long = __webpack_require__(9);
180var ensure = __webpack_require__(8);
181
182/**
183 * @public
184 * @param {!number|!Long} commitPosition
185 * @param {!number|!Long} preparePosition
186 * @constructor
187 * @property {!Long} commitPosition
188 * @property {!Long} preparePosition
189 */
190function Position(commitPosition, preparePosition) {
191 ensure.notNull(commitPosition, "commitPosition");
192 ensure.notNull(preparePosition, "preparePosition");
193 this.commitPosition = Long.fromValue(commitPosition);
194 this.preparePosition = Long.fromValue(preparePosition);
195 Object.freeze(this);
196}
197
198Position.prototype.compareTo = function(other) {
199 if (this.commitPosition.lt(other.commitPosition) || (this.commitPosition.eq(other.commitPosition)&& this.preparePosition.lt(other.preparePosition))) {
200 return -1;
201 }
202 if (this.commitPosition.gt(other.commitPosition) || (this.commitPosition.eq(other.commitPosition) && this.preparePosition.gt(other.preparePosition))) {
203 return 1;
204 }
205 return 0;
206};
207
208Position.prototype.toString = function() {
209 return [this.commitPosition.toString(), this.preparePosition.toString()].join("/");
210};
211
212Position.start = new Position(0,0);
213Position.end = new Position(-1,-1);
214
215const EventReadStatus = Object.freeze({
216 Success: 'success',
217 NotFound: 'notFound',
218 NoStream: 'noStream',
219 StreamDeleted: 'streamDeleted'
220});
221
222/**
223 * @param {object} ev
224 * @constructor
225 * @property {string} eventStreamId
226 * @property {string} eventId
227 * @property {Long} eventNumber
228 * @property {string} eventType
229 * @property {number} createdEpoch
230 * @property {?Buffer} data
231 * @property {?Buffer} metadata
232 * @property {boolean} isJson
233 */
234function RecordedEvent(ev) {
235 this.eventStreamId = ev.eventStreamId;
236 this.eventId = guidParse.unparse(ev.eventId);
237 this.eventNumber = ev.eventNumber;
238 this.eventType = ev.eventType;
239 this.created = new Date(ev.createdEpoch ? ev.createdEpoch.toNumber() : 0);
240 this.createdEpoch = ev.createdEpoch ? ev.createdEpoch.toNumber() : 0;
241 this.data = ev.data ? ev.data : new Buffer(0);
242 this.metadata = ev.metadata ? ev.metadata : new Buffer(0);
243 this.isJson = ev.dataContentType === 1;
244 Object.freeze(this);
245}
246
247/**
248 * @param {object} ev
249 * @constructor
250 * @property {?RecordedEvent} event
251 * @property {?RecordedEvent} link
252 * @property {?RecordedEvent} originalEvent
253 * @property {boolean} isResolved
254 * @property {?Position} originalPosition
255 * @property {string} originalStreamId
256 * @property {Long} originalEventNumber
257 */
258function ResolvedEvent(ev) {
259 this.event = ev.event === null ? null : new RecordedEvent(ev.event);
260 this.link = ev.link === null ? null : new RecordedEvent(ev.link);
261 this.originalEvent = this.link || this.event;
262 this.isResolved = this.link !== null && this.event !== null;
263 this.originalPosition = (ev.commitPosition && ev.preparePosition) ? new Position(ev.commitPosition, ev.preparePosition) : null;
264 this.originalStreamId = this.originalEvent && this.originalEvent.eventStreamId;
265 this.originalEventNumber = this.originalEvent && this.originalEvent.eventNumber;
266 Object.freeze(this);
267}
268
269/**
270 *
271 * @param {string} status
272 * @param {string} stream
273 * @param {Long} eventNumber
274 * @param {object} event
275 * @constructor
276 * @property {string} status
277 * @property {string} stream
278 * @property {Long} eventNumber
279 * @property {ResolvedEvent} event
280 */
281function EventReadResult(status, stream, eventNumber, event) {
282 this.status = status;
283 this.stream = stream;
284 this.eventNumber = eventNumber;
285 this.event = status === EventReadStatus.Success ? new ResolvedEvent(event) : null;
286 Object.freeze(this);
287}
288
289/**
290 * @param {number} nextExpectedVersion
291 * @param {Position} logPosition
292 * @constructor
293 * @property {Long} nextExpectedVersion
294 * @property {Position} logPosition
295 */
296function WriteResult(nextExpectedVersion, logPosition) {
297 this.nextExpectedVersion = nextExpectedVersion;
298 this.logPosition = logPosition;
299 Object.freeze(this);
300}
301
302/**
303 * @param {string} status
304 * @param {string} stream
305 * @param {Long} fromEventNumber
306 * @param {string} readDirection
307 * @param {object[]} events
308 * @param {Long} nextEventNumber
309 * @param {Long} lastEventNumber
310 * @param {boolean} isEndOfStream
311 * @constructor
312 * @property {string} status
313 * @property {string} stream
314 * @property {Long} fromEventNumber
315 * @property {string} readDirection
316 * @property {ResolvedEvent[]} events
317 * @property {Long} nextEventNumber
318 * @property {Long} lastEventNumber
319 * @property {boolean} isEndOfStream
320 */
321function StreamEventsSlice(
322 status, stream, fromEventNumber, readDirection, events, nextEventNumber, lastEventNumber, isEndOfStream
323) {
324 this.status = status;
325 this.stream = stream;
326 this.fromEventNumber = fromEventNumber;
327 this.readDirection = readDirection;
328 this.events = events ? events.map(function(ev) { return new ResolvedEvent(ev); }) : [];
329 this.nextEventNumber = nextEventNumber;
330 this.lastEventNumber = lastEventNumber;
331 this.isEndOfStream = isEndOfStream;
332 Object.freeze(this);
333}
334
335/**
336 * @param {string} readDirection
337 * @param {Position} fromPosition
338 * @param {Position} nextPosition
339 * @param {ResolvedEvent[]} events
340 * @constructor
341 * @property {string} readDirection
342 * @property {Position} fromPosition
343 * @property {Position} nextPosition
344 * @property {ResolvedEvent[]} events
345 */
346function AllEventsSlice(readDirection, fromPosition, nextPosition, events) {
347 this.readDirection = readDirection;
348 this.fromPosition = fromPosition;
349 this.nextPosition = nextPosition;
350 this.events = events ? events.map(function(ev){ return new ResolvedEvent(ev); }) : [];
351 this.isEndOfStream = events === null || events.length === 0;
352 Object.freeze(this);
353}
354
355/**
356 * @param {Position} logPosition
357 * @constructor
358 * @property {Position} logPosition
359 */
360function DeleteResult(logPosition) {
361 this.logPosition = logPosition;
362 Object.freeze(this);
363}
364
365/**
366 * @param {string} stream
367 * @param {boolean} isStreamDeleted
368 * @param {Long} metastreamVersion
369 * @param {object} streamMetadata
370 * @constructor
371 * @property {string} stream
372 * @property {boolean} isStreamDeleted
373 * @property {Long} metastreamVersion
374 * @property {object} streamMetadata
375 */
376function RawStreamMetadataResult(stream, isStreamDeleted, metastreamVersion, streamMetadata) {
377 ensure.notNullOrEmpty(stream);
378 this.stream = stream;
379 this.isStreamDeleted = isStreamDeleted;
380 this.metastreamVersion = metastreamVersion;
381 this.streamMetadata = streamMetadata;
382 Object.freeze(this);
383}
384
385const PersistentSubscriptionCreateStatus = Object.freeze({
386 Success: 'success',
387 NotFound: 'notFound',
388 Failure: 'failure'
389});
390
391/**
392 * @param {string} status
393 * @constructor
394 * @property {string} status
395 */
396function PersistentSubscriptionCreateResult(status) {
397 this.status = status;
398 Object.freeze(this);
399}
400
401const PersistentSubscriptionUpdateStatus = Object.freeze({
402 Success: 'success',
403 NotFound: 'notFound',
404 Failure: 'failure',
405 AccessDenied: 'accessDenied'
406});
407
408/**
409 * @param {string} status
410 * @constructor
411 * @property {string} status
412 */
413function PersistentSubscriptionUpdateResult(status) {
414 this.status = status;
415 Object.freeze(this);
416}
417
418const PersistentSubscriptionDeleteStatus = Object.freeze({
419 Success: 'success',
420 Failure: 'failure'
421});
422
423/**
424 * @param {string} status
425 * @constructor
426 * @property {string} status
427 */
428function PersistentSubscriptionDeleteResult(status) {
429 this.status = status;
430 Object.freeze(this);
431}
432
433// Exports Constructors
434exports.Position = Position;
435exports.ResolvedEvent = ResolvedEvent;
436exports.EventReadStatus = EventReadStatus;
437exports.EventReadResult = EventReadResult;
438exports.WriteResult = WriteResult;
439exports.StreamEventsSlice = StreamEventsSlice;
440exports.AllEventsSlice = AllEventsSlice;
441exports.DeleteResult = DeleteResult;
442exports.RawStreamMetadataResult = RawStreamMetadataResult;
443exports.PersistentSubscriptionCreateResult = PersistentSubscriptionCreateResult;
444exports.PersistentSubscriptionCreateStatus = PersistentSubscriptionCreateStatus;
445exports.PersistentSubscriptionUpdateResult = PersistentSubscriptionUpdateResult;
446exports.PersistentSubscriptionUpdateStatus = PersistentSubscriptionUpdateStatus;
447exports.PersistentSubscriptionDeleteResult = PersistentSubscriptionDeleteResult;
448exports.PersistentSubscriptionDeleteStatus = PersistentSubscriptionDeleteStatus;
449
450/***/ }),
451/* 4 */
452/***/ (function(module, exports) {
453
454var InspectionDecision = Object.freeze({
455 DoNothing: 'doNothing',
456 EndOperation: 'endOperation',
457 Retry: 'retry',
458 Reconnect: 'reconnect',
459 Subscribed: 'subscribed'
460});
461
462module.exports = InspectionDecision;
463
464/***/ }),
465/* 5 */
466/***/ (function(module, exports) {
467
468function InspectionResult(decision, description, tcpEndPoint, secureTcpEndPoint) {
469 this.decision = decision;
470 this.description = description;
471 this.tcpEndPoint = tcpEndPoint || null;
472 this.secureTcpEndPoint = secureTcpEndPoint || null;
473}
474
475module.exports = InspectionResult;
476
477/***/ }),
478/* 6 */
479/***/ (function(module, exports, __webpack_require__) {
480
481var util = __webpack_require__(0);
482
483var TcpPackage = __webpack_require__(11);
484var TcpCommand = __webpack_require__(1);
485var TcpFlags = __webpack_require__(12);
486var InspectionDecision = __webpack_require__(4);
487var ClientMessage = __webpack_require__(2);
488var InspectionResult = __webpack_require__(5);
489var createBufferSegment = __webpack_require__(10);
490
491function OperationBase(log, cb, requestCommand, responseCommand, userCredentials) {
492 this.log = log;
493 this._cb = cb;
494 this._requestCommand = requestCommand;
495 this._responseCommand = responseCommand;
496 this.userCredentials = userCredentials;
497
498 this._completed = false;
499 this._response = null;
500
501 this._responseType = null;
502}
503
504OperationBase.prototype._createRequestDto = function() {
505 throw new Error('_createRequestDto not implemented.');
506};
507
508OperationBase.prototype._inspectResponse = function() {
509 throw new Error('_inspectResponse not implemented.');
510};
511
512OperationBase.prototype._transformResponse = function() {
513 throw new Error('_transformResponse not implemented.');
514};
515
516OperationBase.prototype.fail = function(error) {
517 this._completed = true;
518 this._cb(error);
519};
520
521OperationBase.prototype._succeed = function() {
522 if (!this._completed) {
523 this._completed = true;
524
525 if (this._response) {
526 this._cb(null, this._transformResponse(this._response));
527 } else {
528 this._cb(new Error("No result."))
529 }
530 }
531};
532
533OperationBase.prototype.createNetworkPackage = function(correlationId) {
534 var dto = this._createRequestDto();
535 var buf = dto.constructor.encode(dto).finish();
536 return new TcpPackage(
537 this._requestCommand,
538 this.userCredentials ? TcpFlags.Authenticated : TcpFlags.None,
539 correlationId,
540 this.userCredentials ? this.userCredentials.username : null,
541 this.userCredentials ? this.userCredentials.password : null,
542 createBufferSegment(buf));
543};
544
545OperationBase.prototype.inspectPackage = function(pkg) {
546 try {
547 if (pkg.command === this._responseCommand) {
548 this._response = this._responseType.decode(pkg.data.toBuffer());
549 return this._inspectResponse(this._response);
550 }
551 switch (pkg.command) {
552 case TcpCommand.NotAuthenticated:
553 return this._inspectNotAuthenticated(pkg);
554 case TcpCommand.BadRequest:
555 return this._inspectBadRequest(pkg);
556 case TcpCommand.NotHandled:
557 return this._inspectNotHandled(pkg);
558 default:
559 return this._inspectUnexpectedCommand(pkg, this._responseCommand);
560 }
561 } catch(e) {
562 this.fail(e);
563 return new InspectionResult(InspectionDecision.EndOperation, "Error - " + e.message);
564 }
565};
566
567OperationBase.prototype._inspectNotAuthenticated = function(pkg)
568{
569 var message = '';
570 try {
571 message = pkg.data.toString();
572 } catch(e) {}
573 //TODO typed error
574 this.fail(new Error("Authentication error: " + message));
575 return new InspectionResult(InspectionDecision.EndOperation, "NotAuthenticated");
576};
577
578OperationBase.prototype._inspectBadRequest = function(pkg)
579{
580 var message = '';
581 try {
582 message = pkg.data.toString();
583 } catch(e) {}
584 //TODO typed error
585 this.fail(new Error("Bad request: " + message));
586 return new InspectionResult(InspectionDecision.EndOperation, "BadRequest - " + message);
587};
588
589OperationBase.prototype._inspectNotHandled = function(pkg)
590{
591 var message = ClientMessage.NotHandled.decode(pkg.data.toBuffer());
592 switch (message.reason)
593 {
594 case ClientMessage.NotHandled.NotHandledReason.NotReady:
595 return new InspectionResult(InspectionDecision.Retry, "NotHandled - NotReady");
596
597 case ClientMessage.NotHandled.NotHandledReason.TooBusy:
598 return new InspectionResult(InspectionDecision.Retry, "NotHandled - TooBusy");
599
600 case ClientMessage.NotHandled.NotHandledReason.NotMaster:
601 var masterInfo = ClientMessage.NotHandled.MasterInfo.decode(message.additionalInfo);
602 return new InspectionResult(InspectionDecision.Reconnect, "NotHandled - NotMaster",
603 {host: masterInfo.externalTcpAddress, port: masterInfo.externalTcpPort},
604 {host: masterInfo.externalSecureTcpAddress, port: masterInfo.externalSecureTcpPort});
605
606 default:
607 this.log.error("Unknown NotHandledReason: %s.", message.reason);
608 return new InspectionResult(InspectionDecision.Retry, "NotHandled - <unknown>");
609 }
610};
611
612OperationBase.prototype._inspectUnexpectedCommand = function(pkg, expectedCommand)
613{
614 if (pkg.command === expectedCommand) throw new Error("Command shouldn't be " + TcpCommand.getName(pkg.command));
615
616 this.log.error("Unexpected TcpCommand received.\n"
617 + "Expected: %s, Actual: %s, Flags: %s, CorrelationId: %s\n"
618 + "Operation (%s): %s\n"
619 + "TcpPackage Data Dump:\n%j",
620 expectedCommand, TcpCommand.getName(pkg.command), pkg.flags, pkg.correlationId,
621 this.constructor.name, this, pkg.data);
622
623 this.fail(new Error(util.format("Unexpected command. Expecting %s got %s.", TcpCommand.getName(expectedCommand), TcpCommand.getName(pkg.command))));
624 return new InspectionResult(InspectionDecision.EndOperation, "Unexpected command - " + TcpCommand.getName(pkg.command));
625};
626
627
628module.exports = OperationBase;
629
630/***/ }),
631/* 7 */
632/***/ (function(module, exports, __webpack_require__) {
633
634var util = __webpack_require__(0);
635var Long = __webpack_require__(9);
636
637function AccessDeniedError(action, streamOrTransactionId) {
638 Error.captureStackTrace(this, this.constructor);
639 this.name = this.constructor.name;
640 this.action = action;
641 if (typeof streamOrTransactionId === 'string') {
642 this.message = util.format("%s access denied for stream '%s'.", action, streamOrTransactionId);
643 this.stream = streamOrTransactionId;
644 Object.freeze(this);
645 return;
646 }
647 if (Long.isLong(streamOrTransactionId)) {
648 this.message = util.format("%s access denied for transaction %s.", action, streamOrTransactionId);
649 this.transactionId = streamOrTransactionId;
650 Object.freeze(this);
651 return;
652 }
653 throw new TypeError("second argument must be a stream name or transaction Id.");
654}
655util.inherits(AccessDeniedError, Error);
656
657module.exports = AccessDeniedError;
658
659/***/ }),
660/* 8 */
661/***/ (function(module, exports, __webpack_require__) {
662
663var Long = __webpack_require__(9);
664
665module.exports.notNullOrEmpty = function(value, name) {
666 if (value === null) throw new TypeError(name + " should not be null.");
667 if (value === '') throw new Error(name + " should not be empty.");
668};
669
670module.exports.notNull = function(value, name) {
671 if (value === null) throw new TypeError(name + " should not be null.");
672};
673
674function isInteger(value, name) {
675 if (typeof value !== 'number' || value % 1 !== 0) throw new TypeError(name + " should be an integer.");
676}
677module.exports.isInteger = isInteger;
678
679module.exports.isLongOrInteger = function(value, name) {
680 if (typeof value === 'number') {
681 return isInteger(value, name);
682 } else if (!Long.isLong(value)) {
683 throw new TypeError(name + " should be a Long|number.");
684 }
685};
686
687module.exports.isArrayOf = function(expectedType, value, name) {
688 if (!Array.isArray(value)) throw new TypeError(name + " should be an array.");
689 if (!value.every(function(x) { return x instanceof expectedType; })) {
690 throw new TypeError([name, " should be an array of ", expectedType.name, "."].join(""));
691 }
692};
693
694module.exports.isTypeOf = function(expectedType, value, name, nullAllowed) {
695 if (nullAllowed && value === null) return;
696 if (!(value instanceof expectedType)) {
697 throw new TypeError([name, " should be of type '", expectedType.name, "'", nullAllowed ? " or null" : "", "."].join(""));
698 }
699};
700
701module.exports.positive = function(value, name) {
702 if (value <= 0) throw new Error(name + " should be positive.");
703};
704
705module.exports.nonNegative = function(value, name) {
706 if (value < 0) throw new Error(name + " should be non-negative.");
707};
708
709/***/ }),
710/* 9 */
711/***/ (function(module, exports) {
712
713module.exports = require("long");
714
715/***/ }),
716/* 10 */
717/***/ (function(module, exports) {
718
719/**
720 * Create a buffer segment
721 * @private
722 * @param {Buffer} buf
723 * @param {number} [offset]
724 * @param {number} [count]
725 * @constructor
726 */
727function BufferSegment(buf, offset, count) {
728 if (!Buffer.isBuffer(buf)) throw new TypeError('buf must be a buffer');
729
730 this.buffer = buf;
731 this.offset = offset || 0;
732 this.count = count || buf.length;
733}
734
735BufferSegment.prototype.toString = function() {
736 return this.buffer.toString('utf8', this.offset, this.offset + this.count);
737};
738
739BufferSegment.prototype.toBuffer = function() {
740 if (this.offset === 0 && this.count === this.buffer.length) return this.buffer;
741 return this.buffer.slice(this.offset, this.offset + this.count);
742};
743
744BufferSegment.prototype.copyTo = function(dst, offset) {
745 this.buffer.copy(dst, offset, this.offset, this.offset + this.count);
746};
747
748module.exports = function(buf, offset, count) {
749 return new BufferSegment(buf, offset, count);
750};
751
752/***/ }),
753/* 11 */
754/***/ (function(module, exports, __webpack_require__) {
755
756var guidParse = __webpack_require__(13);
757
758var createBufferSegment = __webpack_require__(10);
759var TcpFlags = __webpack_require__(12);
760
761const CommandOffset = 0;
762const FlagsOffset = CommandOffset + 1;
763const CorrelationOffset = FlagsOffset + 1;
764const AuthOffset = CorrelationOffset + 16;
765const MandatorySize = AuthOffset;
766
767function TcpPackage(command, flags, correlationId, login, password, data) {
768 this.command = command;
769 this.flags = flags;
770 this.correlationId = correlationId;
771 this.login = login || null;
772 this.password = password || null;
773 this.data = data || null;
774}
775
776TcpPackage.fromBufferSegment = function(data) {
777 if (data.length < MandatorySize) throw new Error("ArraySegment too short, length: " + data.length);
778
779 var command = data.buffer[data.offset + CommandOffset];
780 var flags = data.buffer[data.offset + FlagsOffset];
781
782 var correlationId = guidParse.unparse(data.buffer, data.offset + CorrelationOffset);
783
784 var headerSize = MandatorySize;
785 var login = null, pass = null;
786 if ((flags & TcpFlags.Authenticated) !== 0)
787 {
788 var loginLen = data.buffer[data.offset + AuthOffset];
789 if (AuthOffset + 1 + loginLen + 1 >= data.count) {
790 throw new Error("Login length is too big, it doesn't fit into TcpPackage.");
791 }
792 login = data.buffer.toString('utf8', data.offset + AuthOffset + 1, data.offset + AuthOffset + 1 + loginLen);
793
794 var passLen = data.buffer[data.offset + AuthOffset + 1 + loginLen];
795 if (AuthOffset + 1 + loginLen + 1 + passLen > data.count) {
796 throw new Error("Password length is too big, it doesn't fit into TcpPackage.");
797 }
798 headerSize += 1 + loginLen + 1 + passLen;
799 pass = data.buffer.toString('utf8', data.offset + AuthOffset + 1 + loginLen + 1, data.offset + headerSize);
800 }
801 return new TcpPackage(
802 command, flags, correlationId, login, pass,
803 createBufferSegment(data.buffer, data.offset + headerSize, data.count - headerSize));
804};
805
806TcpPackage.prototype.asBuffer = function() {
807 if ((this.flags & TcpFlags.Authenticated) !== 0) {
808 var loginBytes = new Buffer(this.login);
809 if (loginBytes.length > 255) throw new Error("Login serialized length should be less than 256 bytes.");
810 var passwordBytes = new Buffer(this.password);
811 if (passwordBytes.length > 255) throw new Error("Password serialized length should be less than 256 bytes.");
812
813 var res = new Buffer(MandatorySize + 2 + loginBytes.length + passwordBytes.length + (this.data ? this.data.count : 0));
814 res[CommandOffset] = this.command;
815 res[FlagsOffset] = this.flags;
816 guidParse.parse(this.correlationId, res, CorrelationOffset);
817
818 res[AuthOffset] = loginBytes.length;
819 loginBytes.copy(res, AuthOffset + 1);
820 res[AuthOffset + 1 + loginBytes.length] = passwordBytes.length;
821 passwordBytes.copy(res, AuthOffset + 2 + loginBytes.length);
822
823 if (this.data) this.data.copyTo(res, res.length - this.data.count);
824
825 return res;
826 } else {
827 var res = new Buffer(MandatorySize + (this.data ? this.data.count : 0));
828 res[CommandOffset] = this.command;
829 res[FlagsOffset] = this.flags;
830 guidParse.parse(this.correlationId, res, CorrelationOffset);
831 if (this.data) this.data.copyTo(res, AuthOffset);
832 return res;
833 }
834};
835
836TcpPackage.prototype.asBufferSegment = function() {
837 return createBufferSegment(this.asBuffer());
838};
839
840module.exports = TcpPackage;
841
842/***/ }),
843/* 12 */
844/***/ (function(module, exports) {
845
846const TcpFlags = Object.freeze({
847 None: 0x0,
848 Authenticated: 0x01
849});
850
851module.exports = TcpFlags;
852
853
854/***/ }),
855/* 13 */
856/***/ (function(module, exports, __webpack_require__) {
857
858"use strict";
859
860
861// Maps for number <-> hex string conversion
862var _byteToHex = [];
863var _hexToByte = {};
864for (var i = 0; i < 256; i++) {
865 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
866 _hexToByte[_byteToHex[i]] = i;
867}
868
869// **`parse()` - Parse a UUID into it's component bytes**
870function parse(s, buf, offset) {
871 const i = (buf && offset) || 0;
872 var ii = 0;
873
874 if (buf) buf.fill(0, i, i + 16);
875 buf = buf || new Buffer(16);
876 s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
877 if (ii < 16) { // Don't overflow!
878 buf[i + ii++] = _hexToByte[oct];
879 }
880 });
881
882 var buf2 = new Buffer(buf.slice(i, i + 16));
883 buf[i + 0] = buf2[3];
884 buf[i + 1] = buf2[2];
885 buf[i + 2] = buf2[1];
886 buf[i + 3] = buf2[0];
887 buf[i + 4] = buf2[5];
888 buf[i + 5] = buf2[4];
889 buf[i + 6] = buf2[7];
890 buf[i + 7] = buf2[6];
891
892 return buf;
893}
894
895// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
896function unparse(buf, offset) {
897 var i = offset || 0;
898 return '03020100-0504-0706-0809-101112131415'.replace(/\d{2}/g, function (num) {
899 var j = parseInt(num, 10);
900 return _byteToHex[buf[i+j]];
901 })
902}
903
904exports.parse = parse;
905exports.unparse = unparse;
906
907/***/ }),
908/* 14 */
909/***/ (function(module, exports) {
910
911const SubscriptionDropReason = Object.freeze({
912 AccessDenied: 'accessDenied',
913 CatchUpError: 'catchUpError',
914 ConnectionClosed: 'connectionClosed',
915 EventHandlerException: 'eventHandlerException',
916 MaxSubscribersReached: 'maxSubscribersReached',
917 NotFound: 'notFound',
918 PersistentSubscriptionDeleted: 'persistentSubscriptionDeleted',
919 ProcessingQueueOverflow: 'processingQueueOverflow',
920 ServerError: 'serverError',
921 SubscribingError: 'subscribingError',
922 UserInitiated: 'userInitiated',
923 Unknown: 'unknown'
924});
925
926module.exports = SubscriptionDropReason;
927
928/***/ }),
929/* 15 */
930/***/ (function(module, exports, __webpack_require__) {
931
932var util = __webpack_require__(0);
933var Long = __webpack_require__(9);
934
935function WrongExpectedVersionError(action, streamOrTransactionId, expectedVersion) {
936 Error.captureStackTrace(this, this.constructor);
937 this.name = this.constructor.name;
938 this.action = action;
939 if (typeof streamOrTransactionId === 'string') {
940 this.message = util.format("%s failed due to WrongExpectedVersion. Stream: %s Expected version: %d.", action, streamOrTransactionId, expectedVersion);
941 this.stream = streamOrTransactionId;
942 this.expectedVersion = expectedVersion;
943 Object.freeze(this);
944 return;
945 }
946 if (Long.isLong(streamOrTransactionId)) {
947 this.message = util.format("%s transaction failed due to WrongExpectedVersion. Transaction Id: %s.", action, streamOrTransactionId);
948 this.transactionId = streamOrTransactionId;
949 Object.freeze(this);
950 return;
951 }
952 throw new TypeError("second argument must be a stream name or a transaction Id.");
953}
954util.inherits(WrongExpectedVersionError, Error);
955
956module.exports = WrongExpectedVersionError;
957
958/***/ }),
959/* 16 */
960/***/ (function(module, exports, __webpack_require__) {
961
962var util = __webpack_require__(0);
963var Long = __webpack_require__(9);
964
965function StreamDeletedError(streamOrTransactionId) {
966 Error.captureStackTrace(this, this.constructor);
967 this.name = this.constructor.name;
968 if (typeof streamOrTransactionId === 'string') {
969 this.message = util.format("Event stream '%s' is deleted.", streamOrTransactionId);
970 this.stream = streamOrTransactionId;
971 Object.freeze(this);
972 return;
973 }
974 if (Long.isLong(streamOrTransactionId)) {
975 this.message = util.format("Stream is deleted for transaction %s.", streamOrTransactionId);
976 this.transactionId = streamOrTransactionId;
977 Object.freeze(this);
978 return;
979 }
980 throw new TypeError("second argument must be a stream name or transaction Id.");
981}
982util.inherits(StreamDeletedError, Error);
983
984module.exports = StreamDeletedError;
985
986/***/ }),
987/* 17 */
988/***/ (function(module, exports) {
989
990const SystemConsumerStrategies = Object.freeze({
991 DispatchToSingle: 'DispatchToSingle',
992 RoundRobin: 'RoundRobin',
993 Pinned: 'Pinned'
994});
995
996module.exports = SystemConsumerStrategies;
997
998/***/ }),
999/* 18 */
1000/***/ (function(module, exports) {
1001
1002module.exports = require("uuid");
1003
1004/***/ }),
1005/* 19 */
1006/***/ (function(module, exports) {
1007
1008const ReadDirection = Object.freeze({
1009 Forward: 'forward',
1010 Backward: 'backward'
1011});
1012
1013module.exports = ReadDirection;
1014
1015/***/ }),
1016/* 20 */
1017/***/ (function(module, exports, __webpack_require__) {
1018
1019var util = __webpack_require__(0);
1020
1021function Message() {
1022}
1023Message.prototype.toString = function() {
1024 return this.constructor.name;
1025};
1026
1027function StartConnectionMessage(cb, endpointDiscoverer) {
1028 this.cb = cb;
1029 this.endpointDiscoverer = endpointDiscoverer;
1030}
1031util.inherits(StartConnectionMessage, Message);
1032
1033function CloseConnectionMessage(reason, error) {
1034 this.reason = reason;
1035 this.error = error;
1036}
1037util.inherits(CloseConnectionMessage, Message);
1038
1039function StartOperationMessage(operation, maxRetries, timeout) {
1040 this.operation = operation;
1041 this.maxRetries = maxRetries;
1042 this.timeout = timeout;
1043}
1044util.inherits(StartOperationMessage, Message);
1045
1046function StartSubscriptionMessage(
1047 cb, streamId, resolveLinkTos, userCredentials, eventAppeared, subscriptionDropped, maxRetries, timeout
1048) {
1049 this.cb = cb;
1050 this.streamId = streamId;
1051 this.resolveLinkTos = resolveLinkTos;
1052 this.userCredentials = userCredentials;
1053 this.eventAppeared = eventAppeared;
1054 this.subscriptionDropped = subscriptionDropped;
1055 this.maxRetries = maxRetries;
1056 this.timeout = timeout;
1057}
1058util.inherits(StartSubscriptionMessage, Message);
1059
1060/**
1061 * @private
1062 * @constructor
1063 * @property {object} endPoints
1064 * @property {object} endPoints.secureTcpEndPoint
1065 * @property {object} endPoints.tcpEndPoint
1066 */
1067function EstablishTcpConnectionMessage(endPoints) {
1068 this.endPoints = endPoints;
1069}
1070util.inherits(EstablishTcpConnectionMessage, Message);
1071
1072function HandleTcpPackageMessage(connection, pkg) {
1073 this.connection = connection;
1074 this.package = pkg;
1075}
1076util.inherits(HandleTcpPackageMessage, Message);
1077
1078function TcpConnectionErrorMessage(connection, error) {
1079 this.connection = connection;
1080 this.error = error;
1081}
1082util.inherits(TcpConnectionErrorMessage, Message);
1083
1084function TcpConnectionEstablishedMessage(connection) {
1085 this.connection = connection;
1086}
1087util.inherits(TcpConnectionEstablishedMessage, Message);
1088
1089function TcpConnectionClosedMessage(connection, error) {
1090 this.connection = connection;
1091 this.error = error;
1092}
1093util.inherits(TcpConnectionClosedMessage, Message);
1094
1095function TimerTickMessage() {}
1096util.inherits(TimerTickMessage, Message);
1097
1098function StartPersistentSubscriptionMessage(
1099 cb, subscriptionId, streamId, bufferSize, userCredentials, eventAppeared, subscriptionDropped,
1100 maxRetries, operationTimeout
1101) {
1102 this.cb = cb;
1103 this.subscriptionId = subscriptionId;
1104 this.streamId = streamId;
1105 this.bufferSize = bufferSize;
1106 this.userCredentials = userCredentials;
1107 this.eventAppeared = eventAppeared;
1108 this.subscriptionDropped = subscriptionDropped;
1109 this.maxRetries = maxRetries;
1110 this.timeout = operationTimeout;
1111}
1112util.inherits(StartPersistentSubscriptionMessage, Message);
1113
1114module.exports = {
1115 StartConnectionMessage: StartConnectionMessage,
1116 CloseConnectionMessage: CloseConnectionMessage,
1117 StartOperationMessage: StartOperationMessage,
1118 StartSubscriptionMessage: StartSubscriptionMessage,
1119 EstablishTcpConnectionMessage: EstablishTcpConnectionMessage,
1120 HandleTcpPackageMessage: HandleTcpPackageMessage,
1121 TcpConnectionErrorMessage: TcpConnectionErrorMessage,
1122 TcpConnectionEstablishedMessage: TcpConnectionEstablishedMessage,
1123 TcpConnectionClosedMessage: TcpConnectionClosedMessage,
1124 TimerTickMessage: TimerTickMessage,
1125 StartPersistentSubscriptionMessage: StartPersistentSubscriptionMessage
1126};
1127
1128
1129/***/ }),
1130/* 21 */
1131/***/ (function(module, exports) {
1132
1133const SliceReadStatus = Object.freeze({
1134 Success: 'success',
1135 StreamNotFound: 'streamNotFound',
1136 StreamDeleted: 'streamDeleted'
1137});
1138
1139module.exports = SliceReadStatus;
1140
1141/***/ }),
1142/* 22 */
1143/***/ (function(module, exports) {
1144
1145const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1146function isValidId(id) {
1147 if (typeof id !== 'string') return false;
1148 return uuidRegex.test(id);
1149}
1150
1151/**
1152 * Create an EventData
1153 * @private
1154 * @param {string} eventId
1155 * @param {string} type
1156 * @param {boolean} [isJson]
1157 * @param {Buffer} [data]
1158 * @param {Buffer} [metadata]
1159 * @constructor
1160 */
1161function EventData(eventId, type, isJson, data, metadata) {
1162 if (!isValidId(eventId)) throw new TypeError("eventId must be a string containing a UUID.");
1163 if (typeof type !== 'string' || type === '') throw new TypeError("type must be a non-empty string.");
1164 if (isJson && typeof isJson !== 'boolean') throw new TypeError("isJson must be a boolean.");
1165 if (data && !Buffer.isBuffer(data)) throw new TypeError("data must be a Buffer.");
1166 if (metadata && !Buffer.isBuffer(metadata)) throw new TypeError("metadata must be a Buffer.");
1167
1168 this.eventId = eventId;
1169 this.type = type;
1170 this.isJson = isJson || false;
1171 this.data = data || new Buffer(0);
1172 this.metadata = metadata || new Buffer(0);
1173 Object.freeze(this);
1174}
1175
1176module.exports = EventData;
1177
1178
1179/***/ }),
1180/* 23 */
1181/***/ (function(module, exports) {
1182
1183function GossipSeed(endPoint, hostName) {
1184 if (typeof endPoint !== 'object' || !endPoint.host || !endPoint.port) throw new TypeError('endPoint must be have host and port properties.');
1185 this.endPoint = endPoint;
1186 this.hostName = hostName;
1187 Object.freeze(this);
1188}
1189
1190module.exports = GossipSeed;
1191
1192/***/ }),
1193/* 24 */
1194/***/ (function(module, exports, __webpack_require__) {
1195
1196var EventStoreNodeConnection = __webpack_require__(39);
1197var StaticEndpointDiscoverer = __webpack_require__(72);
1198var ClusterDnsEndPointDiscoverer = __webpack_require__(73);
1199var NoopLogger = __webpack_require__(34);
1200var ensure = __webpack_require__(8);
1201
1202var defaultConnectionSettings = Object.freeze({
1203 log: new NoopLogger(),
1204 verboseLogging: false,
1205
1206 maxQueueSize: 5000,
1207 maxConcurrentItems: 5000,
1208 maxRetries: 10,
1209 maxReconnections: 10,
1210
1211 requireMaster: true,
1212
1213 reconnectionDelay: 100,
1214 operationTimeout: 7*1000,
1215 operationTimeoutCheckPeriod: 1000,
1216
1217 defaultUserCredentials: null,
1218 useSslConnection: false,
1219 targetHost: null,
1220 validateServer: false,
1221
1222 failOnNoServerResponse: false,
1223 heartbeatInterval: 750,
1224 heartbeatTimeout: 1500,
1225 clientConnectionTimeout: 1000,
1226
1227 // Cluster Settings
1228 clusterDns: '',
1229 maxDiscoverAttempts: 10,
1230 externalGossipPort: 0,
1231 gossipTimeout: 1000
1232});
1233
1234
1235function merge(a,b) {
1236 var c = {};
1237 Object.getOwnPropertyNames(a).forEach(function(k) {
1238 c[k] = a[k];
1239 });
1240 Object.getOwnPropertyNames(b).forEach(function(k) {
1241 c[k] = b[k];
1242 });
1243 return c;
1244}
1245
1246function createFromTcpEndpoint(settings, tcpEndpoint, connectionName) {
1247 if (!tcpEndpoint.port || !tcpEndpoint.host) throw new TypeError('endPoint object must have host and port properties.');
1248 var mergedSettings = merge(defaultConnectionSettings, settings || {});
1249 var endpointDiscoverer = new StaticEndpointDiscoverer(tcpEndpoint, settings.useSslConnection);
1250 return new EventStoreNodeConnection(mergedSettings, null, endpointDiscoverer, connectionName || null);
1251}
1252
1253function createFromStringEndpoint(settings, endPoint, connectionName) {
1254 var m = endPoint.match(/^(tcp|discover):\/\/([^:]+):?(\d+)?$/);
1255 if (!m) throw new Error('endPoint string must be tcp://hostname[:port] or discover://dns[:port]');
1256 var scheme = m[1];
1257 var host = m[2] || null;
1258 var port = m[3] ? parseInt(m[3]) : null;
1259 if (scheme === 'tcp') {
1260 var tcpEndpoint = {
1261 host: host,
1262 port: port || 1113
1263 };
1264 return createFromTcpEndpoint(settings, tcpEndpoint, connectionName);
1265 }
1266 if (scheme === 'discover') {
1267 return createFromClusterDns(settings, host, port || 2113, connectionName);
1268 }
1269 throw new Error('Invalid scheme for endPoint: ' + scheme);
1270}
1271
1272function createFromClusterDns(connectionSettings, clusterDns, externalGossipPort, connectionName) {
1273 ensure.notNull(connectionSettings, "connectionSettings");
1274 ensure.notNull(clusterDns, "clusterDns");
1275 var mergedSettings = merge(defaultConnectionSettings, connectionSettings || {});
1276 var clusterSettings = {
1277 clusterDns: clusterDns,
1278 gossipSeeds: null,
1279 externalGossipPort: externalGossipPort,
1280 maxDiscoverAttempts: mergedSettings.maxDiscoverAttempts,
1281 gossipTimeout: mergedSettings.gossipTimeout
1282 };
1283 var endPointDiscoverer = new ClusterDnsEndPointDiscoverer(mergedSettings.log,
1284 clusterSettings.clusterDns,
1285 clusterSettings.maxDiscoverAttempts,
1286 clusterSettings.externalGossipPort,
1287 clusterSettings.gossipSeeds,
1288 clusterSettings.gossipTimeout
1289 );
1290 return new EventStoreNodeConnection(mergedSettings, clusterSettings, endPointDiscoverer, connectionName);
1291}
1292
1293function createFromGossipSeeds(connectionSettings, gossipSeeds, connectionName) {
1294 ensure.notNull(connectionSettings, "connectionSettings");
1295 ensure.notNull(gossipSeeds, "gossipSeeds");
1296 var mergedSettings = merge(defaultConnectionSettings, connectionSettings || {});
1297 var clusterSettings = {
1298 clusterDns: '',
1299 gossipSeeds: gossipSeeds,
1300 externalGossipPort: 0,
1301 maxDiscoverAttempts: mergedSettings.maxDiscoverAttempts,
1302 gossipTimeout: mergedSettings.gossipTimeout
1303 };
1304 var endPointDiscoverer = new ClusterDnsEndPointDiscoverer(mergedSettings.log,
1305 clusterSettings.clusterDns,
1306 clusterSettings.maxDiscoverAttempts,
1307 clusterSettings.externalGossipPort,
1308 clusterSettings.gossipSeeds,
1309 clusterSettings.gossipTimeout
1310 );
1311 return new EventStoreNodeConnection(mergedSettings, clusterSettings, endPointDiscoverer, connectionName);
1312}
1313
1314/**
1315 * Create an EventStore connection
1316 * @public
1317 * @alias createConnection
1318 * @param {object} settings
1319 * @param {boolean} [settings.verboseLogging=false]
1320 * @param {number} [settings.maxQueueSize=5000]
1321 * @param {number} [settings.maxConcurrentItems=5000]
1322 * @param {number} [settings.maxRetries=10]
1323 * @param {number} [settings.maxReconnections=10]
1324 * @param {boolean} [settings.requireMaster=true]
1325 * @param {number} [settings.reconnectionDelay=100]
1326 * @param {number} [settings.operationTimeout=7000]
1327 * @param {number} [settings.operationTimeoutCheckPeriod=1000]
1328 * @param {object} [settings.defaultUserCredentials=null] - The default user credentials to use for requests
1329 * @param {boolean} [settings.useSslConnection=false] - Whether to use SSL or not
1330 * @param {object} [settings.targetHost=null]
1331 * @param {boolean} [settings.validateServer=false]
1332 * @param {boolean} [settings.failOnNoServerResponse=false]
1333 * @param {number} [settings.heartbeatInterval=750]
1334 * @param {number} [settings.heartbeatTimeout=1500]
1335 * @param {number} [settings.clientConnectionTimeout=1000]
1336 * @param {string} [settings.clusterDns='']
1337 * @param {number} [settings.maxDiscoverAttempts=10]
1338 * @param {number} [settings.externalGossipPort=0]
1339 * @param {number} [settings.gossipTimeout=1000]
1340 * @param {string|object|array} endPointOrGossipSeeds
1341 * @param {string} [connectionName]
1342 * @returns {EventStoreNodeConnection}
1343 */
1344module.exports.create = function(settings, endPointOrGossipSeeds, connectionName) {
1345 if (Array.isArray(endPointOrGossipSeeds)) return createFromGossipSeeds(settings, endPointOrGossipSeeds, connectionName);
1346 if (typeof endPointOrGossipSeeds === 'object') return createFromTcpEndpoint(settings, endPointOrGossipSeeds, connectionName);
1347 if (typeof endPointOrGossipSeeds === 'string') return createFromStringEndpoint(settings, endPointOrGossipSeeds, connectionName);
1348 throw new TypeError('endPointOrGossipSeeds must be an object, a string or an array.');
1349};
1350
1351/***/ }),
1352/* 25 */
1353/***/ (function(module, exports) {
1354
1355module.exports = require("events");
1356
1357/***/ }),
1358/* 26 */
1359/***/ (function(module, exports) {
1360
1361/**
1362 * @private
1363 * @constructor
1364 * @property {number} length
1365 */
1366function Hash() {
1367 this._ = {};
1368 this._length = 0;
1369}
1370Object.defineProperty(Hash.prototype, 'length', {
1371 get: function() {
1372 return this._length;
1373 }
1374});
1375
1376Hash.prototype.add = function(key,value) {
1377 this._[key] = value;
1378 this._length++;
1379};
1380
1381Hash.prototype.clear = function() {
1382 this._ = {};
1383 this._length = 0;
1384};
1385
1386Hash.prototype.forEach = function(cb) {
1387 for(var k in this._) {
1388 cb(k, this._[k]);
1389 }
1390};
1391
1392Hash.prototype.get = function(key) {
1393 return this._[key];
1394};
1395
1396Hash.prototype.remove = function(key) {
1397 delete this._[key];
1398 this._length--;
1399};
1400
1401
1402module.exports = Hash;
1403
1404/***/ }),
1405/* 27 */
1406/***/ (function(module, exports, __webpack_require__) {
1407
1408var util = __webpack_require__(0);
1409
1410var TcpCommand = __webpack_require__(1);
1411var TcpFlags = __webpack_require__(12);
1412var InspectionDecision = __webpack_require__(4);
1413var InspectionResult = __webpack_require__(5);
1414var ClientMessage = __webpack_require__(2);
1415var TcpPackage = __webpack_require__(11);
1416var BufferSegment = __webpack_require__(10);
1417var results = __webpack_require__(3);
1418var SubscriptionDropReason = __webpack_require__(14);
1419
1420//TODO: nodify eventAppeared and subscriptionDropped, should be emit on subscription
1421function SubscriptionOperation(
1422 log, cb, streamId, resolveLinkTos, userCredentials, eventAppeared,
1423 subscriptionDropped, verboseLogging, getConnection
1424) {
1425 //TODO: validations
1426 //Ensure.NotNull(log, "log");
1427 //Ensure.NotNull(source, "source");
1428 //Ensure.NotNull(eventAppeared, "eventAppeared");
1429 //Ensure.NotNull(getConnection, "getConnection");
1430
1431 this._log = log;
1432 this._cb = cb;
1433 this._streamId = streamId || '';
1434 this._resolveLinkTos = resolveLinkTos;
1435 this._userCredentials = userCredentials;
1436 this._eventAppeared = eventAppeared;
1437 this._subscriptionDropped = subscriptionDropped || function() {};
1438 this._verboseLogging = verboseLogging;
1439 this._getConnection = getConnection;
1440
1441 this._correlationId = null;
1442 this._unsubscribed = false;
1443 this._subscription = null;
1444 this._actionExecuting = false;
1445 this._actionQueue = [];
1446}
1447
1448SubscriptionOperation.prototype._enqueueSend = function(pkg) {
1449 this._getConnection().enqueueSend(pkg);
1450};
1451
1452SubscriptionOperation.prototype.subscribe = function(correlationId, connection) {
1453 if (connection === null) throw new TypeError("connection is null.");
1454
1455 if (this._subscription !== null || this._unsubscribed) return false;
1456
1457 this._correlationId = correlationId;
1458 connection.enqueueSend(this._createSubscriptionPackage());
1459 return true;
1460};
1461
1462SubscriptionOperation.prototype._createSubscriptionPackage = function() {
1463 throw new Error("SubscriptionOperation._createSubscriptionPackage abstract method called. " + this.constructor.name);
1464};
1465
1466SubscriptionOperation.prototype.unsubscribe = function() {
1467 this.dropSubscription(SubscriptionDropReason.UserInitiated, null, this._getConnection());
1468};
1469
1470SubscriptionOperation.prototype._createUnsubscriptionPackage = function() {
1471 var msg = new ClientMessage.UnsubscribeFromStream();
1472 var data = new BufferSegment(ClientMessage.UnsubscribeFromStream.encode(msg).finish());
1473 return new TcpPackage(TcpCommand.UnsubscribeFromStream, TcpFlags.None, this._correlationId, null, null, data);
1474};
1475
1476SubscriptionOperation.prototype._inspectPackage = function(pkg) {
1477 throw new Error("SubscriptionOperation._inspectPackage abstract method called." + this.constructor.name);
1478};
1479
1480SubscriptionOperation.prototype.inspectPackage = function(pkg) {
1481 try
1482 {
1483 var result = this._inspectPackage(pkg);
1484 if (result !== null) return result;
1485
1486 switch (pkg.command)
1487 {
1488 case TcpCommand.StreamEventAppeared:
1489 {
1490 var dto = ClientMessage.StreamEventAppeared.decode(pkg.data.toBuffer());
1491 this._onEventAppeared(new results.ResolvedEvent(dto.event));
1492 return new InspectionResult(InspectionDecision.DoNothing, "StreamEventAppeared");
1493 }
1494
1495 case TcpCommand.SubscriptionDropped:
1496 {
1497 var dto = ClientMessage.SubscriptionDropped.decode(pkg.data.toBuffer());
1498 switch (dto.reason)
1499 {
1500 case ClientMessage.SubscriptionDropped.SubscriptionDropReason.Unsubscribed:
1501 this.dropSubscription(SubscriptionDropReason.UserInitiated, null);
1502 break;
1503 case ClientMessage.SubscriptionDropped.SubscriptionDropReason.AccessDenied:
1504 this.dropSubscription(SubscriptionDropReason.AccessDenied,
1505 new Error(util.format("Subscription to '%s' failed due to access denied.", this._streamId || "<all>")));
1506 break;
1507 default:
1508 if (this._verboseLogging) this._log.debug("Subscription dropped by server. Reason: %s.", dto.reason);
1509 this.dropSubscription(SubscriptionDropReason.Unknown,
1510 new Error(util.format("Unsubscribe reason: '%s'.", dto.reason)));
1511 break;
1512 }
1513 return new InspectionResult(InspectionDecision.EndOperation, util.format("SubscriptionDropped: %s", dto.reason));
1514 }
1515
1516 case TcpCommand.NotAuthenticated:
1517 {
1518 var message = pkg.data.toString();
1519 this.dropSubscription(SubscriptionDropReason.NotAuthenticated,
1520 new Error(message || "Authentication error"));
1521 return new InspectionResult(InspectionDecision.EndOperation, "NotAuthenticated");
1522 }
1523
1524 case TcpCommand.BadRequest:
1525 {
1526 var message = pkg.data.toString();
1527 this.dropSubscription(SubscriptionDropReason.ServerError,
1528 new Error("Server error: " + (message || "<no message>")));
1529 return new InspectionResult(InspectionDecision.EndOperation, util.format("BadRequest: %s", message));
1530 }
1531
1532 case TcpCommand.NotHandled:
1533 {
1534 if (this._subscription !== null) {
1535 throw new Error("NotHandled command appeared while we already subscribed.");
1536 }
1537
1538 var message = ClientMessage.NotHandled.decode(pkg.data.toBuffer());
1539 switch (message.reason)
1540 {
1541 case ClientMessage.NotHandled.NotHandledReason.NotReady:
1542 return new InspectionResult(InspectionDecision.Retry, "NotHandled - NotReady");
1543
1544 case ClientMessage.NotHandled.NotHandledReason.TooBusy:
1545 return new InspectionResult(InspectionDecision.Retry, "NotHandled - TooBusy");
1546
1547 case ClientMessage.NotHandled.NotHandledReason.NotMaster:
1548 var masterInfo = ClientMessage.NotHandled.MasterInfo.decode(message.additionalInfo);
1549 return new InspectionResult(InspectionDecision.Reconnect, "NotHandled - NotMaster",
1550 {host: masterInfo.externalTcpAddress, port: masterInfo.externalTcpPort},
1551 {host: masterInfo.externalSecureTcpAddress, port: masterInfo.externalSecureTcpPort});
1552
1553 default:
1554 this._log.error("Unknown NotHandledReason: %s.", message.reason);
1555 return new InspectionResult(InspectionDecision.Retry, "NotHandled - <unknown>");
1556 }
1557 }
1558
1559 default:
1560 {
1561 this.dropSubscription(SubscriptionDropReason.ServerError,
1562 new Error("Command not expected: " + TcpCommand.getName(pkg.command)));
1563 return new InspectionResult(InspectionDecision.EndOperation, pkg.command);
1564 }
1565 }
1566 }
1567 catch (e)
1568 {
1569 this.dropSubscription(SubscriptionDropReason.Unknown, e);
1570 return new InspectionResult(InspectionDecision.EndOperation, util.format("Exception - %s", e.Message));
1571 }
1572};
1573
1574SubscriptionOperation.prototype.connectionClosed = function() {
1575 this.dropSubscription(SubscriptionDropReason.ConnectionClosed, new Error("Connection was closed."));
1576};
1577
1578SubscriptionOperation.prototype.timeOutSubscription = function() {
1579 if (this._subscription !== null) return false;
1580 this.dropSubscription(SubscriptionDropReason.SubscribingError, null);
1581 return true;
1582};
1583
1584SubscriptionOperation.prototype.dropSubscription = function(reason, err, connection) {
1585 if (!this._unsubscribed)
1586 {
1587 this._unsubscribed = true;
1588 if (this._verboseLogging) {
1589 this._log.debug("Subscription %s to %s: closing subscription, reason: %s, exception: %s...",
1590 this._correlationId, this._streamId || "<all>", reason, err);
1591 }
1592
1593 if (reason !== SubscriptionDropReason.UserInitiated && this._subscription === null)
1594 {
1595 if (err === null) throw new Error(util.format("No exception provided for subscription drop reason '%s", reason));
1596 this._cb(err);
1597 return;
1598 }
1599
1600 if (reason === SubscriptionDropReason.UserInitiated && this._subscription !== null && connection !== null) {
1601 connection.enqueueSend(this._createUnsubscriptionPackage());
1602 }
1603
1604 var self = this;
1605 if (this._subscription !== null) {
1606 this._executeAction(function () {
1607 self._subscriptionDropped(self._subscription, reason, err);
1608 });
1609 }
1610 }
1611};
1612
1613SubscriptionOperation.prototype._confirmSubscription = function(lastCommitPosition, lastEventNumber) {
1614 if (lastCommitPosition < -1) {
1615 throw new Error(util.format("Invalid lastCommitPosition %s on subscription confirmation.", lastCommitPosition));
1616 }
1617 if (this._subscription !== null) {
1618 throw new Error("Double confirmation of subscription.");
1619 }
1620
1621 if (this._verboseLogging) {
1622 this._log.debug("Subscription %s to %s: subscribed at CommitPosition: %d, EventNumber: %d.",
1623 this._correlationId, this._streamId || "<all>", lastCommitPosition, lastEventNumber);
1624 }
1625
1626 this._subscription = this._createSubscriptionObject(lastCommitPosition, lastEventNumber);
1627 this._cb(null, this._subscription);
1628};
1629
1630SubscriptionOperation.prototype._createSubscriptionObject = function(lastCommitPosition, lastEventNumber) {
1631 throw new Error("SubscriptionOperation._createSubscriptionObject abstract method called. " + this.constructor.name);
1632};
1633
1634SubscriptionOperation.prototype._onEventAppeared = function(e) {
1635 if (this._unsubscribed) return;
1636
1637 if (this._subscription === null) throw new Error("Subscription not confirmed, but event appeared!");
1638
1639 if (this._verboseLogging) {
1640 this._log.debug("Subscription %s to %s: event appeared (%s, %d, %s @ %s).",
1641 this._correlationId, this._streamId || "<all>",
1642 e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
1643 }
1644
1645 var self = this;
1646 this._executeAction(function() { return self._eventAppeared(self._subscription, e); });
1647};
1648
1649SubscriptionOperation.prototype._executeAction = function(action) {
1650 this._actionQueue.push(action);
1651 if (!this._actionExecuting) {
1652 this._actionExecuting = true;
1653 setImmediate(this._executeActions.bind(this));
1654 }
1655};
1656
1657SubscriptionOperation.prototype._executeActions = function() {
1658 var action = this._actionQueue.shift();
1659 if (!action) {
1660 this._actionExecuting = false;
1661 return;
1662 }
1663 var promise;
1664 try
1665 {
1666 promise = action();
1667 }
1668 catch (err)
1669 {
1670 this._log.error(err, "Exception during executing user callback: %s.", err.message);
1671 }
1672 if (promise && promise.then) {
1673 var self = this;
1674 promise
1675 .catch(function (err) {
1676 self._log.error(err, "Exception during executing user callback: %s.", err.message);
1677 })
1678 .then(this._executeActions.bind(this));
1679 } else {
1680 setImmediate(this._executeActions.bind(this));
1681 }
1682};
1683
1684SubscriptionOperation.prototype.toString = function() {
1685 return this.constructor.name;
1686};
1687
1688
1689module.exports = SubscriptionOperation;
1690
1691/***/ }),
1692/* 28 */
1693/***/ (function(module, exports) {
1694
1695/***
1696 * EventStoreSubscription
1697 * @param {string} streamId
1698 * @param {number} lastCommitPosition
1699 * @param {?number} lastEventNumber
1700 * @constructor
1701 * @property {boolean} isSubscribedToAll
1702 * @property {string} streamId
1703 * @property {number} lastCommitPosition
1704 * @property {?number} lastEventNumber
1705 */
1706function EventStoreSubscription(streamId, lastCommitPosition, lastEventNumber) {
1707 Object.defineProperties(this, {
1708 isSubscribedToAll: {
1709 value: streamId === ''
1710 },
1711 streamId: {
1712 value: streamId
1713 },
1714 lastCommitPosition: {
1715 value: lastCommitPosition
1716 },
1717 lastEventNumber: {
1718 value: lastEventNumber
1719 }
1720 });
1721}
1722
1723/**
1724 * Unsubscribes from the stream
1725 */
1726EventStoreSubscription.prototype.close = function() {
1727 this.unsubscribe();
1728};
1729
1730/**
1731 * Unsubscribes from the stream
1732 * @abstract
1733 */
1734EventStoreSubscription.prototype.unsubscribe = function() {
1735 throw new Error("EventStoreSubscription.unsubscribe abstract method called." + this.constructor.name);
1736};
1737
1738module.exports = EventStoreSubscription;
1739
1740/***/ }),
1741/* 29 */
1742/***/ (function(module, exports) {
1743
1744/**
1745 * @param {number} transactionId
1746 * @param {UserCredentials} userCredentials
1747 * @param {EventStoreNodeConnection} connection
1748 * @constructor
1749 * @property {number} transactionId
1750 */
1751function EventStoreTransaction(transactionId, userCredentials, connection) {
1752 this._transactionId = transactionId;
1753 this._userCredentials = userCredentials;
1754 this._connection = connection;
1755
1756 this._isCommitted = false;
1757 this._isRolledBack = false;
1758
1759 Object.defineProperties(this, {
1760 transactionId: {
1761 enumerable: true, get: function() { return this._transactionId; }
1762 }
1763 });
1764}
1765
1766/**
1767 * Commit (async)
1768 * @returns {Promise.<WriteResult>}
1769 */
1770EventStoreTransaction.prototype.commit = function() {
1771 if (this._isRolledBack) throw new Error("Can't commit a rolledback transaction.");
1772 if (this._isCommitted) throw new Error("Transaction is already committed.");
1773 this._isCommitted = true;
1774 return this._connection.commitTransaction(this, this._userCredentials);
1775};
1776
1777/**
1778 * Write events (async)
1779 * @param {EventData|EventData[]} eventOrEvents
1780 * @returns {Promise}
1781 */
1782EventStoreTransaction.prototype.write = function(eventOrEvents) {
1783 if (this._isRolledBack) throw new Error("can't write to a rolledback transaction");
1784 if (this._isCommitted) throw new Error("Transaction is already committed");
1785 var events = Array.isArray(eventOrEvents) ? eventOrEvents : [eventOrEvents];
1786 return this._connection.transactionalWrite(this, events);
1787};
1788
1789/**
1790 * Rollback
1791 */
1792EventStoreTransaction.prototype.rollback = function() {
1793 if (this._isCommitted) throw new Error("Transaction is already committed");
1794 this._isRolledBack = true;
1795};
1796
1797module.exports = EventStoreTransaction;
1798
1799/***/ }),
1800/* 30 */
1801/***/ (function(module, exports, __webpack_require__) {
1802
1803var ClientMessage = __webpack_require__(2);
1804var SliceReadStatus = __webpack_require__(21);
1805
1806exports.convert = function(code) {
1807 switch(code) {
1808 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.Success:
1809 return SliceReadStatus.Success;
1810 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.NoStream:
1811 return SliceReadStatus.StreamNotFound;
1812 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.StreamDeleted:
1813 return SliceReadStatus.StreamDeleted;
1814 default:
1815 throw new Error('Invalid code: ' + code)
1816 }
1817};
1818
1819/***/ }),
1820/* 31 */
1821/***/ (function(module, exports, __webpack_require__) {
1822
1823var util = __webpack_require__(0);
1824
1825var SubscriptionDropReason = __webpack_require__(14);
1826
1827const DefaultReadBatchSize = 500;
1828const DefaultMaxPushQueueSize = 10000;
1829const MaxReadSize = 4096;
1830
1831function DropSubscriptionEvent() {}
1832
1833/**
1834 * @param connection
1835 * @param log
1836 * @param streamId
1837 * @param resolveLinkTos
1838 * @param userCredentials
1839 * @param eventAppeared
1840 * @param liveProcessingStarted
1841 * @param subscriptionDropped
1842 * @param verboseLogging
1843 * @param readBatchSize
1844 * @param maxPushQueueSize
1845 * @constructor
1846 * @property {boolean} isSubscribedToAll
1847 * @property {string} streamId
1848 * @property {number} readBatchSize
1849 * @property {number} maxPushQueueSize
1850 */
1851function EventStoreCatchUpSubscription(
1852 connection, log, streamId, resolveLinkTos, userCredentials,
1853 eventAppeared, liveProcessingStarted, subscriptionDropped,
1854 verboseLogging, readBatchSize, maxPushQueueSize
1855) {
1856 readBatchSize = readBatchSize || DefaultReadBatchSize;
1857 maxPushQueueSize = maxPushQueueSize || DefaultMaxPushQueueSize;
1858 //Ensure.NotNull(connection, "connection");
1859 //Ensure.NotNull(log, "log");
1860 //Ensure.NotNull(eventAppeared, "eventAppeared");
1861 //Ensure.Positive(readBatchSize, "readBatchSize");
1862 //Ensure.Positive(maxPushQueueSize, "maxPushQueueSize");
1863 if (readBatchSize > MaxReadSize) throw new Error(util.format("Read batch size should be less than %d. For larger reads you should page.", MaxReadSize));
1864
1865 this._connection = connection;
1866 this._log = log;
1867 this._streamId = streamId || '';
1868 this._resolveLinkTos = resolveLinkTos;
1869 this._userCredentials = userCredentials;
1870 this._shouldStop = false;
1871 this._stopped = false;
1872 this._isDropped = false;
1873 this._subscription = null;
1874 this._liveQueue = [];
1875 this._dropData = null;
1876 this._isProcessing = false;
1877
1878 Object.defineProperties(this, {
1879 isSubscribedToAll: { value: this._streamId === '' },
1880 streamId: { value: this._streamId },
1881 readBatchSize: { value: readBatchSize },
1882 maxPushQueueSize: { value: maxPushQueueSize }
1883 });
1884
1885 this._eventAppeared = eventAppeared;
1886 this._liveProcessingStarted = liveProcessingStarted;
1887 this._subscriptionDropped = subscriptionDropped;
1888 this._verbose = verboseLogging;
1889
1890 var self = this;
1891 this._onReconnect = function() {
1892 if (self._verbose) self._log.debug("Catch-up Subscription to %s: unhooking from connection.Connected.", self._streamId || '<all>');
1893 self._connection.removeListener('connected', self._onReconnect);
1894 if (self._verbose) self._log.debug("Catch-up Subscription to %s: recovering after reconnection.", self._streamId || '<all>');
1895 self._runSubscription();
1896 }
1897}
1898
1899/**
1900 * @param {EventStoreNodeConnection} connection
1901 * @param {boolean} resolveLinkTos
1902 * @param {UserCredentials} userCredentials
1903 * @param {?number} lastCommitPosition
1904 * @param {?number} lastEventNumber
1905 * @private
1906 * @abstract
1907 */
1908EventStoreCatchUpSubscription.prototype._readEventsTill = function(
1909 connection, resolveLinkTos, userCredentials, lastCommitPosition, lastEventNumber
1910) {
1911 throw new Error("EventStoreCatchUpSubscription._readEventsTill abstract method called. " + this.constructor.name);
1912};
1913
1914/**
1915 * @param {ResolvedEvent} e
1916 * @private
1917 * @abstract
1918 */
1919EventStoreCatchUpSubscription.prototype._tryProcess = function(e) {
1920 throw new Error("EventStoreCatchUpSubscription._tryProcess abstract method called. " + this.constructor.name);
1921};
1922
1923EventStoreCatchUpSubscription.prototype.start = function() {
1924 if (this._verbose) this._log.debug("Catch-up Subscription to %s: starting...", this._streamId || '<all>');
1925 this._runSubscription();
1926};
1927
1928EventStoreCatchUpSubscription.prototype.stop = function() {
1929 if (this._verbose) this._log.debug("Catch-up Subscription to %s: requesting stop...", this._streamId || '<all>');
1930
1931 if (this._verbose) this._log.debug("Catch-up Subscription to %s: unhooking from connection.Connected.", this._streamId || '<all>');
1932 this._connection.removeListener('connected', this._onReconnect);
1933
1934 this._shouldStop = true;
1935 this._enqueueSubscriptionDropNotification(SubscriptionDropReason.UserInitiated, null);
1936/*
1937 if (timeout) {
1938 if (this._verbose) this._log.debug("Waiting on subscription to stop");
1939 if (!this._stopped.Wait(timeout))
1940 throw new TimeoutException(string.Format("Could not stop {0} in time.", GetType().Name));
1941 }
1942 */
1943};
1944
1945EventStoreCatchUpSubscription.prototype._runSubscription = function() {
1946 var logStreamName = this._streamId || '<all>';
1947
1948 if (this._verbose) this._log.debug("Catch-up Subscription to %s: running...", logStreamName);
1949
1950 var self = this;
1951 this._stopped = false;
1952 this._isDropped = false;
1953 this._dropData = null;
1954 if (this._verbose) this._log.debug("Catch-up Subscription to %s: pulling events...", logStreamName);
1955 this._readEventsTill(this._connection, this._resolveLinkTos, this._userCredentials, null, null)
1956 .then(function() {
1957 if (self._shouldStop) return;
1958 if (self._verbose) self._log.debug("Catch-up Subscription to %s: subscribing...", logStreamName);
1959 if (self._streamId === '') {
1960 return self._connection.subscribeToAll(self._resolveLinkTos, self._enqueuePushedEvent.bind(self), self._serverSubscriptionDropped.bind(self), self._userCredentials);
1961 } else {
1962 return self._connection.subscribeToStream(self._streamId, self._resolveLinkTos, self._enqueuePushedEvent.bind(self), self._serverSubscriptionDropped.bind(self), self._userCredentials);
1963 }
1964 })
1965 .then(function(subscription) {
1966 if (subscription === undefined) return;
1967 if (self._verbose) self._log.debug("Catch-up Subscription to %s: pulling events (if left)...", logStreamName);
1968 self._subscription = subscription;
1969 return self._readEventsTill(self._connection, self._resolveLinkTos, self._userCredentials, subscription.lastCommitPosition, subscription.lastEventNumber)
1970 })
1971 .catch(function(err) {
1972 self._dropSubscription(SubscriptionDropReason.CatchUpError, err);
1973 return true;
1974 })
1975 .then(function(faulted) {
1976 if (faulted) return;
1977 if (self._shouldStop) {
1978 self._dropSubscription(SubscriptionDropReason.UserInitiated, null);
1979 return;
1980 }
1981 if (self._verbose) self._log.debug("Catch-up Subscription to %s: processing live events...", logStreamName);
1982 if (self._liveProcessingStarted) {
1983 try {
1984 self._liveProcessingStarted(self);
1985 } catch (e) {
1986 self._log.error(e, "Catch-up Subscription to %s: liveProcessingStarted callback failed.", logStreamName);
1987 }
1988 }
1989 if (self._verbose) self._log.debug("Catch-up Subscription to %s: hooking to connection.Connected", logStreamName);
1990 self._connection.on('connected', self._onReconnect);
1991 self._allowProcessing = true;
1992 self._ensureProcessingPushQueue();
1993 });
1994};
1995
1996EventStoreCatchUpSubscription.prototype._enqueuePushedEvent = function(subscription, e) {
1997 if (this._verbose) {
1998 this._log.debug("Catch-up Subscription to %s: event appeared (%s, %d, %s @ %s).",
1999 this._streamId || '<all>',
2000 e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
2001 }
2002
2003 if (this._liveQueue.length >= this.maxPushQueueSize)
2004 {
2005 this._enqueueSubscriptionDropNotification(SubscriptionDropReason.ProcessingQueueOverflow, null);
2006 subscription.unsubscribe();
2007 return;
2008 }
2009
2010 this._liveQueue.push(e);
2011
2012 if (this._allowProcessing) this._ensureProcessingPushQueue();
2013};
2014
2015EventStoreCatchUpSubscription.prototype._serverSubscriptionDropped = function(subscription, reason, err) {
2016 this._enqueueSubscriptionDropNotification(reason, err);
2017};
2018
2019EventStoreCatchUpSubscription.prototype._enqueueSubscriptionDropNotification = function(reason, error) {
2020 // if drop data was already set -- no need to enqueue drop again, somebody did that already
2021 if (this._dropData) return;
2022 this._dropData = {reason: reason, error: error};
2023 this._liveQueue.push(new DropSubscriptionEvent());
2024 if (this._allowProcessing) this._ensureProcessingPushQueue();
2025};
2026
2027EventStoreCatchUpSubscription.prototype._ensureProcessingPushQueue = function() {
2028 if (this._isProcessing) return;
2029
2030 this._isProcessing = true;
2031 setImmediate(this._processLiveQueue.bind(this));
2032};
2033
2034EventStoreCatchUpSubscription.prototype._processLiveQueue = function() {
2035 var ev = this._liveQueue.shift();
2036 if (!ev) {
2037 this._isProcessing = false;
2038 return;
2039 }
2040 if (ev instanceof DropSubscriptionEvent) {
2041 if (!this._dropData) this._dropData = {reason: SubscriptionDropReason.Unknown, error: new Error("Drop reason not specified.")};
2042 this._dropSubscription(this._dropData.reason, this._dropData.error);
2043 this._isProcessing = false;
2044 return;
2045 }
2046 var promise;
2047 try {
2048 promise = this._tryProcess(ev);
2049 }
2050 catch(err) {
2051 this._dropSubscription(SubscriptionDropReason.EventHandlerException, err);
2052 this._isProcessing = false;
2053 return;
2054 }
2055 if (promise && promise.then) {
2056 var self = this;
2057 promise
2058 .then(this._processLiveQueue.bind(this), function(err) {
2059 self._dropSubscription(SubscriptionDropReason.EventHandlerException, err);
2060 self._isProcessing = false;
2061 });
2062 } else {
2063 setImmediate(this._processLiveQueue.bind(this));
2064 }
2065};
2066
2067EventStoreCatchUpSubscription.prototype._dropSubscription = function(reason, error) {
2068 if (this._isDropped) return;
2069
2070 this._isDropped = true;
2071 if (this._verbose) {
2072 this._log.debug("Catch-up Subscription to %s: dropping subscription, reason: %s %s.",
2073 this._streamId || '<all>', reason, error);
2074 }
2075
2076 if (this._subscription) this._subscription.unsubscribe();
2077 if (this._subscriptionDropped) {
2078 try {
2079 this._subscriptionDropped(this, reason, error);
2080 } catch (e) {
2081 this._log.error(e, "Catch-up Subscription to %s: subscriptionDropped callback failed.", this._streamId || '<all>');
2082 }
2083 }
2084 this._stopped = true;
2085};
2086
2087module.exports = EventStoreCatchUpSubscription;
2088
2089/***/ }),
2090/* 32 */
2091/***/ (function(module, exports) {
2092
2093const PersistentSubscriptionNakEventAction = Object.freeze({
2094 Unknown: 0,
2095 Park: 1,
2096 Retry: 2,
2097 Skip: 3,
2098 Stop: 4,
2099 isValid: function(value) {
2100 for(var k in PersistentSubscriptionNakEventAction) {
2101 if (PersistentSubscriptionNakEventAction[k] === value) return true;
2102 }
2103 return false;
2104 }
2105});
2106
2107module.exports = PersistentSubscriptionNakEventAction;
2108
2109/***/ }),
2110/* 33 */
2111/***/ (function(module, exports) {
2112
2113module.exports = require("http");
2114
2115/***/ }),
2116/* 34 */
2117/***/ (function(module, exports) {
2118
2119function NoopLogger() {
2120}
2121NoopLogger.prototype.error = function() {};
2122NoopLogger.prototype.debug = function() {};
2123NoopLogger.prototype.info = function() {};
2124
2125module.exports = NoopLogger;
2126
2127/***/ }),
2128/* 35 */
2129/***/ (function(module, exports, __webpack_require__) {
2130
2131const util = __webpack_require__(0);
2132
2133function ProjectionCommandFailedError(httpStatusCode, message) {
2134 Error.captureStackTrace(this, this.constructor);
2135 this.httpStatusCode = httpStatusCode;
2136 this.message = message;
2137}
2138util.inherits(ProjectionCommandFailedError, Error);
2139
2140module.exports = ProjectionCommandFailedError;
2141
2142/***/ }),
2143/* 36 */
2144/***/ (function(module, exports, __webpack_require__) {
2145
2146var EventData = __webpack_require__(22);
2147var results = __webpack_require__(3);
2148
2149const expectedVersion = {
2150 any: -2,
2151 noStream: -1,
2152 emptyStream: -1,
2153 streamExists: -4
2154};
2155Object.freeze(expectedVersion);
2156
2157const positions = {
2158 start: new results.Position(0, 0),
2159 end: new results.Position(-1, -1)
2160};
2161Object.freeze(positions);
2162
2163const streamPosition = {
2164 start: 0,
2165 end: -1
2166};
2167Object.freeze(streamPosition);
2168
2169/**
2170 * Create an EventData object from JavaScript event/metadata that will be serialized as json
2171 * @public
2172 * @param {string} eventId Event UUID
2173 * @param {object} event Event object
2174 * @param {object} [metadata] Event metadata
2175 * @param {string} [type] Event type
2176 * @returns {EventData}
2177 */
2178function createJsonEventData(eventId, event, metadata, type) {
2179 if (!event || typeof event !== 'object') throw new TypeError("data must be an object.");
2180
2181 var eventBuf = new Buffer(JSON.stringify(event));
2182 var metaBuf = metadata ? new Buffer(JSON.stringify(metadata)) : null;
2183 return new EventData(eventId, type || event.constructor.name, true, eventBuf, metaBuf);
2184}
2185
2186/**
2187 * Create an EventData object from event/metadata buffer(s)
2188 * @public
2189 * @param {string} eventId Event UUID
2190 * @param {string} type Event type
2191 * @param {boolean} isJson is buffer(s) content json
2192 * @param {Buffer} data Data buffer
2193 * @param {Buffer} [metadata] Metadata buffer
2194 * @returns {EventData}
2195 */
2196function createEventData(eventId, type, isJson, data, metadata) {
2197 return new EventData(eventId, type, isJson, data, metadata);
2198}
2199
2200// Expose classes
2201exports.Position = results.Position;
2202exports.UserCredentials = __webpack_require__(37);
2203exports.PersistentSubscriptionSettings = __webpack_require__(38);
2204exports.SystemConsumerStrategies = __webpack_require__(17);
2205exports.GossipSeed = __webpack_require__(23);
2206exports.EventStoreConnection = __webpack_require__(24);
2207exports.ProjectionsManager = __webpack_require__(75);
2208// Expose errors
2209exports.WrongExpectedVersionError = __webpack_require__(15);
2210exports.StreamDeletedError = __webpack_require__(16);
2211exports.AccessDeniedError = __webpack_require__(7);
2212exports.ProjectionCommandFailedError = __webpack_require__(35);
2213// Expose enums/constants
2214exports.expectedVersion = expectedVersion;
2215exports.positions = positions;
2216exports.streamPosition = streamPosition;
2217exports.systemMetadata = __webpack_require__(78);
2218exports.eventReadStatus = results.EventReadStatus;
2219exports.sliceReadStatus = __webpack_require__(21);
2220exports.persistentSubscriptionNakEventAction =
2221exports.PersistentSubscriptionNakEventAction = __webpack_require__(32);
2222// Expose loggers
2223exports.NoopLogger = __webpack_require__(34);
2224exports.FileLogger = __webpack_require__(79);
2225// Expose Helper functions
2226exports.createConnection = __webpack_require__(24).create;
2227exports.createJsonEventData = createJsonEventData;
2228exports.createEventData = createEventData;
2229
2230
2231/***/ }),
2232/* 37 */
2233/***/ (function(module, exports, __webpack_require__) {
2234
2235var ensure = __webpack_require__(8);
2236
2237/**
2238 * @param {string} username
2239 * @param {string} password
2240 * @constructor
2241 * @property {string} username
2242 * @property {string} password
2243 */
2244function UserCredentials(username, password) {
2245 ensure.notNullOrEmpty(username, 'username');
2246 ensure.notNullOrEmpty(password, 'password');
2247 this.username = username;
2248 this.password = password;
2249 Object.freeze(this);
2250}
2251
2252module.exports = UserCredentials;
2253
2254/***/ }),
2255/* 38 */
2256/***/ (function(module, exports, __webpack_require__) {
2257
2258var SystemConsumerStrategies = __webpack_require__(17);
2259var ensure = __webpack_require__(8);
2260var Long = __webpack_require__(9);
2261
2262function PersistentSubscriptionSettings(
2263 resolveLinkTos, startFrom, extraStatistics, messageTimeout,
2264 maxRetryCount, liveBufferSize, readBatchSize, historyBufferSize,
2265 checkPointAfter, minCheckPointCount, maxCheckPointCount,
2266 maxSubscriberCount, namedConsumerStrategy
2267) {
2268 ensure.isLongOrInteger(startFrom);
2269 startFrom = Long.fromValue(startFrom);
2270
2271 this.resolveLinkTos = resolveLinkTos;
2272 this.startFrom = startFrom;
2273 this.extraStatistics = extraStatistics;
2274 this.messageTimeout = messageTimeout;
2275 this.maxRetryCount = maxRetryCount;
2276 this.liveBufferSize = liveBufferSize;
2277 this.readBatchSize = readBatchSize;
2278 this.historyBufferSize = historyBufferSize;
2279 this.checkPointAfter = checkPointAfter;
2280 this.minCheckPointCount = minCheckPointCount;
2281 this.maxCheckPointCount = maxCheckPointCount;
2282 this.maxSubscriberCount = maxSubscriberCount;
2283 this.namedConsumerStrategy = namedConsumerStrategy;
2284}
2285
2286PersistentSubscriptionSettings.create = function() {
2287 return new PersistentSubscriptionSettings(false, -1, false, 30000, 500, 500, 10, 20, 2000, 10, 1000, 0, SystemConsumerStrategies.RoundRobin);
2288};
2289
2290module.exports = PersistentSubscriptionSettings;
2291
2292/***/ }),
2293/* 39 */
2294/***/ (function(module, exports, __webpack_require__) {
2295
2296var util = __webpack_require__(0);
2297var uuid = __webpack_require__(18);
2298var Long = __webpack_require__(9);
2299var EventEmitter = __webpack_require__(25).EventEmitter;
2300var ensure = __webpack_require__(8);
2301
2302var messages = __webpack_require__(20);
2303var EventStoreConnectionLogicHandler = __webpack_require__(40);
2304
2305var DeleteStreamOperation = __webpack_require__(53);
2306var AppendToStreamOperation = __webpack_require__(54);
2307var StartTransactionOperation = __webpack_require__(55);
2308var TransactionalWriteOperation = __webpack_require__(56);
2309var CommitTransactionOperation = __webpack_require__(57);
2310var ReadEventOperation = __webpack_require__(58);
2311var ReadStreamEventsForwardOperation = __webpack_require__(59);
2312var ReadStreamEventsBackwardOperation = __webpack_require__(60);
2313var ReadAllEventsForwardOperation = __webpack_require__(61);
2314var ReadAllEventsBackwardOperation = __webpack_require__(62);
2315var CreatePersistentSubscriptionOperation = __webpack_require__(63);
2316var UpdatePersistentSubscriptionOperation = __webpack_require__(64);
2317var DeletePersistentSubscriptionOperation = __webpack_require__(65);
2318
2319var EventStoreTransaction = __webpack_require__(29);
2320var EventStoreStreamCatchUpSubscription = __webpack_require__(66);
2321var EventStoreAllCatchUpSubscription = __webpack_require__(67);
2322var EventStorePersistentSubscription = __webpack_require__(68);
2323
2324var results = __webpack_require__(3);
2325var systemStreams = __webpack_require__(70);
2326var systemEventTypes = __webpack_require__(71);
2327var EventData = __webpack_require__(22);
2328
2329const MaxReadSize = 4096;
2330
2331/**
2332 * @protected
2333 * @constructor
2334 */
2335function EventStoreNodeConnection(settings, clusterSettings, endpointDiscoverer, connectionName) {
2336 EventEmitter.call(this);
2337 this._connectionName = connectionName || ['ES-', uuid.v4()].join('');
2338 this._settings = settings;
2339 this._clusterSettings = clusterSettings;
2340 this._endpointDiscoverer = endpointDiscoverer;
2341 this._handler = new EventStoreConnectionLogicHandler(this, settings);
2342
2343 var self = this;
2344 this._handler.on('connected', function(e) {
2345 self.emit('connected', e);
2346 });
2347 this._handler.on('disconnected', function(e) {
2348 self.emit('disconnected', e);
2349 });
2350 this._handler.on('reconnecting', function(e) {
2351 self.emit('reconnecting', e);
2352 });
2353 this._handler.on('closed', function(e) {
2354 self.emit('closed', e);
2355 });
2356 this._handler.on('error', function(e) {
2357 self.emit('error', e);
2358 });
2359 this._handler.on('heartbeatInfo', function(e) {
2360 self.emit('heartbeatInfo', e);
2361 });
2362}
2363util.inherits(EventStoreNodeConnection, EventEmitter);
2364
2365Object.defineProperty(EventStoreNodeConnection.prototype, 'connectionName', {
2366 get: function() {
2367 return this._connectionName;
2368 }
2369});
2370
2371/**
2372 * Start connection task
2373 * @public
2374 * @returns {Promise}
2375 */
2376EventStoreNodeConnection.prototype.connect = function() {
2377 var self = this;
2378 return new Promise(function(resolve, reject) {
2379 function cb(err) {
2380 if (err) return reject(err);
2381 resolve();
2382 }
2383 var startConnectionMessage = new messages.StartConnectionMessage(cb, self._endpointDiscoverer);
2384 self._handler.enqueueMessage(startConnectionMessage);
2385 });
2386};
2387
2388/**
2389 * Close connection
2390 * @public
2391 */
2392EventStoreNodeConnection.prototype.close = function() {
2393 this._handler.enqueueMessage(new messages.CloseConnectionMessage("Connection close requested by client.", null));
2394};
2395
2396/**
2397 * Delete a stream (async)
2398 * @public
2399 * @param {string} stream
2400 * @param {Long|number} expectedVersion
2401 * @param {boolean} [hardDelete]
2402 * @param {UserCredentials} [userCredentials]
2403 * @returns {Promise.<DeleteResult>}
2404 */
2405EventStoreNodeConnection.prototype.deleteStream = function(stream, expectedVersion, hardDelete, userCredentials) {
2406 ensure.notNullOrEmpty(stream, "stream");
2407 ensure.isLongOrInteger(expectedVersion, "expectedVersion");
2408 expectedVersion = Long.fromValue(expectedVersion);
2409 hardDelete = Boolean(hardDelete);
2410 userCredentials = userCredentials || null;
2411
2412 var self = this;
2413 return new Promise(function(resolve, reject) {
2414 function cb(err, result) {
2415 if (err) return reject(err);
2416 resolve(result);
2417 }
2418
2419 var deleteStreamOperation = new DeleteStreamOperation(
2420 self._settings.log, cb, self._settings.requireMaster, stream, expectedVersion, hardDelete, userCredentials);
2421 self._enqueueOperation(deleteStreamOperation);
2422 });
2423};
2424
2425/**
2426 * Append events to a stream (async)
2427 * @public
2428 * @param {string} stream The name of the stream to which to append.
2429 * @param {Long|number} expectedVersion The version at which we currently expect the stream to be in order that an optimistic concurrency check can be performed.
2430 * @param {EventData[]|EventData} events The event(s) to append.
2431 * @param {UserCredentials} [userCredentials] User credentials
2432 * @returns {Promise.<WriteResult>}
2433 */
2434EventStoreNodeConnection.prototype.appendToStream = function(stream, expectedVersion, events, userCredentials) {
2435 ensure.notNullOrEmpty(stream, "stream");
2436 ensure.isLongOrInteger(expectedVersion, "expectedVersion");
2437 expectedVersion = Long.fromValue(expectedVersion);
2438 if (!Array.isArray(events)) events = [events];
2439 ensure.isArrayOf(EventData, events, "events");
2440 userCredentials = userCredentials || null;
2441
2442 var self = this;
2443 return new Promise(function(resolve, reject) {
2444 function cb(err, result) {
2445 if (err) return reject(err);
2446 resolve(result);
2447 }
2448 var operation = new AppendToStreamOperation(self._settings.log, cb, self._settings.requireMaster, stream,
2449 expectedVersion, events, userCredentials);
2450 self._enqueueOperation(operation);
2451 });
2452};
2453
2454/**
2455 * Start a transaction (async)
2456 * @public
2457 * @param {string} stream
2458 * @param {Long|number} expectedVersion
2459 * @param {UserCredentials} [userCredentials]
2460 * @returns {Promise.<EventStoreTransaction>}
2461 */
2462EventStoreNodeConnection.prototype.startTransaction = function(stream, expectedVersion, userCredentials) {
2463 ensure.notNullOrEmpty(stream, "stream");
2464 ensure.isLongOrInteger(expectedVersion, "expectedVersion");
2465 expectedVersion = Long.fromValue(expectedVersion);
2466 userCredentials = userCredentials || null;
2467
2468 var self = this;
2469 return new Promise(function(resolve, reject) {
2470 function cb(err, result) {
2471 if (err) return reject(err);
2472 resolve(result);
2473 }
2474 var operation = new StartTransactionOperation(self._settings.log, cb, self._settings.requireMaster, stream,
2475 expectedVersion, self, userCredentials);
2476 self._enqueueOperation(operation);
2477 });
2478};
2479
2480/**
2481 * Continue a transaction
2482 * @public
2483 * @param {number} transactionId
2484 * @param {UserCredentials} userCredentials
2485 * @returns {EventStoreTransaction}
2486 */
2487EventStoreNodeConnection.prototype.continueTransaction = function(transactionId, userCredentials) {
2488 ensure.nonNegative(transactionId, "transactionId");
2489
2490 return new EventStoreTransaction(transactionId, userCredentials, this);
2491};
2492
2493EventStoreNodeConnection.prototype.transactionalWrite = function(transaction, events, userCredentials) {
2494 ensure.isTypeOf(EventStoreTransaction, transaction, "transaction");
2495 ensure.isArrayOf(EventData, events, "events");
2496 userCredentials = userCredentials || null;
2497
2498 var self = this;
2499 return new Promise(function(resolve, reject) {
2500 function cb(err) {
2501 if (err) return reject(err);
2502 resolve();
2503 }
2504 var operation = new TransactionalWriteOperation(self._settings.log, cb, self._settings.requireMaster,
2505 transaction.transactionId, events, userCredentials);
2506 self._enqueueOperation(operation);
2507 });
2508};
2509
2510/**
2511 * Commit a transaction
2512 * @public
2513 * @param transaction
2514 * @param userCredentials
2515 * @returns {Promise.<WriteResult>}
2516 */
2517EventStoreNodeConnection.prototype.commitTransaction = function(transaction, userCredentials) {
2518 ensure.isTypeOf(EventStoreTransaction, transaction, "transaction");
2519
2520 var self = this;
2521 return new Promise(function(resolve, reject) {
2522 function cb(err, result) {
2523 if (err) return reject(err);
2524 resolve(result);
2525 }
2526 var operation = new CommitTransactionOperation(self._settings.log, cb, self._settings.requireMaster,
2527 transaction.transactionId, userCredentials);
2528 self._enqueueOperation(operation);
2529 });
2530};
2531
2532/**
2533 * Read a single event (async)
2534 * @public
2535 * @param {string} stream
2536 * @param {Long|number} eventNumber
2537 * @param {boolean} [resolveLinkTos]
2538 * @param {UserCredentials} [userCredentials]
2539 * @returns {Promise.<EventReadResult>}
2540 */
2541EventStoreNodeConnection.prototype.readEvent = function(stream, eventNumber, resolveLinkTos, userCredentials) {
2542 ensure.notNullOrEmpty(stream, "stream");
2543 ensure.isLongOrInteger(eventNumber, "eventNumber");
2544 eventNumber = Long.fromValue(eventNumber);
2545 resolveLinkTos = Boolean(resolveLinkTos);
2546 userCredentials = userCredentials || null;
2547
2548 if (typeof stream !== 'string' || stream === '') throw new TypeError("stream must be an non-empty string.");
2549 if (eventNumber.compare(-1) < 0) throw new Error("eventNumber out of range.");
2550 if (resolveLinkTos && typeof resolveLinkTos !== 'boolean') throw new TypeError("resolveLinkTos must be a boolean.");
2551
2552 var self = this;
2553 return new Promise(function(resolve, reject){
2554 function cb(err, result) {
2555 if (err) return reject(err);
2556 resolve(result);
2557 }
2558 var operation = new ReadEventOperation(self._settings.log, cb, stream, eventNumber, resolveLinkTos,
2559 self._settings.requireMaster, userCredentials);
2560 self._enqueueOperation(operation);
2561 });
2562};
2563
2564/**
2565 * Reading a specific stream forwards (async)
2566 * @public
2567 * @param {string} stream
2568 * @param {Long|number} start
2569 * @param {number} count
2570 * @param {boolean} [resolveLinkTos]
2571 * @param {UserCredentials} [userCredentials]
2572 * @returns {Promise.<StreamEventsSlice>}
2573 */
2574EventStoreNodeConnection.prototype.readStreamEventsForward = function(
2575 stream, start, count, resolveLinkTos, userCredentials
2576) {
2577 ensure.notNullOrEmpty(stream, "stream");
2578 ensure.isLongOrInteger(start, "start");
2579 start = Long.fromValue(start);
2580 ensure.nonNegative(start, "start");
2581 ensure.isInteger(count, "count");
2582 ensure.positive(count, "count");
2583 if (count > MaxReadSize) throw new Error(util.format("Count should be less than %d. For larger reads you should page.", MaxReadSize));
2584 resolveLinkTos = Boolean(resolveLinkTos);
2585 userCredentials = userCredentials || null;
2586
2587 var self = this;
2588 return new Promise(function(resolve, reject) {
2589 function cb(err, result) {
2590 if (err) return reject(err);
2591 resolve(result);
2592 }
2593 var operation = new ReadStreamEventsForwardOperation(self._settings.log, cb, stream, start, count,
2594 resolveLinkTos, self._settings.requireMaster, userCredentials);
2595 self._enqueueOperation(operation);
2596 });
2597};
2598
2599/**
2600 * Reading a specific stream backwards (async)
2601 * @public
2602 * @param {string} stream
2603 * @param {Long|number} start
2604 * @param {number} count
2605 * @param {boolean} [resolveLinkTos]
2606 * @param {UserCredentials} [userCredentials]
2607 * @returns {Promise.<StreamEventsSlice>}
2608 */
2609EventStoreNodeConnection.prototype.readStreamEventsBackward = function(
2610 stream, start, count, resolveLinkTos, userCredentials
2611) {
2612 ensure.notNullOrEmpty(stream, "stream");
2613 ensure.isLongOrInteger(start, "start");
2614 start = Long.fromValue(start);
2615 ensure.isInteger(count, "count");
2616 ensure.positive(count, "count");
2617 if (count > MaxReadSize) throw new Error(util.format("Count should be less than %d. For larger reads you should page.", MaxReadSize));
2618 resolveLinkTos = Boolean(resolveLinkTos);
2619 userCredentials = userCredentials || null;
2620
2621 var self = this;
2622 return new Promise(function(resolve, reject) {
2623 function cb(err, result) {
2624 if (err) return reject(err);
2625 resolve(result);
2626 }
2627 var operation = new ReadStreamEventsBackwardOperation(self._settings.log, cb, stream, start, count,
2628 resolveLinkTos, self._settings.requireMaster, userCredentials);
2629 self._enqueueOperation(operation);
2630 });
2631};
2632
2633/**
2634 * Reading all events forwards (async)
2635 * @public
2636 * @param {Position} position
2637 * @param {number} maxCount
2638 * @param {boolean} [resolveLinkTos]
2639 * @param {UserCredentials} [userCredentials]
2640 * @returns {Promise.<AllEventsSlice>}
2641 */
2642EventStoreNodeConnection.prototype.readAllEventsForward = function(
2643 position, maxCount, resolveLinkTos, userCredentials
2644) {
2645 ensure.isTypeOf(results.Position, position, "position");
2646 ensure.isInteger(maxCount, "maxCount");
2647 ensure.positive(maxCount, "maxCount");
2648 if (maxCount > MaxReadSize) throw new Error(util.format("Count should be less than %d. For larger reads you should page.", MaxReadSize));
2649 resolveLinkTos = Boolean(resolveLinkTos);
2650 userCredentials = userCredentials || null;
2651
2652 var self = this;
2653 return new Promise(function(resolve, reject) {
2654 function cb(err, result) {
2655 if (err) return reject(err);
2656 resolve(result);
2657 }
2658 var operation = new ReadAllEventsForwardOperation(self._settings.log, cb, position, maxCount,
2659 resolveLinkTos, self._settings.requireMaster, userCredentials);
2660 self._enqueueOperation(operation);
2661 });
2662};
2663
2664/**
2665 * Reading all events backwards (async)
2666 * @public
2667 * @param {Position} position
2668 * @param {number} maxCount
2669 * @param {boolean} [resolveLinkTos]
2670 * @param {UserCredentials} [userCredentials]
2671 * @returns {Promise.<AllEventsSlice>}
2672 */
2673EventStoreNodeConnection.prototype.readAllEventsBackward = function(
2674 position, maxCount, resolveLinkTos, userCredentials
2675) {
2676 ensure.isTypeOf(results.Position, position, "position");
2677 ensure.isInteger(maxCount, "maxCount");
2678 ensure.positive(maxCount, "maxCount");
2679 if (maxCount > MaxReadSize) throw new Error(util.format("Count should be less than %d. For larger reads you should page.", MaxReadSize));
2680 resolveLinkTos = Boolean(resolveLinkTos);
2681 userCredentials = userCredentials || null;
2682
2683 var self = this;
2684 return new Promise(function(resolve, reject) {
2685 function cb(err, result) {
2686 if (err) return reject(err);
2687 resolve(result);
2688 }
2689 var operation = new ReadAllEventsBackwardOperation(self._settings.log, cb, position, maxCount,
2690 resolveLinkTos || false, self._settings.requireMaster, userCredentials || null);
2691 self._enqueueOperation(operation);
2692 });
2693};
2694
2695/**
2696 * Subscribe to a stream (async)
2697 * @public
2698 * @param {!string} stream
2699 * @param {!boolean} resolveLinkTos
2700 * @param {function} eventAppeared
2701 * @param {function} [subscriptionDropped]
2702 * @param {UserCredentials} [userCredentials]
2703 * @returns {Promise.<EventStoreSubscription>}
2704 */
2705EventStoreNodeConnection.prototype.subscribeToStream = function(
2706 stream, resolveLinkTos, eventAppeared, subscriptionDropped, userCredentials
2707) {
2708 ensure.notNullOrEmpty(stream, "stream");
2709 ensure.isTypeOf(Function, eventAppeared, "eventAppeared");
2710 if (subscriptionDropped) ensure.isTypeOf(Function, subscriptionDropped, "subscriptionDropped");
2711
2712 var self = this;
2713 return new Promise(function(resolve,reject) {
2714 function cb(err, result) {
2715 if (err) return reject(err);
2716 resolve(result);
2717 }
2718 self._handler.enqueueMessage(
2719 new messages.StartSubscriptionMessage(
2720 cb, stream, !!resolveLinkTos, userCredentials || null, eventAppeared, subscriptionDropped || null,
2721 self._settings.maxRetries, self._settings.operationTimeout));
2722 });
2723};
2724
2725/**
2726 * Subscribe to a stream from position
2727 * @public
2728 * @param {!string} stream
2729 * @param {?number|Position} lastCheckpoint
2730 * @param {!boolean} resolveLinkTos
2731 * @param {!function} eventAppeared
2732 * @param {function} [liveProcessingStarted]
2733 * @param {function} [subscriptionDropped]
2734 * @param {UserCredentials} [userCredentials]
2735 * @param {!number} [readBatchSize]
2736 * @returns {EventStoreStreamCatchUpSubscription}
2737 */
2738EventStoreNodeConnection.prototype.subscribeToStreamFrom = function(
2739 stream, lastCheckpoint, resolveLinkTos, eventAppeared, liveProcessingStarted, subscriptionDropped,
2740 userCredentials, readBatchSize
2741) {
2742 if (typeof stream !== 'string' || stream === '') throw new TypeError("stream must be a non-empty string.");
2743 if (lastCheckpoint !== null) {
2744 ensure.isLongOrInteger(lastCheckpoint);
2745 lastCheckpoint = Long.fromValue(lastCheckpoint);
2746 }
2747 if (typeof eventAppeared !== 'function') throw new TypeError("eventAppeared must be a function.");
2748
2749 var catchUpSubscription =
2750 new EventStoreStreamCatchUpSubscription(this, this._settings.log, stream, lastCheckpoint,
2751 resolveLinkTos, userCredentials || null, eventAppeared,
2752 liveProcessingStarted || null, subscriptionDropped || null, this._settings.verboseLogging,
2753 readBatchSize);
2754 catchUpSubscription.start();
2755 return catchUpSubscription;
2756};
2757
2758/**
2759 * Subscribe to all (async)
2760 * @public
2761 * @param {!boolean} resolveLinkTos
2762 * @param {!function} eventAppeared
2763 * @param {function} [subscriptionDropped]
2764 * @param {UserCredentials} [userCredentials]
2765 * @returns {Promise.<EventStoreSubscription>}
2766 */
2767EventStoreNodeConnection.prototype.subscribeToAll = function(
2768 resolveLinkTos, eventAppeared, subscriptionDropped, userCredentials
2769) {
2770 if (typeof eventAppeared !== 'function') throw new TypeError("eventAppeared must be a function.");
2771
2772 var self = this;
2773 return new Promise(function(resolve, reject) {
2774 function cb(err, result) {
2775 if (err) return reject(err);
2776 resolve(result);
2777 }
2778 self._handler.enqueueMessage(
2779 new messages.StartSubscriptionMessage(
2780 cb, '', resolveLinkTos, userCredentials || null, eventAppeared, subscriptionDropped || null,
2781 self._settings.maxRetries, self._settings.operationTimeout));
2782 });
2783};
2784
2785/**
2786 * Subscribe to all from
2787 * @public
2788 * @param {?Position} lastCheckpoint
2789 * @param {!boolean} resolveLinkTos
2790 * @param {!function} eventAppeared
2791 * @param {function} [liveProcessingStarted]
2792 * @param {function} [subscriptionDropped]
2793 * @param {UserCredentials} [userCredentials]
2794 * @param {!number} [readBatchSize]
2795 * @returns {EventStoreAllCatchUpSubscription}
2796 */
2797EventStoreNodeConnection.prototype.subscribeToAllFrom = function(
2798 lastCheckpoint, resolveLinkTos, eventAppeared, liveProcessingStarted, subscriptionDropped,
2799 userCredentials, readBatchSize
2800) {
2801 ensure.isTypeOf(results.Position, lastCheckpoint, "lastCheckpoint", true);
2802 ensure.isTypeOf(Function, eventAppeared, "eventAppeared", false);
2803 if (liveProcessingStarted) ensure.isTypeOf(Function, liveProcessingStarted, "liveProcessingStarted", false);
2804 if (subscriptionDropped) ensure.isTypeOf(Function, subscriptionDropped, "subscriptionDropped", false);
2805
2806 var catchUpSubscription =
2807 new EventStoreAllCatchUpSubscription(this, this._settings.log, lastCheckpoint, resolveLinkTos,
2808 userCredentials || null, eventAppeared, liveProcessingStarted || null,
2809 subscriptionDropped || null, this._settings.verboseLogging, readBatchSize || 500);
2810 catchUpSubscription.start();
2811 return catchUpSubscription;
2812};
2813
2814/**
2815 * Subscribe to a persistent subscription
2816 * @public
2817 * @param {string} stream
2818 * @param {string} groupName
2819 * @param {function} eventAppeared
2820 * @param {function} [subscriptionDropped]
2821 * @param {UserCredentials} [userCredentials]
2822 * @param {number} [bufferSize]
2823 * @param {boolean} [autoAck]
2824 * @return {Promise<EventStorePersistentSubscription>}
2825 */
2826EventStoreNodeConnection.prototype.connectToPersistentSubscription = function(
2827 stream, groupName, eventAppeared, subscriptionDropped, userCredentials, bufferSize, autoAck
2828) {
2829 ensure.notNullOrEmpty(groupName, "groupName");
2830 ensure.notNullOrEmpty(stream, "stream");
2831 ensure.notNull(eventAppeared, "eventAppeared");
2832
2833 subscriptionDropped = subscriptionDropped || null;
2834 userCredentials = userCredentials || null;
2835 bufferSize = bufferSize === undefined ? 10 : bufferSize;
2836 autoAck = autoAck === undefined ? true : Boolean(autoAck);
2837
2838 var subscription = new EventStorePersistentSubscription(
2839 groupName, stream, eventAppeared, subscriptionDropped, userCredentials, this._settings.log,
2840 this._settings.verboseLogging, this._settings, this._handler, bufferSize, autoAck);
2841 return subscription.start();
2842};
2843
2844/**
2845 * Create a persistent subscription
2846 * @public
2847 * @param {string} stream
2848 * @param {string} groupName
2849 * @param {PersistentSubscriptionSettings} settings
2850 * @param {UserCredentials} [userCredentials]
2851 * @returns {Promise.<PersistentSubscriptionCreateResult>}
2852 */
2853EventStoreNodeConnection.prototype.createPersistentSubscription = function(stream, groupName, settings, userCredentials) {
2854 ensure.notNullOrEmpty(stream, "stream");
2855 ensure.notNullOrEmpty(groupName, "groupName");
2856 ensure.notNull(settings, "settings");
2857
2858 var self = this;
2859 return new Promise(function(resolve, reject){
2860 function cb(err, result) {
2861 if (err) return reject(err);
2862 resolve(result);
2863 }
2864 self._enqueueOperation(
2865 new CreatePersistentSubscriptionOperation(self._settings.log, cb, stream, groupName, settings, userCredentials || null));
2866 });
2867};
2868
2869/**
2870 * Update a persistent subscription
2871 * @public
2872 * @param {string} stream
2873 * @param {string} groupName
2874 * @param {PersistentSubscriptionSettings} settings
2875 * @param {UserCredentials} [userCredentials]
2876 * @returns {Promise.<PersistentSubscriptionUpdateResult>}
2877 */
2878EventStoreNodeConnection.prototype.updatePersistentSubscription = function(stream, groupName, settings, userCredentials) {
2879 ensure.notNullOrEmpty(stream, "stream");
2880 ensure.notNullOrEmpty(groupName, "groupName");
2881 ensure.notNull(settings, "settings");
2882 var self = this;
2883 return new Promise(function(resolve, reject) {
2884 function cb(err, result) {
2885 if (err) return reject(err);
2886 resolve(result);
2887 }
2888 self._enqueueOperation(
2889 new UpdatePersistentSubscriptionOperation(self._settings.log, cb, stream, groupName, settings, userCredentials || null));
2890 });
2891};
2892
2893/**
2894 * Delete a persistent subscription
2895 * @public
2896 * @param {string} stream
2897 * @param {string} groupName
2898 * @param {UserCredentials} [userCredentials]
2899 * @returns {Promise.<PersistentSubscriptionDeleteResult>}
2900 */
2901EventStoreNodeConnection.prototype.deletePersistentSubscription = function(stream, groupName, userCredentials) {
2902 ensure.notNullOrEmpty(stream, "stream");
2903 ensure.notNullOrEmpty(groupName, "groupName");
2904 var self = this;
2905 return new Promise(function(resolve, reject) {
2906 function cb(err, result) {
2907 if (err) return reject(err);
2908 resolve(result);
2909 }
2910 self._enqueueOperation(
2911 new DeletePersistentSubscriptionOperation(self._settings.log, cb, stream, groupName, userCredentials || null));
2912 });
2913};
2914
2915/**
2916 * Set stream metadata
2917 * @private
2918 */
2919EventStoreNodeConnection.prototype.setStreamMetadata = function() {
2920 //TODO: set stream metadata (non-raw)
2921 throw new Error("Not implemented.");
2922};
2923
2924/**
2925 * Set stream metadata with raw object (async)
2926 * @public
2927 * @param {string} stream
2928 * @param {Long|number} expectedMetastreamVersion
2929 * @param {object} metadata
2930 * @param {UserCredentials} [userCredentials]
2931 * @returns {Promise.<WriteResult>}
2932 */
2933EventStoreNodeConnection.prototype.setStreamMetadataRaw = function(
2934 stream, expectedMetastreamVersion, metadata, userCredentials
2935) {
2936 ensure.notNullOrEmpty(stream, "stream");
2937 if (systemStreams.isMetastream(stream)) {
2938 throw new Error(util.format("Setting metadata for metastream '%s' is not supported.", stream));
2939 }
2940 ensure.isLongOrInteger(expectedMetastreamVersion, "expectedMetastreamVersion");
2941 expectedMetastreamVersion = Long.fromValue(expectedMetastreamVersion);
2942 var self = this;
2943 return new Promise(function(resolve, reject) {
2944 function cb(err, result) {
2945 if (err) return reject(err);
2946 resolve(result);
2947 }
2948 var data = metadata ? new Buffer(JSON.stringify(metadata)) : null;
2949 var metaevent = new EventData(uuid.v4(), systemEventTypes.StreamMetadata, true, data, null);
2950 self._enqueueOperation(
2951 new AppendToStreamOperation(self._settings.log, cb, self._settings.requireMaster,
2952 systemStreams.metastreamOf(stream), expectedMetastreamVersion,
2953 [metaevent], userCredentials));
2954 });
2955};
2956
2957/**
2958 * Get stream metadata
2959 * @private
2960 * @param stream
2961 * @param userCredentials
2962 */
2963EventStoreNodeConnection.prototype.getStreamMetadata = function(stream, userCredentials) {
2964 //TODO: get stream metadata (non-raw)
2965 throw new Error("Not implemented.");
2966};
2967
2968/**
2969 * Get stream metadata as raw object (async)
2970 * @public
2971 * @param {string} stream
2972 * @param {UserCredentials} [userCredentials]
2973 * @returns {Promise.<RawStreamMetadataResult>}
2974 */
2975EventStoreNodeConnection.prototype.getStreamMetadataRaw = function(stream, userCredentials) {
2976 return this.readEvent(systemStreams.metastreamOf(stream), -1, false, userCredentials)
2977 .then(function(res) {
2978 switch(res.status) {
2979 case results.EventReadStatus.Success:
2980 if (res.event === null) throw new Error("Event is null while operation result is Success.");
2981 var evnt = res.event.originalEvent;
2982 var version = evnt ? evnt.eventNumber : -1;
2983 var data = evnt ? JSON.parse(evnt.data.toString()) : null;
2984 return new results.RawStreamMetadataResult(stream, false, Long.fromValue(version), data);
2985 case results.EventReadStatus.NotFound:
2986 case results.EventReadStatus.NoStream:
2987 return new results.RawStreamMetadataResult(stream, false, Long.fromValue(-1), null);
2988 case results.EventReadStatus.StreamDeleted:
2989 return new results.RawStreamMetadataResult(stream, true, Long.fromValue(0x7fffffff), null);
2990 default:
2991 throw new Error(util.format("Unexpected ReadEventResult: %s.", res.status));
2992 }
2993 });
2994};
2995
2996/**
2997 * Set system settings
2998 * @private
2999 */
3000EventStoreNodeConnection.prototype.setSystemSettings = function() {
3001 //TODO: set system settings
3002 throw new Error("Not implemented.");
3003};
3004
3005EventStoreNodeConnection.prototype._enqueueOperation = function(operation) {
3006 var self = this;
3007 var message = new messages.StartOperationMessage(operation, self._settings.maxRetries, self._settings.operationTimeout);
3008 function tryEnqueue() {
3009 if (self._handler.totalOperationCount >= self._settings.maxQueueSize) {
3010 setTimeout(tryEnqueue, 0);
3011 return;
3012 }
3013 self._handler.enqueueMessage(message);
3014 }
3015 setImmediate(tryEnqueue)
3016};
3017
3018module.exports = EventStoreNodeConnection;
3019
3020/***/ }),
3021/* 40 */
3022/***/ (function(module, exports, __webpack_require__) {
3023
3024var util = __webpack_require__(0);
3025var uuid = __webpack_require__(18);
3026var EventEmitter = __webpack_require__(25).EventEmitter;
3027
3028var SimpleQueuedHandler = __webpack_require__(41);
3029var TcpPackageConnection = __webpack_require__(42);
3030var OperationsManager = __webpack_require__(47);
3031var SubscriptionsManager = __webpack_require__(48);
3032var VolatileSubscriptionOperation = __webpack_require__(49);
3033var ConnectToPersistentSubscriptionOperation = __webpack_require__(51);
3034var messages = __webpack_require__(20);
3035var ClientMessage = __webpack_require__(2);
3036var createBufferSegment = __webpack_require__(10);
3037
3038var TcpPackage = __webpack_require__(11);
3039var TcpCommand = __webpack_require__(1);
3040var TcpFlags = __webpack_require__(12);
3041var InspectionDecision = __webpack_require__(4);
3042
3043const ConnectionState = Object.freeze({
3044 Init: 'init',
3045 Connecting: 'connecting',
3046 Connected: 'connected',
3047 Closed: 'closed'
3048});
3049
3050const ConnectingPhase = Object.freeze({
3051 Invalid: 'invalid',
3052 Reconnecting: 'reconnecting',
3053 EndPointDiscovery: 'endpointDiscovery',
3054 ConnectionEstablishing: 'connectionEstablishing',
3055 Authentication: 'authentication',
3056 Identification: 'identification',
3057 Connected: 'connected'
3058});
3059
3060const TimerPeriod = 200;
3061const TimerTickMessage = new messages.TimerTickMessage();
3062const EmptyGuid = '00000000-0000-0000-0000-000000000000';
3063const ClientVersion = 1;
3064
3065/**
3066 * @private
3067 * @param {EventStoreNodeConnection} esConnection
3068 * @param {Object} settings
3069 * @constructor
3070 * @property {Number} totalOperationCount
3071 */
3072function EventStoreConnectionLogicHandler(esConnection, settings) {
3073 EventEmitter.call(this);
3074 this._esConnection = esConnection;
3075 this._settings = settings;
3076 this._queue = new SimpleQueuedHandler(this._settings.log);
3077 this._state = ConnectionState.Init;
3078 this._connectingPhase = ConnectingPhase.Invalid;
3079 this._endpointDiscoverer = null;
3080 this._connection = null;
3081 this._wasConnected = false;
3082 this._packageNumber = 0;
3083 this._authInfo = null;
3084 this._lastTimeoutsTimeStamp = 0;
3085
3086 this._operations = new OperationsManager(esConnection.connectionName, settings);
3087 this._subscriptions = new SubscriptionsManager(esConnection.connectionName, settings);
3088
3089 var self = this;
3090 this._queue.registerHandler(messages.StartConnectionMessage, function(msg) {
3091 self._startConnection(msg.cb, msg.endpointDiscoverer);
3092 });
3093 this._queue.registerHandler(messages.CloseConnectionMessage, function(msg) {
3094 self._closeConnection(msg.reason, msg.error);
3095 });
3096
3097 this._queue.registerHandler(messages.StartOperationMessage, function(msg) {
3098 self._startOperation(msg.operation, msg.maxRetries, msg.timeout);
3099 });
3100 this._queue.registerHandler(messages.StartSubscriptionMessage, function(msg) {
3101 self._startSubscription(msg);
3102 });
3103 this._queue.registerHandler(messages.StartPersistentSubscriptionMessage, function(msg) {
3104 self._startPersistentSubscription(msg);
3105 });
3106
3107 this._queue.registerHandler(messages.EstablishTcpConnectionMessage, function(msg) {
3108 self._establishTcpConnection(msg.endPoints);
3109 });
3110 this._queue.registerHandler(messages.TcpConnectionEstablishedMessage, function(msg) {
3111 self._tcpConnectionEstablished(msg.connection);
3112 });
3113 this._queue.registerHandler(messages.TcpConnectionErrorMessage, function(msg) {
3114 self._tcpConnectionError(msg.connection, msg.error);
3115 });
3116 this._queue.registerHandler(messages.TcpConnectionClosedMessage, function(msg) {
3117 self._tcpConnectionClosed(msg.connection, msg.error);
3118 });
3119 this._queue.registerHandler(messages.HandleTcpPackageMessage, function(msg) {
3120 self._handleTcpPackage(msg.connection, msg.package);
3121 });
3122
3123 this._queue.registerHandler(messages.TimerTickMessage, function(msg) {
3124 self._timerTick();
3125 });
3126
3127 this._timer = setInterval(function() {
3128 self.enqueueMessage(TimerTickMessage);
3129 }, TimerPeriod);
3130}
3131util.inherits(EventStoreConnectionLogicHandler, EventEmitter);
3132
3133Object.defineProperty(EventStoreConnectionLogicHandler.prototype, 'totalOperationCount', {
3134 get: function() {
3135 return this._operations.totalOperationCount;
3136 }
3137});
3138
3139EventStoreConnectionLogicHandler.prototype.enqueueMessage = function(msg) {
3140 if (this._settings.verboseLogging && msg !== TimerTickMessage) this._logDebug("enqueuing message %s.", msg);
3141 this._queue.enqueueMessage(msg);
3142};
3143
3144EventStoreConnectionLogicHandler.prototype._discoverEndpoint = function(cb) {
3145 this._logDebug('DiscoverEndpoint');
3146
3147 if (this._state !== ConnectionState.Connecting) return;
3148 if (this._connectingPhase !== ConnectingPhase.Reconnecting) return;
3149
3150 this._connectingPhase = ConnectingPhase.EndPointDiscovery;
3151
3152 cb = cb || function() {};
3153
3154 var self = this;
3155 this._endpointDiscoverer.discover(this._connection !== null ? this._connection.remoteEndPoint : null)
3156 .then(function(nodeEndpoints){
3157 self.enqueueMessage(new messages.EstablishTcpConnectionMessage(nodeEndpoints));
3158 cb();
3159 })
3160 .catch(function(err) {
3161 self.enqueueMessage(new messages.CloseConnectionMessage("Failed to resolve TCP end point to which to connect.", err));
3162 cb(new Error("Couldn't resolve target end point: " + err.message));
3163 });
3164};
3165
3166/**
3167 * @param {Function} cb
3168 * @param {StaticEndpointDiscoverer} endpointDiscoverer
3169 * @private
3170 */
3171EventStoreConnectionLogicHandler.prototype._startConnection = function(cb, endpointDiscoverer) {
3172 this._logDebug('StartConnection');
3173
3174 switch(this._state) {
3175 case ConnectionState.Init:
3176 this._endpointDiscoverer = endpointDiscoverer;
3177 this._state = ConnectionState.Connecting;
3178 this._connectingPhase = ConnectingPhase.Reconnecting;
3179 this._discoverEndpoint(cb);
3180 break;
3181 case ConnectionState.Connecting:
3182 case ConnectionState.Connected:
3183 return cb(new Error(['EventStoreConnection', this._esConnection.connectionName, 'is already active.'].join(' ')));
3184 case ConnectionState.Closed:
3185 return cb(new Error(['EventStoreConnection', this._esConnection.connectionName, 'is closed.'].join(' ')));
3186 default:
3187 return cb(new Error(['Unknown state:', this._state].join(' ')));
3188 }
3189};
3190
3191/**
3192 * @param {string} reason
3193 * @param {Error} [error]
3194 * @private
3195 */
3196EventStoreConnectionLogicHandler.prototype._closeConnection = function(reason, error) {
3197 if (this._state === ConnectionState.Closed) {
3198 this._logDebug("CloseConnection IGNORED because is ESConnection is CLOSED, reason %s, error %s.", reason, error ? error.stack : '');
3199 return;
3200 }
3201
3202 this._logDebug("CloseConnection, reason %s, error %s.", reason, error ? error.stack : '');
3203
3204 this._state = ConnectionState.Closed;
3205
3206 clearInterval(this._timer);
3207 this._operations.cleanUp();
3208 this._subscriptions.cleanUp();
3209 this._closeTcpConnection(reason);
3210
3211 this._logInfo("Closed. Reason: %s", reason);
3212
3213 if (error) this.emit('error', error);
3214
3215 this.emit('closed', reason);
3216};
3217
3218EventStoreConnectionLogicHandler.prototype._closeTcpConnection = function(reason) {
3219 if (!this._connection) {
3220 this._logDebug("CloseTcpConnection IGNORED because _connection === null");
3221 return;
3222 }
3223
3224 this._logDebug("CloseTcpConnection");
3225 this._connection.close(reason);
3226 this._tcpConnectionClosed(this._connection);
3227 this._connection = null;
3228};
3229
3230var _nextSeqNo = 0;
3231function createOperationItem(operation, maxRetries, timeout) {
3232 var operationItem = {
3233 seqNo: _nextSeqNo++,
3234 operation: operation,
3235 maxRetries: maxRetries,
3236 timeout: timeout,
3237 createdTime: Date.now(),
3238 correlationId: uuid.v4(),
3239 retryCount: 0,
3240 lastUpdated: Date.now()
3241 };
3242 operationItem.toString = (function() {
3243 return util.format("Operation %s (%s): %s, retry count: %d, created: %s, last updated: %s",
3244 this.operation.constructor.name, this.correlationId, this.operation, this.retryCount,
3245 new Date(this.createdTime).toISOString().substr(11,12),
3246 new Date(this.lastUpdated).toISOString().substr(11,12));
3247 }).bind(operationItem);
3248 return operationItem;
3249}
3250
3251EventStoreConnectionLogicHandler.prototype._startOperation = function(operation, maxRetries, timeout) {
3252 switch(this._state) {
3253 case ConnectionState.Init:
3254 operation.fail(new Error("EventStoreConnection '" + this._esConnection.connectionName + "' is not active."));
3255 break;
3256 case ConnectionState.Connecting:
3257 this._logDebug("StartOperation enqueue %s, %s, %d, %d.", operation.constructor.name, operation, maxRetries, timeout);
3258 this._operations.enqueueOperation(createOperationItem(operation, maxRetries, timeout));
3259 break;
3260 case ConnectionState.Connected:
3261 this._logDebug("StartOperation schedule %s, %s, %d, %d.", operation.constructor.name, operation, maxRetries, timeout);
3262 this._operations.scheduleOperation(createOperationItem(operation, maxRetries, timeout), this._connection);
3263 break;
3264 case ConnectionState.Closed:
3265 operation.fail(new Error("EventStoreConnection '" + this._esConnection.connectionName + "' is closed."));
3266 break;
3267 default:
3268 throw new Error("Unknown state: " + this._state + '.');
3269 }
3270};
3271
3272function createSubscriptionItem(operation, maxRetries, timeout) {
3273 var subscriptionItem = {
3274 operation: operation,
3275 maxRetries: maxRetries,
3276 timeout: timeout,
3277 createdTime: Date.now(),
3278 correlationId: uuid.v4(),
3279 retryCount: 0,
3280 lastUpdated: Date.now(),
3281 isSubscribed: false
3282 };
3283 subscriptionItem.toString = (function(){
3284 return util.format("Subscription %s (%s): %s, is subscribed: %s, retry count: %d, created: %s, last updated: %s",
3285 this.operation.constructor.name, this.correlationId, this.operation, this.isSubscribed, this.retryCount,
3286 new Date(this.createdTime).toISOString().substr(11,12),
3287 new Date(this.lastUpdated).toISOString().substr(11,12));
3288 }).bind(subscriptionItem);
3289 return subscriptionItem;
3290}
3291
3292EventStoreConnectionLogicHandler.prototype._startSubscription = function(msg) {
3293 switch (this._state)
3294 {
3295 case ConnectionState.Init:
3296 msg.cb(new Error(util.format("EventStoreConnection '%s' is not active.", this._esConnection.connectionName)));
3297 break;
3298 case ConnectionState.Connecting:
3299 case ConnectionState.Connected:
3300 var self = this;
3301 var operation = new VolatileSubscriptionOperation(this._settings.log, msg.cb, msg.streamId, msg.resolveLinkTos,
3302 msg.userCredentials, msg.eventAppeared, msg.subscriptionDropped,
3303 this._settings.verboseLogging, function() { return self._connection });
3304 this._logDebug("StartSubscription %s %s, %s, %d, %d.",
3305 this._state === ConnectionState.Connected ? "fire" : "enqueue",
3306 operation.constructor.name, operation, msg.maxRetries, msg.timeout);
3307 var subscription = createSubscriptionItem(operation, msg.maxRetries, msg.timeout);
3308 if (this._state === ConnectionState.Connecting) {
3309 this._subscriptions.enqueueSubscription(subscription);
3310 } else {
3311 this._subscriptions.startSubscription(subscription, this._connection);
3312 }
3313 break;
3314 case ConnectionState.Closed:
3315 msg.cb(new Error("Connection closed. Connection: " + this._esConnection.connectionName));
3316 break;
3317 default:
3318 throw new Error(util.format("Unknown state: %s.", this._state));
3319 }
3320};
3321
3322EventStoreConnectionLogicHandler.prototype._startPersistentSubscription = function(msg) {
3323 var self = this;
3324 switch (this._state)
3325 {
3326 case ConnectionState.Init:
3327 msg.cb(new Error(util.format("EventStoreConnection '%s' is not active.", this._esConnection.connectionName)));
3328 break;
3329 case ConnectionState.Connecting:
3330 case ConnectionState.Connected:
3331 var operation = new ConnectToPersistentSubscriptionOperation(this._settings.log, msg.cb, msg.subscriptionId,
3332 msg.bufferSize, msg.streamId, msg.userCredentials, msg.eventAppeared, msg.subscriptionDropped,
3333 this._settings.verboseLogging, function() { return self._connection });
3334 this._logDebug("StartSubscription %s %s, %s, %d, %d.",
3335 this._state === ConnectionState.Connected ? "fire" : "enqueue",
3336 operation.constructor.name, operation, msg.maxRetries, msg.timeout);
3337 var subscription = createSubscriptionItem(operation, msg.maxRetries, msg.timeout);
3338 if (this._state === ConnectionState.Connecting) {
3339 this._subscriptions.enqueueSubscription(subscription);
3340 } else {
3341 this._subscriptions.startSubscription(subscription, this._connection);
3342 }
3343 break;
3344 case ConnectionState.Closed:
3345 msg.cb(new Error("Connection closed. " + this._esConnection.connectionName));
3346 break;
3347 default: throw new Error(util.format("Unknown state: %s.", this._state));
3348 }
3349};
3350
3351EventStoreConnectionLogicHandler.prototype._establishTcpConnection = function(endPoints) {
3352 var endPoint = this._settings.useSslConnection ? endPoints.secureTcpEndPoint : endPoints.tcpEndPoint;
3353 if (endPoint === null)
3354 {
3355 this._closeConnection("No end point to node specified.");
3356 return;
3357 }
3358
3359 this._logDebug("EstablishTcpConnection to [%j]", endPoint);
3360
3361 if (this._state !== ConnectionState.Connecting) return;
3362 if (this._connectingPhase !== ConnectingPhase.EndPointDiscovery) return;
3363
3364 var self = this;
3365 this._connectingPhase = ConnectingPhase.ConnectionEstablishing;
3366 this._connection = new TcpPackageConnection(
3367 this._settings.log,
3368 endPoint,
3369 uuid.v4(),
3370 this._settings.useSslConnection,
3371 this._settings.targetHost,
3372 this._settings.validateServer,
3373 this._settings.clientConnectionTimeout,
3374 function(connection, pkg) {
3375 self.enqueueMessage(new messages.HandleTcpPackageMessage(connection, pkg));
3376 },
3377 function(connection, error) {
3378 self.enqueueMessage(new messages.TcpConnectionErrorMessage(connection, error));
3379 },
3380 function(connection) {
3381 connection.startReceiving();
3382 self.enqueueMessage(new messages.TcpConnectionEstablishedMessage(connection));
3383 },
3384 function(connection, error) {
3385 self.enqueueMessage(new messages.TcpConnectionClosedMessage(connection, error));
3386 }
3387 );
3388};
3389
3390EventStoreConnectionLogicHandler.prototype._tcpConnectionEstablished = function(connection) {
3391 if (this._state !== ConnectionState.Connecting || !this._connection || !this._connection.equals(connection) || connection.isClosed)
3392 {
3393 this._logDebug("IGNORED (_state %s, _conn.Id %s, conn.Id %s, conn.closed %s): TCP connection to [%j, L%j] established.",
3394 this._state, this._connection === null ? EmptyGuid : this._connection.connectionId, connection.connectionId,
3395 connection.isClosed, connection.remoteEndPoint, connection.localEndPoint);
3396 return;
3397 }
3398
3399 this._logDebug("TCP connection to [%j, L%j, %s] established.", connection.remoteEndPoint, connection.localEndPoint, connection.connectionId);
3400 this._heartbeatInfo = {
3401 lastPackageNumber: this._packageNumber,
3402 isIntervalStage: true,
3403 timeStamp: Date.now()
3404 };
3405
3406 if (this._settings.defaultUserCredentials !== null)
3407 {
3408 this._connectingPhase = ConnectingPhase.Authentication;
3409
3410 this._authInfo = {
3411 correlationId: uuid.v4(),
3412 timeStamp: Date.now()
3413 };
3414 this._connection.enqueueSend(new TcpPackage(
3415 TcpCommand.Authenticate,
3416 TcpFlags.Authenticated,
3417 this._authInfo.correlationId,
3418 this._settings.defaultUserCredentials.username,
3419 this._settings.defaultUserCredentials.password));
3420 }
3421 else
3422 {
3423 this._goToIdentifiedState();
3424 }
3425};
3426
3427EventStoreConnectionLogicHandler.prototype._goToIdentifiedState = function() {
3428 this._connectingPhase = ConnectingPhase.Identification;
3429 this._identityInfo = {
3430 correlationId: uuid.v4(),
3431 timeStamp: Date.now()
3432 };
3433 var dto = new ClientMessage.IdentifyClient({version: ClientVersion, connectionName: this._esConnection.connectionName});
3434 var buf = dto.constructor.encode(dto).finish();
3435 this._connection.enqueueSend(new TcpPackage(TcpCommand.IdentifyClient, TcpFlags.None, this._identityInfo.correlationId, null, null, createBufferSegment(buf)))
3436};
3437
3438EventStoreConnectionLogicHandler.prototype._goToConnectedState = function() {
3439 this._state = ConnectionState.Connected;
3440 this._connectingPhase = ConnectingPhase.Connected;
3441
3442 this._wasConnected = true;
3443
3444 this.emit('connected', this._connection.remoteEndPoint);
3445
3446 if ((Date.now() - this._lastTimeoutsTimeStamp) >= this._settings.operationTimeoutCheckPeriod)
3447 {
3448 this._operations.checkTimeoutsAndRetry(this._connection);
3449 this._subscriptions.checkTimeoutsAndRetry(this._connection);
3450 this._lastTimeoutsTimeStamp = Date.now();
3451 }
3452};
3453
3454EventStoreConnectionLogicHandler.prototype._tcpConnectionError = function(connection, error) {
3455 if (!this._connection || !this._connection.equals(connection)) return;
3456 if (this._state === ConnectionState.Closed) return;
3457
3458 this._logDebug("TcpConnectionError connId %s, exc %s.", connection.connectionId, error);
3459 this._closeConnection("TCP connection error occurred.", error);
3460};
3461
3462EventStoreConnectionLogicHandler.prototype._tcpConnectionClosed = function(connection, error) {
3463 if (this._state === ConnectionState.Init) throw new Error();
3464 if (this._state === ConnectionState.Closed || !this._connection || !this._connection.equals(connection))
3465 {
3466 this._logDebug("IGNORED (_state: %s, _conn.ID: %s, conn.ID: %s): TCP connection to [%j, L%j] closed.",
3467 this._state, this._connection === null ? EmptyGuid : this._connection.connectionId, connection.connectionId,
3468 connection.remoteEndPoint, connection.localEndPoint);
3469 return;
3470 }
3471
3472 this._state = ConnectionState.Connecting;
3473 this._connectingPhase = ConnectingPhase.Reconnecting;
3474
3475 this._logDebug("TCP connection to [%j, L%j, %s] closed. %s", connection.remoteEndPoint, connection.localEndPoint, connection.connectionId, error);
3476
3477 this._subscriptions.purgeSubscribedAndDroppedSubscriptions(this._connection.connectionId);
3478 this._reconnInfo = {
3479 reconnectionAttempt: this._reconnInfo ? this._reconnInfo.reconnectionAttempt : 0,
3480 timeStamp: Date.now()
3481 };
3482
3483 if (this._wasConnected)
3484 {
3485 this._wasConnected = false;
3486 this.emit('disconnected', connection.remoteEndPoint);
3487 }
3488};
3489
3490EventStoreConnectionLogicHandler.prototype._handleTcpPackage = function(connection, pkg) {
3491 if (!connection.equals(this._connection) || this._state === ConnectionState.Closed || this._state === ConnectionState.Init)
3492 {
3493 this._logDebug("IGNORED: HandleTcpPackage connId %s, package %s, %s.",
3494 connection.connectionId, TcpCommand.getName(pkg.command), pkg.correlationId);
3495 return;
3496 }
3497
3498 this._logDebug("HandleTcpPackage connId %s, package %s, %s.",
3499 this._connection.connectionId, TcpCommand.getName(pkg.command), pkg.correlationId);
3500 this._packageNumber += 1;
3501
3502 if (pkg.command === TcpCommand.HeartbeatResponseCommand)
3503 {
3504 if (pkg.correlationId === this._heartbeatInfo.correlationId)
3505 {
3506 var now = Date.now();
3507 var heartbeatEvent = {
3508 connectionId: this._connection.connectionId,
3509 remoteEndPoint: this._connection.remoteEndPoint,
3510 requestSentAt: this._heartbeatInfo.timeStamp,
3511 requestPkgNumber: this._heartbeatInfo.lastPackageNumber,
3512 responseReceivedAt: now,
3513 responsePkgNumber: this._packageNumber
3514 };
3515 try {
3516 this.emit('heartbeatInfo', heartbeatEvent);
3517 } catch(e) {
3518 this._logDebug("IGNORED: emit heartbeat event failed.\n%s", e.stack);
3519 }
3520 }
3521 return;
3522 }
3523 if (pkg.command === TcpCommand.HeartbeatRequestCommand)
3524 {
3525 this._connection.enqueueSend(new TcpPackage(
3526 TcpCommand.HeartbeatResponseCommand,
3527 TcpFlags.None,
3528 pkg.correlationId));
3529 return;
3530 }
3531
3532 if (pkg.command === TcpCommand.Authenticated || pkg.command === TcpCommand.NotAuthenticated)
3533 {
3534 if (this._state === ConnectionState.Connecting
3535 && this._connectingPhase === ConnectingPhase.Authentication
3536 && this._authInfo.correlationId === pkg.correlationId)
3537 {
3538 if (pkg.command === TcpCommand.NotAuthenticated)
3539 this.emit('authenticationFailed', "Not authenticated");
3540
3541 this._goToIdentifiedState();
3542 return;
3543 }
3544 }
3545
3546 if (pkg.command === TcpCommand.ClientIdentified)
3547 {
3548 if (this._state === ConnectionState.Connecting
3549 && this._identityInfo.correlationId === pkg.correlationId)
3550 {
3551 this._goToConnectedState();
3552 return;
3553 }
3554 }
3555
3556 if (pkg.command === TcpCommand.BadRequest && pkg.correlationId === EmptyGuid)
3557 {
3558 var message = "<no message>";
3559 try {
3560 message = pkg.data.toString();
3561 } catch(e) {}
3562 var err = new Error("Bad request received from server. Error: " + message);
3563 this._closeConnection("Connection-wide BadRequest received. Too dangerous to continue.", err);
3564 return;
3565 }
3566
3567 var operation = this._operations.getActiveOperation(pkg.correlationId);
3568 if (operation)
3569 {
3570 var result = operation.operation.inspectPackage(pkg);
3571 this._logDebug("HandleTcpPackage OPERATION DECISION %s (%s), %s", result.decision, result.description, operation.operation);
3572 switch (result.decision)
3573 {
3574 case InspectionDecision.DoNothing: break;
3575 case InspectionDecision.EndOperation:
3576 this._operations.removeOperation(operation);
3577 break;
3578 case InspectionDecision.Retry:
3579 this._operations.scheduleOperationRetry(operation);
3580 break;
3581 case InspectionDecision.Reconnect:
3582 this._reconnectTo({tcpEndPoint: result.tcpEndPoint, secureTcpEndPoint: result.secureTcpEndPoint});
3583 this._operations.scheduleOperationRetry(operation);
3584 break;
3585 default:
3586 throw new Error("Unknown InspectionDecision: " + result.decision);
3587 }
3588 if (this._state === ConnectionState.Connected) {
3589 this._operations.scheduleWaitingOperations(connection);
3590 }
3591
3592 return;
3593 }
3594
3595 var subscription = this._subscriptions.getActiveSubscription(pkg.correlationId);
3596 if (subscription)
3597 {
3598 var result = subscription.operation.inspectPackage(pkg);
3599 this._logDebug("HandleTcpPackage SUBSCRIPTION DECISION %s (%s), %s", result.decision, result.description, subscription);
3600 switch (result.decision)
3601 {
3602 case InspectionDecision.DoNothing: break;
3603 case InspectionDecision.EndOperation:
3604 this._subscriptions.removeSubscription(subscription);
3605 break;
3606 case InspectionDecision.Retry:
3607 this._subscriptions.scheduleSubscriptionRetry(subscription);
3608 break;
3609 case InspectionDecision.Reconnect:
3610 this._reconnectTo({tcpEndPoint: result.tcpEndPoint, secureTcpEndPoint: result.secureTcpEndPoint});
3611 this._subscriptions.scheduleSubscriptionRetry(subscription);
3612 break;
3613 case InspectionDecision.Subscribed:
3614 subscription.isSubscribed = true;
3615 break;
3616 default:
3617 throw new Error("Unknown InspectionDecision: " + result.decision);
3618 }
3619
3620 return;
3621 }
3622
3623 this._logDebug("HandleTcpPackage UNMAPPED PACKAGE with CorrelationId %s, Command: %s",
3624 pkg.correlationId, TcpCommand.getName(pkg.command));
3625};
3626
3627EventStoreConnectionLogicHandler.prototype._reconnectTo = function(endPoints) {
3628 var endPoint = this._settings.useSslConnection
3629 ? endPoints.secureTcpEndPoint
3630 : endPoints.tcpEndPoint;
3631 if (endPoint === null)
3632 {
3633 this._closeConnection("No end point is specified while trying to reconnect.");
3634 return;
3635 }
3636
3637 if (this._state !== ConnectionState.Connected || this._connection.remoteEndPoint === endPoint) return;
3638
3639 var msg = util.format("EventStoreConnection '%s': going to reconnect to [%j]. Current endpoint: [%j, L%j].",
3640 this._esConnection.connectionName, endPoint, this._connection.remoteEndPoint, this._connection.localEndPoint);
3641 if (this._settings.verboseLogging) this._settings.log.info(msg);
3642 this._closeTcpConnection(msg);
3643
3644 this._state = ConnectionState.Connecting;
3645 this._connectingPhase = ConnectingPhase.EndPointDiscovery;
3646 this._establishTcpConnection(endPoints);
3647};
3648
3649EventStoreConnectionLogicHandler.prototype._timerTick = function() {
3650 switch (this._state)
3651 {
3652 case ConnectionState.Init: break;
3653 case ConnectionState.Connecting:
3654 if (this._connectingPhase === ConnectingPhase.Reconnecting && (Date.now() - this._reconnInfo.timeStamp) >= this._settings.reconnectionDelay) {
3655 this._logDebug("TimerTick checking reconnection...");
3656
3657 this._reconnInfo = {reconnectionAttempt: this._reconnInfo.reconnectionAttempt + 1, timeStamp: Date.now()};
3658 if (this._settings.maxReconnections >= 0 && this._reconnInfo.reconnectionAttempt > this._settings.maxReconnections) {
3659 this._closeConnection("Reconnection limit reached.");
3660 } else {
3661 this.emit('reconnecting', {});
3662 this._discoverEndpoint(null);
3663 }
3664 } else if (this._connectingPhase === ConnectingPhase.Authentication && (Date.now() - this._authInfo.timeStamp) >= this._settings.operationTimeout) {
3665 this.emit('authenticationFailed', "Authentication timed out.");
3666 if (this._clientVersion === 1) {
3667 this._goToIdentifiedState();
3668 } else {
3669 this._goToConnectedState();
3670 }
3671 } else if (this._connectingPhase === ConnectingPhase.Authentication || this._connectingPhase === ConnectingPhase.Connected) {
3672 this._manageHeartbeats();
3673 }
3674 break;
3675 case ConnectionState.Connected:
3676 // operations timeouts are checked only if connection is established and check period time passed
3677 if ((Date.now() - this._lastTimeoutsTimeStamp) >= this._settings.operationTimeoutCheckPeriod)
3678 {
3679 // On mono even impossible connection first says that it is established
3680 // so clearing of reconnection count on ConnectionEstablished event causes infinite reconnections.
3681 // So we reset reconnection count to zero on each timeout check period when connection is established
3682 this._reconnInfo = {reconnectionAttempt: 0, timeStamp: Date.now()};
3683 this._operations.checkTimeoutsAndRetry(this._connection);
3684 this._subscriptions.checkTimeoutsAndRetry(this._connection);
3685 this._lastTimeoutsTimeStamp = Date.now();
3686 }
3687 this._manageHeartbeats();
3688 break;
3689 case ConnectionState.Closed:
3690 break;
3691 default:
3692 throw new Error("Unknown state: " + this._state + ".");
3693 }
3694};
3695
3696EventStoreConnectionLogicHandler.prototype._manageHeartbeats = function() {
3697 if (this._connection === null) return;
3698
3699 var timeout = this._heartbeatInfo.isIntervalStage ? this._settings.heartbeatInterval : this._settings.heartbeatTimeout;
3700 if ((Date.now() - this._heartbeatInfo.timeStamp) < timeout) return;
3701
3702 var packageNumber = this._packageNumber;
3703 if (this._heartbeatInfo.lastPackageNumber !== packageNumber)
3704 {
3705 this._heartbeatInfo = {lastPackageNumber: packageNumber, isIntervalStage: true, timeStamp: Date.now()};
3706 return;
3707 }
3708
3709 if (this._heartbeatInfo.isIntervalStage)
3710 {
3711 var correlationId = uuid.v4();
3712 // TcpMessage.Heartbeat analog
3713 this._connection.enqueueSend(new TcpPackage(
3714 TcpCommand.HeartbeatRequestCommand,
3715 TcpFlags.None,
3716 correlationId));
3717 this._heartbeatInfo = {correlationId: correlationId, lastPackageNumber: this._heartbeatInfo.lastPackageNumber, isIntervalStage: false, timeStamp: Date.now()};
3718 }
3719 else
3720 {
3721 // TcpMessage.HeartbeatTimeout analog
3722 var msg = util.format("EventStoreConnection '%s': closing TCP connection [%j, L%j, %s] due to HEARTBEAT TIMEOUT at pkgNum %d.",
3723 this._esConnection.connectionName, this._connection.remoteEndPoint, this._connection.localEndPoint,
3724 this._connection.connectionId, packageNumber);
3725 this._settings.log.info(msg);
3726 this._closeTcpConnection(msg);
3727 }
3728};
3729
3730EventStoreConnectionLogicHandler.prototype._logDebug = function(message) {
3731 if (!this._settings.verboseLogging) return;
3732
3733 if (arguments.length > 1) {
3734 message = util.format.apply(util, Array.prototype.slice.call(arguments));
3735 }
3736
3737 this._settings.log.debug("EventStoreConnection '%s': %s", this._esConnection.connectionName, message);
3738};
3739
3740EventStoreConnectionLogicHandler.prototype._logInfo = function(message){
3741 if (arguments.length > 1) {
3742 message = util.format.apply(util, Array.prototype.slice.call(arguments));
3743 }
3744
3745 this._settings.log.info("EventStoreConnection '%s': %s", this._esConnection.connectionName, message);
3746};
3747
3748module.exports = EventStoreConnectionLogicHandler;
3749
3750
3751/***/ }),
3752/* 41 */
3753/***/ (function(module, exports) {
3754
3755function typeName(t) {
3756 if (typeof t === 'function') return t.name;
3757 if (typeof t === 'object') return t.constructor.name;
3758 throw new TypeError('type must be a function or object, not ' + typeof t);
3759}
3760
3761function SimpleQueuedHandler(log) {
3762 this._handlers = {};
3763 this._messages = [];
3764 this._isProcessing = false;
3765 this._log = log;
3766}
3767
3768SimpleQueuedHandler.prototype.registerHandler = function(type, handler) {
3769 var typeId = typeName(type);
3770 this._handlers[typeId] = function (msg) {
3771 try {
3772 handler(msg);
3773 } catch(e) {
3774 this._log.error('handle for', type, 'failed:', e.stack);
3775 }
3776 };
3777};
3778
3779SimpleQueuedHandler.prototype.enqueueMessage = function(msg) {
3780 this._messages.push(msg);
3781 if (!this._isProcessing) {
3782 this._isProcessing = true;
3783 setImmediate(this._processQueue.bind(this));
3784 }
3785};
3786
3787SimpleQueuedHandler.prototype._processQueue = function() {
3788 var message = this._messages.shift();
3789 while(message) {
3790 var typeId = typeName(message);
3791 var handler = this._handlers[typeId];
3792 if (!handler) throw new Error("No handler registered for message " + typeId);
3793 setImmediate(handler, message);
3794 message = this._messages.shift();
3795 }
3796 this._isProcessing = false;
3797};
3798
3799module.exports = SimpleQueuedHandler;
3800
3801
3802/***/ }),
3803/* 42 */
3804/***/ (function(module, exports, __webpack_require__) {
3805
3806var util = __webpack_require__(0);
3807
3808var LengthPrefixMessageFramer = __webpack_require__(43);
3809var TcpConnection = __webpack_require__(44);
3810var TcpPackage = __webpack_require__(11);
3811var TcpCommand = __webpack_require__(1);
3812
3813/**
3814 * @private
3815 * @param log
3816 * @param remoteEndPoint
3817 * @param connectionId
3818 * @param ssl
3819 * @param targetHost
3820 * @param validateServer
3821 * @param timeout
3822 * @param handlePackage
3823 * @param onError
3824 * @param connectionEstablished
3825 * @param connectionClosed
3826 * @constructor
3827 * @property {string} connectionId
3828 * @property {boolean} isClosed
3829 * @property {object} remoteEndPoint
3830 * @property {object} localEndPoint
3831 */
3832function TcpPackageConnection(
3833 log, remoteEndPoint, connectionId, ssl, targetHost, validateServer, timeout,
3834 handlePackage, onError, connectionEstablished, connectionClosed)
3835{
3836 this._connectionId = connectionId;
3837 this._log = log;
3838 this._handlePackage = handlePackage;
3839 this._onError = onError;
3840
3841 //Setup callback for incoming messages
3842 this._framer = new LengthPrefixMessageFramer();
3843 this._framer.registerMessageArrivedCallback(this._incomingMessageArrived.bind(this));
3844
3845 var self = this;
3846 this._connection = TcpConnection.createConnectingConnection(
3847 log,
3848 connectionId,
3849 remoteEndPoint,
3850 ssl,
3851 targetHost,
3852 validateServer,
3853 timeout,
3854 function(tcpConnection) {
3855 log.debug("TcpPackageConnection: connected to [%j, L%j, %s].", tcpConnection.remoteEndPoint, tcpConnection.localEndPoint, connectionId);
3856 connectionEstablished(self);
3857 },
3858 function(conn, error) {
3859 log.debug("TcpPackageConnection: connection to [%j, L%j, %s] failed. Error: %s.", conn.remoteEndPoint, conn.localEndPoint, connectionId, error);
3860 connectionClosed(self, error);
3861 },
3862 function (conn, error) {
3863 if (error === true) error = new Error('transmission error.');
3864
3865 log.debug("TcpPackageConnection: connection [%j, L%j, %s] was closed %s", conn.remoteEndPoint, conn.localEndPoint,
3866 connectionId, error ? "with error: " + error.stack : "cleanly.");
3867
3868 connectionClosed(self, error);
3869 });
3870}
3871Object.defineProperty(TcpPackageConnection.prototype, 'connectionId', {
3872 enumerable: true,
3873 get: function() {
3874 return this._connectionId;
3875 }
3876});
3877Object.defineProperty(TcpPackageConnection.prototype, 'isClosed', {
3878 enumerable: true,
3879 get: function() {
3880 return this._connection.isClosed;
3881 }
3882});
3883Object.defineProperty(TcpPackageConnection.prototype, 'remoteEndPoint', {
3884 enumerable: true,
3885 get: function() {
3886 return this._connection.remoteEndPoint;
3887 }
3888});
3889Object.defineProperty(TcpPackageConnection.prototype, 'localEndPoint', {
3890 enumerable: true,
3891 get: function() {
3892 return this._connection.localEndPoint;
3893 }
3894});
3895
3896TcpPackageConnection.prototype._onRawDataReceived = function(connection, data) {
3897 try {
3898 this._framer.unframeData(data);
3899 } catch(e) {
3900 this._log.error(e, "TcpPackageConnection: [%j, L%j, %s]. Invalid TCP frame received.", this.remoteEndPoint, this.localEndPoint, this._connectionId);
3901 this.close("Invalid TCP frame received");
3902 return;
3903 }
3904
3905 connection.receive(this._onRawDataReceived.bind(this));
3906};
3907
3908TcpPackageConnection.prototype._incomingMessageArrived = function(data) {
3909 var valid = false;
3910 var pkg;
3911 try
3912 {
3913 pkg = TcpPackage.fromBufferSegment(data);
3914 valid = true;
3915 this._handlePackage(this, pkg);
3916 }
3917 catch (e)
3918 {
3919 this._connection.close(util.format("Error when processing TcpPackage %s: %s",
3920 valid ? TcpCommand.getName(pkg.command) : "<invalid package>", e.message));
3921
3922 var message = util.format("TcpPackageConnection: [%j, L%j, %s] ERROR for %s. Connection will be closed.",
3923 this.remoteEndPoint, this.localEndPoint, this._connectionId,
3924 valid ? TcpCommand.getName(pkg.command) : "<invalid package>");
3925 if (this._onError !== null) this._onError(this, e);
3926 this._log.debug(e, message);
3927 }
3928};
3929
3930TcpPackageConnection.prototype.startReceiving = function() {
3931 if (this._connection === null) throw new Error("Failed connection.");
3932 this._connection.receive(this._onRawDataReceived.bind(this));
3933};
3934
3935TcpPackageConnection.prototype.enqueueSend = function(pkg) {
3936 if (this._connection === null) throw new Error("Failed connection.");
3937 this._connection.enqueueSend(this._framer.frameData(pkg.asBufferSegment()));
3938};
3939
3940TcpPackageConnection.prototype.close = function(reason) {
3941 if (this._connection === null) throw new Error("Failed connection.");
3942 this._connection.close(reason);
3943};
3944
3945TcpPackageConnection.prototype.equals = function(other) {
3946 if (other === null) return false;
3947 return this._connectionId === other._connectionId;
3948};
3949
3950
3951module.exports = TcpPackageConnection;
3952
3953
3954/***/ }),
3955/* 43 */
3956/***/ (function(module, exports, __webpack_require__) {
3957
3958var createBufferSegment = __webpack_require__(10);
3959
3960const HeaderLength = 4;
3961
3962function LengthPrefixMessageFramer(maxPackageSize) {
3963 this._maxPackageSize = maxPackageSize || 64*1024*1024;
3964 this._receivedHandler = null;
3965 this.reset();
3966}
3967
3968LengthPrefixMessageFramer.prototype.reset = function() {
3969 this._messageBuffer = null;
3970 this._headerBytes = 0;
3971 this._packageLength = 0;
3972 this._bufferIndex = 0;
3973};
3974
3975LengthPrefixMessageFramer.prototype.unframeData = function(bufferSegments) {
3976 for(var i = 0; i < bufferSegments.length; i++) {
3977 this._parse(bufferSegments[i]);
3978 }
3979};
3980
3981LengthPrefixMessageFramer.prototype._parse = function(bytes) {
3982 var buffer = bytes.buffer;
3983 for (var i = bytes.offset; i < bytes.offset + bytes.count; i++)
3984 {
3985 if (this._headerBytes < HeaderLength)
3986 {
3987 this._packageLength |= (buffer[i] << (this._headerBytes * 8)); // little-endian order
3988 ++this._headerBytes;
3989 if (this._headerBytes === HeaderLength)
3990 {
3991 if (this._packageLength <= 0 || this._packageLength > this._maxPackageSize) {
3992 throw new Error(["Package size is out of bounds: ", this._packageLength, "(max: ", this._maxPackageSize, "."].join(''));
3993 }
3994
3995 this._messageBuffer = new Buffer(this._packageLength);
3996 }
3997 }
3998 else
3999 {
4000 var copyCnt = Math.min(bytes.count + bytes.offset - i, this._packageLength - this._bufferIndex);
4001 bytes.buffer.copy(this._messageBuffer, this._bufferIndex, i, i + copyCnt);
4002 this._bufferIndex += copyCnt;
4003 i += copyCnt - 1;
4004
4005 if (this._bufferIndex === this._packageLength)
4006 {
4007 if (this._receivedHandler !== null) {
4008 this._receivedHandler(createBufferSegment(this._messageBuffer, 0, this._bufferIndex));
4009 }
4010 this.reset();
4011 }
4012 }
4013 }
4014};
4015
4016LengthPrefixMessageFramer.prototype.frameData = function(data) {
4017 var length = data.count;
4018 var lengthBuffer = new Buffer(HeaderLength);
4019 lengthBuffer.writeInt32LE(length, 0);
4020 return [
4021 createBufferSegment(lengthBuffer, 0, HeaderLength),
4022 data
4023 ];
4024};
4025
4026LengthPrefixMessageFramer.prototype.registerMessageArrivedCallback = function(handler) {
4027 this._receivedHandler = handler;
4028};
4029
4030
4031module.exports = LengthPrefixMessageFramer;
4032
4033/***/ }),
4034/* 44 */
4035/***/ (function(module, exports, __webpack_require__) {
4036
4037var net = __webpack_require__(45);
4038var tls = __webpack_require__(46);
4039var createBufferSegment = __webpack_require__(10);
4040
4041const MaxSendPacketSize = 64 * 1024;
4042
4043function TcpConnection(log, connectionId, remoteEndPoint, onConnectionClosed) {
4044 this._socket = null;
4045 this._log = log;
4046 this._connectionId = connectionId;
4047 this._remoteEndPoint = remoteEndPoint;
4048 this._localEndPoint = null;
4049 this._onConnectionClosed = onConnectionClosed;
4050 this._receiveCallback = null;
4051 this._closed = false;
4052 this._sendQueue = [];
4053 this._receiveQueue = [];
4054
4055 Object.defineProperty(this, 'remoteEndPoint', {
4056 enumerable: true,
4057 get: function() {
4058 return this._remoteEndPoint;
4059 }
4060 });
4061 Object.defineProperty(this, 'localEndPoint', {
4062 enumerable: true,
4063 get: function() {
4064 return this._localEndPoint;
4065 }
4066 });
4067}
4068
4069TcpConnection.prototype._initSocket = function(socket) {
4070 this._socket = socket;
4071 this._localEndPoint = {host: socket.localAddress, port: socket.localPort};
4072 this._remoteEndPoint.host = socket.remoteAddress;
4073
4074 this._socket.on('error', this._processError.bind(this));
4075 this._socket.on('drain', this._trySend.bind(this));
4076 this._socket.on('data', this._processReceive.bind(this));
4077 this._socket.on('close', this._processClose.bind(this));
4078
4079 this._trySend();
4080};
4081
4082TcpConnection.prototype.enqueueSend = function(bufSegmentArray) {
4083 for(var i = 0; i < bufSegmentArray.length; i++) {
4084 var bufSegment = bufSegmentArray[i];
4085 this._sendQueue.push(bufSegment.toBuffer());
4086 }
4087
4088 this._trySend();
4089};
4090
4091TcpConnection.prototype._trySend = function() {
4092 if (this._sendQueue.length === 0 || this._socket === null) return;
4093
4094 var buffers = [];
4095 var bytes = 0;
4096 var sendPiece;
4097 while((sendPiece = this._sendQueue.shift())) {
4098 buffers.push(sendPiece);
4099 bytes += sendPiece.length;
4100 if (bytes > MaxSendPacketSize) break;
4101 }
4102
4103 var joinedBuffers = Buffer.concat(buffers, bytes);
4104 if (!this._socket.write(joinedBuffers)) return;
4105
4106 setImmediate(this._trySend.bind(this));
4107};
4108
4109TcpConnection.prototype._processError = function(err) {
4110 this._closeInternal(err, "Socket error");
4111};
4112
4113TcpConnection.prototype._processClose = function(had_error) {
4114 this._closeInternal(had_error, "Socket closed");
4115};
4116
4117TcpConnection.prototype._processReceive = function(buf) {
4118 if (buf.length === 0) {
4119 //NotifyReceiveCompleted(0);
4120 this._closeInternal(null, "Socket closed");
4121 return;
4122 }
4123
4124 //NotifyReceiveCompleted(buf.length)
4125 this._receiveQueue.push(buf);
4126
4127 this._tryDequeueReceivedData();
4128};
4129
4130TcpConnection.prototype.receive = function(cb) {
4131 this._receiveCallback = cb;
4132 this._tryDequeueReceivedData();
4133};
4134
4135TcpConnection.prototype._tryDequeueReceivedData = function() {
4136 if (this._receiveCallback === null || this._receiveQueue.length === 0) return;
4137
4138 var res = [];
4139 while(this._receiveQueue.length > 0) {
4140 var buf = this._receiveQueue.shift();
4141 var bufferSegment = createBufferSegment(buf);
4142 res.push(bufferSegment);
4143 }
4144 var callback = this._receiveCallback;
4145 this._receiveCallback = null;
4146
4147 callback(this, res);
4148
4149 var bytes = 0;
4150 for(var i=0;i<res.length;i++) {
4151 bytes += res[i].count;
4152 }
4153
4154 //this._pendingReceivedBytes -= bytes;
4155};
4156
4157TcpConnection.prototype.close = function(reason) {
4158 this._closeInternal(null, reason || "Normal socket close.");
4159};
4160
4161TcpConnection.prototype._closeInternal = function(err, reason) {
4162 if (this._closed) return;
4163 this._closed = true;
4164
4165 if (this._socket !== null) {
4166 this._socket.end();
4167 this._socket.unref();
4168 this._socket = null;
4169 }
4170
4171 if (this._onConnectionClosed !== null) this._onConnectionClosed(this, err);
4172};
4173
4174TcpConnection.createConnectingConnection = function(
4175 log, connectionId, remoteEndPoint, ssl, targetHost, validateServer,
4176 connectionTimeout, onConnectionEstablished, onConnectionFailed, onConnectionClosed
4177) {
4178 var connection = new TcpConnection(log, connectionId, remoteEndPoint, onConnectionClosed);
4179 var provider = ssl ? tls : net;
4180 var options = {
4181 servername: targetHost,
4182 rejectUnauthorized: validateServer,
4183 port: remoteEndPoint.port,
4184 host: remoteEndPoint.host,
4185 timeout: connectionTimeout
4186 };
4187 var socket = provider.connect(options, function() {
4188 socket.removeListener('error', onError);
4189 connection._initSocket(socket);
4190 if (onConnectionEstablished) onConnectionEstablished(connection);
4191 });
4192 socket.once('error', onError);
4193 function onError(err) {
4194 if (onConnectionFailed) onConnectionFailed(connection, err);
4195 }
4196 return connection;
4197};
4198
4199module.exports = TcpConnection;
4200
4201
4202/***/ }),
4203/* 45 */
4204/***/ (function(module, exports) {
4205
4206module.exports = require("net");
4207
4208/***/ }),
4209/* 46 */
4210/***/ (function(module, exports) {
4211
4212module.exports = require("tls");
4213
4214/***/ }),
4215/* 47 */
4216/***/ (function(module, exports, __webpack_require__) {
4217
4218var util = __webpack_require__(0);
4219var uuid = __webpack_require__(18);
4220
4221var Hash = __webpack_require__(26);
4222var TcpCommand = __webpack_require__(1);
4223
4224/**
4225 * @private
4226 * @param {string} connectionName
4227 * @param {object} settings
4228 * @constructor
4229 * @property {number} totalOperationCount
4230 */
4231function OperationsManager(connectionName, settings) {
4232 this._connectionName = connectionName;
4233 this._settings = settings;
4234
4235 this._totalOperationCount = 0;
4236 this._activeOperations = new Hash();
4237 this._waitingOperations = [];
4238 this._retryPendingOperations = [];
4239}
4240Object.defineProperty(OperationsManager.prototype, 'totalOperationCount', {
4241 get: function() {
4242 return this._totalOperationCount;
4243 }
4244});
4245
4246OperationsManager.prototype.getActiveOperation = function(correlationId) {
4247 return this._activeOperations.get(correlationId);
4248};
4249
4250function cleanUpError(connName, state, operation) {
4251 return new Error(util.format("Connection '%s' was closed. %s %s.", connName, state, operation.toString()));
4252}
4253
4254OperationsManager.prototype.cleanUp = function() {
4255 var self = this;
4256 this._activeOperations.forEach(function(correlationId, operation){
4257 operation.operation.fail(cleanUpError(self._connectionName, 'Active', operation));
4258 });
4259 this._waitingOperations.forEach(function(operation) {
4260 operation.operation.fail(cleanUpError(self._connectionName, 'Waiting', operation));
4261 });
4262 this._retryPendingOperations.forEach(function(operation) {
4263 operation.operation.fail(cleanUpError(self._connectionName, 'Pending', operation));
4264 });
4265
4266 this._activeOperations.clear();
4267 this._waitingOperations = [];
4268 this._retryPendingOperations = [];
4269 this._totalOperationCount = 0;
4270};
4271
4272OperationsManager.prototype.checkTimeoutsAndRetry = function(connection) {
4273 if (!connection) throw new TypeError("Connection is null.");
4274
4275 var retryOperations = [];
4276 var removeOperations = [];
4277 var self = this;
4278 this._activeOperations.forEach(function(correlationId, operation) {
4279 if (operation.connectionId !== connection.connectionId)
4280 {
4281 retryOperations.push(operation);
4282 }
4283 else if (operation.timeout > 0 && Date.now() - operation.lastUpdated > self._settings.operationTimeout)
4284 {
4285 var err = util.format("EventStoreConnection '%s': operation never got response from server.\n"
4286 + "UTC now: %s, operation: %s.",
4287 self._connectionName, new Date(), operation);
4288 self._settings.log.error(err);
4289
4290 if (self._settings.failOnNoServerResponse)
4291 {
4292 operation.operation.fail(new Error(err));
4293 removeOperations.push(operation);
4294 }
4295 else
4296 {
4297 retryOperations.push(operation);
4298 }
4299 }
4300 });
4301
4302 retryOperations.forEach(function(operation) {
4303 self.scheduleOperationRetry(operation);
4304 });
4305 removeOperations.forEach(function(operation) {
4306 self.removeOperation(operation);
4307 });
4308
4309 if (this._retryPendingOperations.length > 0)
4310 {
4311 this._retryPendingOperations.sort(function(x,y) {
4312 if (x.seqNo < y.seqNo) return -1;
4313 if (x.seqNo > y.seqNo) return 1;
4314 return 0;
4315 });
4316 this._retryPendingOperations.forEach(function(operation) {
4317 var oldCorrId = operation.correlationId;
4318 operation.correlationId = uuid.v4();
4319 operation.retryCount += 1;
4320 self._logDebug("retrying, old corrId %s, operation %s.", oldCorrId, operation);
4321 self.scheduleOperation(operation, connection);
4322 });
4323 this._retryPendingOperations = [];
4324 }
4325
4326 this.scheduleWaitingOperations(connection);
4327};
4328
4329OperationsManager.prototype.scheduleOperationRetry = function(operation) {
4330 if (!this.removeOperation(operation)) return;
4331
4332 this._logDebug("ScheduleOperationRetry for %s.", operation);
4333 if (operation.maxRetries >= 0 && operation.retryCount >= operation.maxRetries)
4334 {
4335 var err = util.format("Retry limit reached. Operation: %s, RetryCount: %d", operation, operation.retryCount);
4336 operation.operation.fail(new Error(err));
4337 return;
4338 }
4339 this._retryPendingOperations.push(operation);
4340};
4341
4342OperationsManager.prototype.removeOperation = function(operation) {
4343 this._activeOperations.remove(operation.correlationId);
4344 this._logDebug("RemoveOperation SUCCEEDED for %s.", operation);
4345 this._totalOperationCount = this._activeOperations.length + this._waitingOperations.length;
4346 return true;
4347};
4348
4349OperationsManager.prototype.scheduleWaitingOperations = function(connection) {
4350 if (!connection) throw new TypeError("connection is null.");
4351 while (this._waitingOperations.length > 0 && this._activeOperations.length < this._settings.maxConcurrentItems)
4352 {
4353 this.scheduleOperation(this._waitingOperations.shift(), connection);
4354 }
4355 this._totalOperationCount = this._activeOperations.length + this._waitingOperations.length;
4356};
4357
4358OperationsManager.prototype.enqueueOperation = function(operation) {
4359 this._logDebug("EnqueueOperation WAITING for %s.", operation);
4360 this._waitingOperations.push(operation);
4361};
4362
4363OperationsManager.prototype.scheduleOperation = function(operation, connection) {
4364 if (this._activeOperations.length >= this._settings.maxConcurrentItems)
4365 {
4366 this._logDebug("ScheduleOperation WAITING for %s.", operation);
4367 this._waitingOperations.push(operation);
4368 }
4369 else
4370 {
4371 operation.connectionId = connection.connectionId;
4372 operation.lastUpdated = Date.now();
4373 this._activeOperations.add(operation.correlationId, operation);
4374
4375 var pkg = operation.operation.createNetworkPackage(operation.correlationId);
4376 this._logDebug("ScheduleOperation package %s, %s, %s.", TcpCommand.getName(pkg.command), pkg.correlationId, operation);
4377 connection.enqueueSend(pkg);
4378 }
4379 this._totalOperationCount = this._activeOperations.length + this._waitingOperations.length;
4380};
4381
4382OperationsManager.prototype._logDebug = function(message) {
4383 if (!this._settings.verboseLogging) return;
4384
4385 if (arguments.length > 1) {
4386 message = util.format.apply(util, Array.prototype.slice.call(arguments));
4387 }
4388
4389 this._settings.log.debug("EventStoreConnection '%s': %s.", this._connectionName, message);
4390};
4391
4392module.exports = OperationsManager;
4393
4394/***/ }),
4395/* 48 */
4396/***/ (function(module, exports, __webpack_require__) {
4397
4398var util = __webpack_require__(0);
4399var uuid = __webpack_require__(18);
4400var Hash = __webpack_require__(26);
4401
4402var SubscriptionDropReason = __webpack_require__(14);
4403
4404function SubscriptionsManager(connectionName, settings) {
4405 //Ensure.NotNull(connectionName, "connectionName");
4406 //Ensure.NotNull(settings, "settings");
4407 this._connectionName = connectionName;
4408 this._settings = settings;
4409
4410 this._activeSubscriptions = new Hash();
4411 this._waitingSubscriptions = [];
4412 this._retryPendingSubscriptions = [];
4413}
4414
4415SubscriptionsManager.prototype.getActiveSubscription = function(correlationId) {
4416 return this._activeSubscriptions.get(correlationId);
4417};
4418
4419SubscriptionsManager.prototype.cleanUp = function() {
4420 var connectionClosedError = new Error(util.format("Connection '%s' was closed.", this._connectionName));
4421
4422 var self = this;
4423 this._activeSubscriptions.forEach(function(correlationId, subscription){
4424 subscription.operation.dropSubscription(SubscriptionDropReason.ConnectionClosed, connectionClosedError);
4425 });
4426 this._waitingSubscriptions.forEach(function(subscription){
4427 subscription.operation.dropSubscription(SubscriptionDropReason.ConnectionClosed, connectionClosedError);
4428 });
4429 this._retryPendingSubscriptions.forEach(function(subscription){
4430 subscription.operation.dropSubscription(SubscriptionDropReason.ConnectionClosed, connectionClosedError);
4431 });
4432
4433 this._activeSubscriptions.clear();
4434 this._waitingSubscriptions = [];
4435 this._retryPendingSubscriptions = [];
4436};
4437
4438SubscriptionsManager.prototype.purgeSubscribedAndDroppedSubscriptions = function(connectionId) {
4439 var self = this;
4440 var subscriptionsToRemove = [];
4441 this._activeSubscriptions.forEach(function(_, subscription) {
4442 if (subscription.isSubscribed && subscription.connectionId === connectionId) {
4443 subscription.operation.connectionClosed();
4444 subscriptionsToRemove.push(subscription);
4445 }
4446 });
4447 subscriptionsToRemove.forEach(function(subscription) {
4448 self._activeSubscriptions.remove(subscription.correlationId);
4449 });
4450};
4451
4452SubscriptionsManager.prototype.checkTimeoutsAndRetry = function(connection) {
4453 //Ensure.NotNull(connection, "connection");
4454
4455 var self = this;
4456 var retrySubscriptions = [];
4457 var removeSubscriptions = [];
4458 this._activeSubscriptions.forEach(function(_, subscription) {
4459 if (subscription.isSubscribed) return;
4460 if (subscription.connectionId !== connection.connectionId)
4461 {
4462 retrySubscriptions.push(subscription);
4463 }
4464 else if (subscription.timeout > 0 && Date.now() - subscription.lastUpdated > self._settings.operationTimeout)
4465 {
4466 var err = util.format("EventStoreConnection '%s': subscription never got confirmation from server.\n" +
4467 "UTC now: %s, operation: %s.",
4468 self._connectionName, new Date(), subscription);
4469 self._settings.log.error(err);
4470
4471 if (self._settings.failOnNoServerResponse)
4472 {
4473 subscription.operation.dropSubscription(SubscriptionDropReason.SubscribingError, new Error(err));
4474 removeSubscriptions.push(subscription);
4475 }
4476 else
4477 {
4478 retrySubscriptions.push(subscription);
4479 }
4480 }
4481 });
4482
4483 retrySubscriptions.forEach(function(subscription) {
4484 self.scheduleSubscriptionRetry(subscription);
4485 });
4486 removeSubscriptions.forEach(function(subscription) {
4487 self.removeSubscription(subscription);
4488 });
4489
4490 if (this._retryPendingSubscriptions.length > 0)
4491 {
4492 this._retryPendingSubscriptions.forEach(function(subscription) {
4493 subscription.retryCount += 1;
4494 self.startSubscription(subscription, connection);
4495 });
4496 this._retryPendingSubscriptions = [];
4497 }
4498
4499 while (this._waitingSubscriptions.length > 0)
4500 {
4501 this.startSubscription(this._waitingSubscriptions.shift(), connection);
4502 }
4503};
4504
4505SubscriptionsManager.prototype.removeSubscription = function(subscription) {
4506 this._activeSubscriptions.remove(subscription.correlationId);
4507 this._logDebug("RemoveSubscription %s.", subscription);
4508 return true;
4509};
4510
4511SubscriptionsManager.prototype.scheduleSubscriptionRetry = function(subscription) {
4512 if (!this.removeSubscription(subscription))
4513 {
4514 this._logDebug("RemoveSubscription failed when trying to retry %s.", subscription);
4515 return;
4516 }
4517
4518 if (subscription.maxRetries >= 0 && subscription.retryCount >= subscription.maxRetries)
4519 {
4520 this._logDebug("RETRIES LIMIT REACHED when trying to retry %s.", subscription);
4521 var err = util.format("Retries limit reached. Subscription: %s RetryCount: %d.", subscription, subscription.retryCount);
4522 subscription.operation.dropSubscription(SubscriptionDropReason.SubscribingError, new Error(err));
4523 return;
4524 }
4525
4526 this._logDebug("retrying subscription %s.", subscription);
4527 this._retryPendingSubscriptions.push(subscription);
4528};
4529
4530SubscriptionsManager.prototype.enqueueSubscription = function(subscriptionItem) {
4531 this._waitingSubscriptions.push(subscriptionItem);
4532};
4533
4534SubscriptionsManager.prototype.startSubscription = function(subscription, connection) {
4535 //Ensure.NotNull(connection, "connection");
4536
4537 if (subscription.isSubscribed)
4538 {
4539 this._logDebug("StartSubscription REMOVING due to already subscribed %s.", subscription);
4540 this.removeSubscription(subscription);
4541 return;
4542 }
4543
4544 subscription.correlationId = uuid.v4();
4545 subscription.connectionId = connection.connectionId;
4546 subscription.lastUpdated = Date.now();
4547
4548 this._activeSubscriptions.add(subscription.correlationId, subscription);
4549
4550 if (!subscription.operation.subscribe(subscription.correlationId, connection))
4551 {
4552 this._logDebug("StartSubscription REMOVING AS COULDN'T SUBSCRIBE %s.", subscription);
4553 this.removeSubscription(subscription);
4554 }
4555 else
4556 {
4557 this._logDebug("StartSubscription SUBSCRIBING %s.", subscription);
4558 }
4559};
4560
4561SubscriptionsManager.prototype._logDebug = function(message) {
4562 if (!this._settings.verboseLogging) return;
4563
4564 var parameters = Array.prototype.slice.call(arguments, 1);
4565 this._settings.log.debug("EventStoreConnection '%s': %s.", this._connectionName, parameters.length === 0 ? message : util.format(message, parameters));
4566};
4567
4568module.exports = SubscriptionsManager;
4569
4570/***/ }),
4571/* 49 */
4572/***/ (function(module, exports, __webpack_require__) {
4573
4574var util = __webpack_require__(0);
4575
4576var SubscriptionOperation = __webpack_require__(27);
4577var ClientMessage = __webpack_require__(2);
4578var TcpPackage = __webpack_require__(11);
4579var TcpCommand = __webpack_require__(1);
4580var TcpFlags = __webpack_require__(12);
4581var BufferSegment = __webpack_require__(10);
4582var InspectionDecision = __webpack_require__(4);
4583var InspectionResult = __webpack_require__(5);
4584var results = __webpack_require__(3);
4585var VolatileEventStoreSubscription = __webpack_require__(50);
4586
4587function VolatileSubscriptionOperation(
4588 log, cb, streamId, resolveLinkTos, userCredentials, eventAppeared,
4589 subscriptionDropped, verboseLogging, getConnection
4590) {
4591 SubscriptionOperation.call(this, log, cb, streamId, resolveLinkTos, userCredentials, eventAppeared, subscriptionDropped, verboseLogging, getConnection);
4592}
4593util.inherits(VolatileSubscriptionOperation, SubscriptionOperation);
4594
4595VolatileSubscriptionOperation.prototype._createSubscriptionPackage = function() {
4596 var dto = new ClientMessage.SubscribeToStream({
4597 eventStreamId: this._streamId,
4598 resolveLinkTos: this._resolveLinkTos
4599 });
4600 return new TcpPackage(TcpCommand.SubscribeToStream,
4601 this._userCredentials !== null ? TcpFlags.Authenticated : TcpFlags.None,
4602 this._correlationId,
4603 this._userCredentials !== null ? this._userCredentials.username : null,
4604 this._userCredentials !== null ? this._userCredentials.password : null,
4605 new BufferSegment(ClientMessage.SubscribeToStream.encode(dto).finish()));
4606};
4607
4608VolatileSubscriptionOperation.prototype._inspectPackage = function(pkg) {
4609 try {
4610 if (pkg.command === TcpCommand.SubscriptionConfirmation) {
4611 var dto = ClientMessage.SubscriptionConfirmation.decode(pkg.data.toBuffer());
4612 this._confirmSubscription(dto.lastCommitPosition, dto.lastEventNumber);
4613 return new InspectionResult(InspectionDecision.Subscribed, "SubscriptionConfirmation");
4614 }
4615 if (pkg.command === TcpCommand.StreamEventAppeared) {
4616 var dto = ClientMessage.StreamEventAppeared.decode(pkg.data.toBuffer());
4617 this._onEventAppeared(new results.ResolvedEvent(dto.event));
4618 return new InspectionResult(InspectionDecision.DoNothing, "StreamEventAppeared");
4619 }
4620 return null;
4621 } catch(e) {
4622 this._log.warn(e.stack);
4623 return null;
4624 }
4625};
4626
4627VolatileSubscriptionOperation.prototype._createSubscriptionObject = function(lastCommitPosition, lastEventNumber) {
4628 return new VolatileEventStoreSubscription(this, this._streamId, lastCommitPosition, lastEventNumber);
4629};
4630
4631module.exports = VolatileSubscriptionOperation;
4632
4633
4634/***/ }),
4635/* 50 */
4636/***/ (function(module, exports, __webpack_require__) {
4637
4638var util = __webpack_require__(0);
4639
4640var EventStoreSubsription = __webpack_require__(28);
4641
4642/**
4643 * @private
4644 * @param {SubscriptionOperation} subscriptionOperation
4645 * @param {string} streamId
4646 * @param {Position} lastCommitPosition
4647 * @param {number} lastEventNumber
4648 * @constructor
4649 * @augments {EventStoreSubscription}
4650 */
4651function VolatileEventStoreSubscription(subscriptionOperation, streamId, lastCommitPosition, lastEventNumber) {
4652 EventStoreSubsription.call(this, streamId, lastCommitPosition, lastEventNumber);
4653
4654 this._subscriptionOperation = subscriptionOperation;
4655}
4656util.inherits(VolatileEventStoreSubscription, EventStoreSubsription);
4657
4658VolatileEventStoreSubscription.prototype.unsubscribe = function() {
4659 this._subscriptionOperation.unsubscribe();
4660};
4661
4662module.exports = VolatileEventStoreSubscription;
4663
4664/***/ }),
4665/* 51 */
4666/***/ (function(module, exports, __webpack_require__) {
4667
4668var util = __webpack_require__(0);
4669var guidParse = __webpack_require__(13);
4670
4671var SubscriptionOperation = __webpack_require__(27);
4672var ClientMessage = __webpack_require__(2);
4673var TcpCommand = __webpack_require__(1);
4674var TcpFlags = __webpack_require__(12);
4675var TcpPackage = __webpack_require__(11);
4676var createBufferSegment = __webpack_require__(10);
4677var InspectionResult = __webpack_require__(5);
4678var InspectionDecision = __webpack_require__(4);
4679var results = __webpack_require__(3);
4680var SubscriptionDropReason = __webpack_require__(14);
4681var PersistentEventStoreSubscription = __webpack_require__(52);
4682var ensure = __webpack_require__(8);
4683
4684function ConnectToPersistentSubscriptionOperation(
4685 log, cb, groupName, bufferSize, streamId, userCredentials, eventAppeared, subscriptionDropped,
4686 verboseLogging, getConnection
4687) {
4688 SubscriptionOperation.call(this, log, cb, streamId, false, userCredentials, eventAppeared, subscriptionDropped, verboseLogging, getConnection);
4689
4690 this._groupName = groupName;
4691 this._bufferSize = bufferSize;
4692 this._subscriptionId = null;
4693}
4694util.inherits(ConnectToPersistentSubscriptionOperation, SubscriptionOperation);
4695
4696ConnectToPersistentSubscriptionOperation.prototype._createSubscriptionPackage = function() {
4697 var dto = new ClientMessage.ConnectToPersistentSubscription({
4698 subscriptionId: this._groupName,
4699 eventStreamId: this._streamId,
4700 allowedInFlightMessages: this._bufferSize
4701 });
4702 return new TcpPackage(TcpCommand.ConnectToPersistentSubscription,
4703 this._userCredentials !== null ? TcpFlags.Authenticated : TcpFlags.None,
4704 this._correlationId,
4705 this._userCredentials !== null ? this._userCredentials.username : null,
4706 this._userCredentials !== null ? this._userCredentials.password : null,
4707 createBufferSegment(ClientMessage.ConnectToPersistentSubscription.encode(dto).finish()));
4708};
4709
4710ConnectToPersistentSubscriptionOperation.prototype._inspectPackage = function(pkg) {
4711 if (pkg.command === TcpCommand.PersistentSubscriptionConfirmation)
4712 {
4713 var dto = ClientMessage.PersistentSubscriptionConfirmation.decode(pkg.data.toBuffer());
4714 this._confirmSubscription(dto.lastCommitPosition, dto.lastEventNumber);
4715 this._subscriptionId = dto.subscriptionId;
4716 return new InspectionResult(InspectionDecision.Subscribed, "SubscriptionConfirmation");
4717 }
4718 if (pkg.command === TcpCommand.PersistentSubscriptionStreamEventAppeared)
4719 {
4720 var dto = ClientMessage.PersistentSubscriptionStreamEventAppeared.decode(pkg.data.toBuffer());
4721 this._onEventAppeared(new results.ResolvedEvent(dto.event));
4722 return new InspectionResult(InspectionDecision.DoNothing, "StreamEventAppeared");
4723 }
4724 if (pkg.command === TcpCommand.SubscriptionDropped)
4725 {
4726 var dto = ClientMessage.SubscriptionDropped.decode(pkg.data.toBuffer());
4727 if (dto.reason === ClientMessage.SubscriptionDropped.SubscriptionDropReason.AccessDenied)
4728 {
4729 this.dropSubscription(SubscriptionDropReason.AccessDenied, new Error("You do not have access to the stream."));
4730 return new InspectionResult(InspectionDecision.EndOperation, "SubscriptionDropped");
4731 }
4732 if (dto.reason === ClientMessage.SubscriptionDropped.SubscriptionDropReason.NotFound)
4733 {
4734 this.dropSubscription(SubscriptionDropReason.NotFound, new Error("Subscription not found"));
4735 return new InspectionResult(InspectionDecision.EndOperation, "SubscriptionDropped");
4736 }
4737 if (dto.reason === ClientMessage.SubscriptionDropped.SubscriptionDropReason.PersistentSubscriptionDeleted)
4738 {
4739 this.dropSubscription(SubscriptionDropReason.PersistentSubscriptionDeleted, new Error("Persistent subscription deleted."));
4740 return new InspectionResult(InspectionDecision.EndOperation, "SubscriptionDropped");
4741 }
4742 if (dto.reason === ClientMessage.SubscriptionDropped.SubscriptionDropReason.SubscriberMaxCountReached)
4743 {
4744 this.dropSubscription(SubscriptionDropReason.MaxSubscribersReached, new Error("Maximum subscribers reached."));
4745 return new InspectionResult(InspectionDecision.EndOperation, "SubscriptionDropped");
4746 }
4747 this.dropSubscription(SubscriptionDropReason.UserInitiated, null, this._getConnection());
4748 return new InspectionResult(InspectionDecision.EndOperation, "SubscriptionDropped");
4749 }
4750 return null;
4751};
4752
4753ConnectToPersistentSubscriptionOperation.prototype._createSubscriptionObject = function(lastCommitPosition, lastEventNumber) {
4754 return new PersistentEventStoreSubscription(this, this._streamId, lastCommitPosition, lastEventNumber);
4755};
4756
4757ConnectToPersistentSubscriptionOperation.prototype.notifyEventsProcessed = function(processedEvents) {
4758 ensure.notNull(processedEvents, "processedEvents");
4759 var dto = new ClientMessage.PersistentSubscriptionAckEvents({
4760 subscriptionId: this._subscriptionId,
4761 processedEventIds: processedEvents.map(function (x) {
4762 return guidParse.parse(x);
4763 })
4764 });
4765
4766 var pkg = new TcpPackage(TcpCommand.PersistentSubscriptionAckEvents,
4767 this._userCredentials !== null ? TcpFlags.Authenticated : TcpFlags.None,
4768 this._correlationId,
4769 this._userCredentials !== null ? this._userCredentials.username : null,
4770 this._userCredentials !== null ? this._userCredentials.password : null,
4771 createBufferSegment(ClientMessage.PersistentSubscriptionAckEvents.encode(dto).finish()));
4772 this._enqueueSend(pkg);
4773};
4774
4775ConnectToPersistentSubscriptionOperation.prototype.notifyEventsFailed = function(processedEvents, action, reason) {
4776 ensure.notNull(processedEvents, "processedEvents");
4777 ensure.notNull(reason, "reason");
4778 var dto = new ClientMessage.PersistentSubscriptionNakEvents({
4779 subscriptionId: this._subscriptionId,
4780 processedEventIds: processedEvents.map(function(x) { return guidParse.parse(x); }),
4781 message: reason,
4782 action: action
4783 });
4784
4785 var pkg = new TcpPackage(TcpCommand.PersistentSubscriptionNakEvents,
4786 this._userCredentials !== null ? TcpFlags.Authenticated : TcpFlags.None,
4787 this._correlationId,
4788 this._userCredentials !== null ? this._userCredentials.username : null,
4789 this._userCredentials !== null ? this._userCredentials.password : null,
4790 createBufferSegment(ClientMessage.PersistentSubscriptionNakEvents.encode(dto).finish()));
4791 this._enqueueSend(pkg);
4792};
4793
4794module.exports = ConnectToPersistentSubscriptionOperation;
4795
4796/***/ }),
4797/* 52 */
4798/***/ (function(module, exports, __webpack_require__) {
4799
4800var util = __webpack_require__(0);
4801
4802var EventStoreSubscription = __webpack_require__(28);
4803
4804
4805function PersistentEventStoreSubscription(subscriptionOperation, streamId, lastCommitPosition, lastEventNumber) {
4806 EventStoreSubscription.call(this, streamId, lastCommitPosition, lastEventNumber);
4807
4808 this._subscriptionOperation = subscriptionOperation;
4809}
4810util.inherits(PersistentEventStoreSubscription, EventStoreSubscription);
4811
4812PersistentEventStoreSubscription.prototype.unsubscribe = function() {
4813 this._subscriptionOperation.unsubscribe();
4814};
4815
4816PersistentEventStoreSubscription.prototype.notifyEventsProcessed = function(processedEvents) {
4817 this._subscriptionOperation.notifyEventsProcessed(processedEvents);
4818};
4819
4820PersistentEventStoreSubscription.prototype.notifyEventsFailed = function(processedEvents, action, reason) {
4821 this._subscriptionOperation.notifyEventsFailed(processedEvents, action, reason);
4822};
4823
4824module.exports = PersistentEventStoreSubscription;
4825
4826/***/ }),
4827/* 53 */
4828/***/ (function(module, exports, __webpack_require__) {
4829
4830var util = __webpack_require__(0);
4831
4832var TcpCommand = __webpack_require__(1);
4833var InspectionDecision = __webpack_require__(4);
4834var InspectionResult = __webpack_require__(5);
4835var ClientMessage = __webpack_require__(2);
4836var results = __webpack_require__(3);
4837var WrongExpectedVersionError = __webpack_require__(15);
4838var StreamDeletedError = __webpack_require__(16);
4839var AccessDeniedError = __webpack_require__(7);
4840
4841var OperationBase = __webpack_require__(6);
4842
4843
4844function DeleteStreamOperation(log, cb, requireMaster, stream, expectedVersion, hardDelete, userCredentials) {
4845 OperationBase.call(this, log, cb, TcpCommand.DeleteStream, TcpCommand.DeleteStreamCompleted, userCredentials);
4846 this._responseType = ClientMessage.DeleteStreamCompleted;
4847
4848 this._requireMaster = requireMaster;
4849 this._stream = stream;
4850 this._expectedVersion = expectedVersion;
4851 this._hardDelete = hardDelete;
4852}
4853util.inherits(DeleteStreamOperation, OperationBase);
4854
4855DeleteStreamOperation.prototype._createRequestDto = function() {
4856 return new ClientMessage.DeleteStream({
4857 eventStreamId: this._stream,
4858 expectedVersion: this._expectedVersion,
4859 requireMaster: this._requireMaster,
4860 hardDelete: this._hardDelete
4861 });
4862};
4863
4864DeleteStreamOperation.prototype._inspectResponse = function(response) {
4865 switch (response.result)
4866 {
4867 case ClientMessage.OperationResult.Success:
4868 this._succeed();
4869 return new InspectionResult(InspectionDecision.EndOperation, "Success");
4870 case ClientMessage.OperationResult.PrepareTimeout:
4871 return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
4872 case ClientMessage.OperationResult.CommitTimeout:
4873 return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
4874 case ClientMessage.OperationResult.ForwardTimeout:
4875 return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
4876 case ClientMessage.OperationResult.WrongExpectedVersion:
4877 this.fail(new WrongExpectedVersionError("Delete", this._stream, this._expectedVersion));
4878 return new InspectionResult(InspectionDecision.EndOperation, "WrongExpectedVersion");
4879 case ClientMessage.OperationResult.StreamDeleted:
4880 this.fail(new StreamDeletedError(this._stream));
4881 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
4882 case ClientMessage.OperationResult.InvalidTransaction:
4883 this.fail(new Error("Invalid transaction."));
4884 return new InspectionResult(InspectionDecision.EndOperation, "InvalidTransaction");
4885 case ClientMessage.OperationResult.AccessDenied:
4886 this.fail(new AccessDeniedError("Delete", this._stream));
4887 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
4888 default:
4889 throw new Error(util.format("Unexpected OperationResult: %d.", response.result));
4890 }
4891};
4892
4893DeleteStreamOperation.prototype._transformResponse = function(response) {
4894 return new results.DeleteResult(new results.Position(response.preparePosition || -1, response.commitPosition || -1));
4895};
4896
4897DeleteStreamOperation.prototype.toString = function() {
4898 return util.format("Stream: %s, ExpectedVersion: %s.", this._stream, this._expectedVersion);
4899};
4900
4901module.exports = DeleteStreamOperation;
4902
4903/***/ }),
4904/* 54 */
4905/***/ (function(module, exports, __webpack_require__) {
4906
4907var util = __webpack_require__(0);
4908var guidParse = __webpack_require__(13);
4909
4910var TcpCommand = __webpack_require__(1);
4911var InspectionDecision = __webpack_require__(4);
4912var InspectionResult = __webpack_require__(5);
4913var ClientMessage = __webpack_require__(2);
4914var WriteResult = __webpack_require__(3).WriteResult;
4915var Position = __webpack_require__(3).Position;
4916var WrongExpectedVersionError = __webpack_require__(15);
4917var StreamDeletedError = __webpack_require__(16);
4918var AccessDeniedError = __webpack_require__(7);
4919
4920var OperationBase = __webpack_require__(6);
4921
4922function AppendToStreamOperation(log, cb, requireMaster, stream, expectedVersion, events, userCredentials) {
4923 OperationBase.call(this, log, cb, TcpCommand.WriteEvents, TcpCommand.WriteEventsCompleted, userCredentials);
4924 this._responseType = ClientMessage.WriteEventsCompleted;
4925
4926 this._requireMaster = requireMaster;
4927 this._stream = stream;
4928 this._expectedVersion = expectedVersion;
4929 this._events = events;
4930}
4931util.inherits(AppendToStreamOperation, OperationBase);
4932
4933AppendToStreamOperation.prototype._createRequestDto = function() {
4934 var dtos = this._events.map(function(ev) {
4935 var eventId = guidParse.parse(ev.eventId);
4936 return {
4937 eventId: eventId, eventType: ev.type,
4938 dataContentType: ev.isJson ? 1 : 0, metadataContentType: 0,
4939 data: ev.data, metadata: ev.metadata
4940 };
4941 });
4942 return new ClientMessage.WriteEvents({
4943 eventStreamId: this._stream,
4944 expectedVersion: this._expectedVersion,
4945 events: dtos,
4946 requireMaster: this._requireMaster});
4947};
4948
4949AppendToStreamOperation.prototype._inspectResponse = function(response) {
4950 switch (response.result)
4951 {
4952 case ClientMessage.OperationResult.Success:
4953 if (this._wasCommitTimeout) this.log.debug("IDEMPOTENT WRITE SUCCEEDED FOR %s.", this);
4954 this._succeed();
4955 return new InspectionResult(InspectionDecision.EndOperation, "Success");
4956 case ClientMessage.OperationResult.PrepareTimeout:
4957 return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
4958 case ClientMessage.OperationResult.ForwardTimeout:
4959 return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
4960 case ClientMessage.OperationResult.CommitTimeout:
4961 this._wasCommitTimeout = true;
4962 return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
4963 case ClientMessage.OperationResult.WrongExpectedVersion:
4964 this.fail(new WrongExpectedVersionError("Append", this._stream, this._expectedVersion));
4965 return new InspectionResult(InspectionDecision.EndOperation, "WrongExpectedVersion");
4966 case ClientMessage.OperationResult.StreamDeleted:
4967 this.fail(new StreamDeletedError(this._stream));
4968 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
4969 case ClientMessage.OperationResult.InvalidTransaction:
4970 this.fail(new Error("Invalid transaction."));
4971 return new InspectionResult(InspectionDecision.EndOperation, "InvalidTransaction");
4972 case ClientMessage.OperationResult.AccessDenied:
4973 this.fail(new AccessDeniedError("Write", this._stream));
4974 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
4975 default:
4976 throw new Error("Unexpected OperationResult: " + response.result);
4977 }
4978};
4979
4980AppendToStreamOperation.prototype._transformResponse = function(response) {
4981 return new WriteResult(response.lastEventNumber, new Position(response.preparePosition || -1, response.commitPosition || -1));
4982};
4983
4984AppendToStreamOperation.prototype.toString = function() {
4985 return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
4986};
4987
4988module.exports = AppendToStreamOperation;
4989
4990/***/ }),
4991/* 55 */
4992/***/ (function(module, exports, __webpack_require__) {
4993
4994var util = __webpack_require__(0);
4995
4996var TcpCommand = __webpack_require__(1);
4997var InspectionDecision = __webpack_require__(4);
4998var InspectionResult = __webpack_require__(5);
4999var ClientMessage = __webpack_require__(2);
5000var EventStoreTransaction = __webpack_require__(29);
5001var AccessDeniedError = __webpack_require__(7);
5002var WrongExpectedVersionError = __webpack_require__(15);
5003var StreamDeletedError = __webpack_require__(16);
5004var OperationBase = __webpack_require__(6);
5005
5006function StartTransactionOperation(log, cb, requireMaster, stream, expectedVersion, parentConnection, userCredentials) {
5007 OperationBase.call(this, log, cb, TcpCommand.TransactionStart, TcpCommand.TransactionStartCompleted, userCredentials);
5008 this._responseType = ClientMessage.TransactionStartCompleted;
5009
5010 this._requireMaster = requireMaster;
5011 this._stream = stream;
5012 this._expectedVersion = expectedVersion;
5013 this._parentConnection = parentConnection;
5014}
5015util.inherits(StartTransactionOperation, OperationBase);
5016
5017StartTransactionOperation.prototype._createRequestDto = function() {
5018 return new ClientMessage.TransactionStart({
5019 eventStreamId: this._stream,
5020 expectedVersion: this._expectedVersion,
5021 requireMaster: this._requireMaster
5022 });
5023};
5024
5025StartTransactionOperation.prototype._inspectResponse = function(response) {
5026 switch (response.result)
5027 {
5028 case ClientMessage.OperationResult.Success:
5029 this._succeed();
5030 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5031 case ClientMessage.OperationResult.PrepareTimeout:
5032 return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
5033 case ClientMessage.OperationResult.CommitTimeout:
5034 return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
5035 case ClientMessage.OperationResult.ForwardTimeout:
5036 return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
5037 case ClientMessage.OperationResult.WrongExpectedVersion:
5038 this.fail(new WrongExpectedVersionError("Start transaction", this._stream, this._expectedVersion));
5039 return new InspectionResult(InspectionDecision.EndOperation, "WrongExpectedVersion");
5040 case ClientMessage.OperationResult.StreamDeleted:
5041 this.fail(new StreamDeletedError(this._stream));
5042 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
5043 case ClientMessage.OperationResult.InvalidTransaction:
5044 this.fail(new Error("Invalid transaction."));
5045 return new InspectionResult(InspectionDecision.EndOperation, "InvalidTransaction");
5046 case ClientMessage.OperationResult.AccessDenied:
5047 this.fail(new AccessDeniedError("Write", this._stream));
5048 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5049 default:
5050 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5051 }
5052};
5053
5054StartTransactionOperation.prototype._transformResponse = function(response) {
5055 return new EventStoreTransaction(response.transactionId, this.userCredentials, this._parentConnection);
5056};
5057
5058StartTransactionOperation.prototype.toString = function() {
5059 return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
5060};
5061
5062module.exports = StartTransactionOperation;
5063
5064/***/ }),
5065/* 56 */
5066/***/ (function(module, exports, __webpack_require__) {
5067
5068var util = __webpack_require__(0);
5069var guidParse = __webpack_require__(13);
5070
5071var TcpCommand = __webpack_require__(1);
5072var InspectionDecision = __webpack_require__(4);
5073var InspectionResult = __webpack_require__(5);
5074var ClientMessage = __webpack_require__(2);
5075var AccessDeniedError = __webpack_require__(7);
5076
5077var OperationBase = __webpack_require__(6);
5078
5079
5080function TransactionalWriteOperation(log, cb, requireMaster, transactionId, events, userCredentials) {
5081 OperationBase.call(this, log, cb, TcpCommand.TransactionWrite, TcpCommand.TransactionWriteCompleted, userCredentials);
5082 this._responseType = ClientMessage.TransactionWriteCompleted;
5083
5084 this._requireMaster = requireMaster;
5085 this._transactionId = transactionId;
5086 this._events = events;
5087}
5088util.inherits(TransactionalWriteOperation, OperationBase);
5089
5090TransactionalWriteOperation.prototype._createRequestDto = function() {
5091 var dtos = this._events.map(function(ev) {
5092 var eventId = guidParse.parse(ev.eventId);
5093 return {
5094 eventId: eventId, eventType: ev.type,
5095 dataContentType: ev.isJson ? 1 : 0, metadataContentType: 0,
5096 data: ev.data, metadata: ev.metadata
5097 };
5098 });
5099 return new ClientMessage.TransactionWrite({
5100 transactionId: this._transactionId,
5101 events: dtos,
5102 requireMaster: this._requireMaster
5103 });
5104};
5105
5106TransactionalWriteOperation.prototype._inspectResponse = function(response) {
5107 switch (response.result)
5108 {
5109 case ClientMessage.OperationResult.Success:
5110 this._succeed();
5111 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5112 case ClientMessage.OperationResult.PrepareTimeout:
5113 return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
5114 case ClientMessage.OperationResult.CommitTimeout:
5115 return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
5116 case ClientMessage.OperationResult.ForwardTimeout:
5117 return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
5118 case ClientMessage.OperationResult.AccessDenied:
5119 this.fail(new AccessDeniedError("Write", "trx:" + this._transactionId));
5120 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5121 default:
5122 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5123 }
5124};
5125
5126TransactionalWriteOperation.prototype._transformResponse = function(response) {
5127 return null;
5128};
5129
5130TransactionalWriteOperation.prototype.toString = function() {
5131 return util.format("TransactionId: %s", this._transactionId);
5132};
5133
5134module.exports = TransactionalWriteOperation;
5135
5136/***/ }),
5137/* 57 */
5138/***/ (function(module, exports, __webpack_require__) {
5139
5140var util = __webpack_require__(0);
5141
5142var TcpCommand = __webpack_require__(1);
5143var InspectionDecision = __webpack_require__(4);
5144var InspectionResult = __webpack_require__(5);
5145var ClientMessage = __webpack_require__(2);
5146var results = __webpack_require__(3);
5147var WrongExpectedVersionError = __webpack_require__(15);
5148var StreamDeletedError = __webpack_require__(16);
5149var AccessDeniedError = __webpack_require__(7);
5150
5151var OperationBase = __webpack_require__(6);
5152
5153
5154function CommitTransactionOperation(log, cb, requireMaster, transactionId, userCredentials) {
5155 OperationBase.call(this, log, cb, TcpCommand.TransactionCommit, TcpCommand.TransactionCommitCompleted, userCredentials);
5156 this._responseType = ClientMessage.TransactionCommitCompleted;
5157
5158 this._requireMaster = requireMaster;
5159 this._transactionId = transactionId;
5160}
5161util.inherits(CommitTransactionOperation, OperationBase);
5162
5163CommitTransactionOperation.prototype._createRequestDto = function() {
5164 return new ClientMessage.TransactionCommit({
5165 transactionId: this._transactionId,
5166 requireMaster: this._requireMaster
5167 });
5168};
5169
5170CommitTransactionOperation.prototype._inspectResponse = function(response) {
5171 switch (response.result)
5172 {
5173 case ClientMessage.OperationResult.Success:
5174 this._succeed();
5175 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5176 case ClientMessage.OperationResult.PrepareTimeout:
5177 return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
5178 case ClientMessage.OperationResult.CommitTimeout:
5179 return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
5180 case ClientMessage.OperationResult.ForwardTimeout:
5181 return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
5182 case ClientMessage.OperationResult.WrongExpectedVersion:
5183 this.fail(new WrongExpectedVersionError("Commit", this._transactionId));
5184 return new InspectionResult(InspectionDecision.EndOperation, "WrongExpectedVersion");
5185 case ClientMessage.OperationResult.StreamDeleted:
5186 this.fail(new StreamDeletedError(this._transactionId));
5187 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
5188 case ClientMessage.OperationResult.InvalidTransaction:
5189 this.fail(new Error("Invalid transaction."));
5190 return new InspectionResult(InspectionDecision.EndOperation, "InvalidTransaction");
5191 case ClientMessage.OperationResult.AccessDenied:
5192 this.fail(new AccessDeniedError("Write", this._transactionId));
5193 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5194 default:
5195 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5196 }
5197};
5198
5199CommitTransactionOperation.prototype._transformResponse = function(response) {
5200 var logPosition = new results.Position(response.preparePosition || -1, response.commitPosition || -1);
5201 return new results.WriteResult(response.lastEventNumber, logPosition);
5202};
5203
5204CommitTransactionOperation.prototype.toString = function() {
5205 return util.format("TransactionId: %s", this._transactionId);
5206};
5207
5208module.exports = CommitTransactionOperation;
5209
5210/***/ }),
5211/* 58 */
5212/***/ (function(module, exports, __webpack_require__) {
5213
5214var util = __webpack_require__(0);
5215
5216var TcpCommand = __webpack_require__(1);
5217var ClientMessage = __webpack_require__(2);
5218var InspectionResult = __webpack_require__(5);
5219var InspectionDecision = __webpack_require__(4);
5220var results = __webpack_require__(3);
5221var AccessDeniedError = __webpack_require__(7);
5222
5223var OperationBase = __webpack_require__(6);
5224
5225function ReadEventOperation(log, cb, stream, eventNumber, resolveLinkTos, requireMaster, userCredentials) {
5226 OperationBase.call(this, log, cb, TcpCommand.ReadEvent, TcpCommand.ReadEventCompleted, userCredentials);
5227 this._responseType = ClientMessage.ReadEventCompleted;
5228
5229 this._stream = stream;
5230 this._eventNumber = eventNumber;
5231 this._resolveLinkTos = resolveLinkTos;
5232 this._requireMaster = requireMaster;
5233}
5234util.inherits(ReadEventOperation, OperationBase);
5235
5236ReadEventOperation.prototype._createRequestDto = function() {
5237 return new ClientMessage.ReadEvent({
5238 eventStreamId: this._stream,
5239 eventNumber: this._eventNumber,
5240 resolveLinkTos: this._resolveLinkTos,
5241 requireMaster: this._requireMaster
5242 });
5243};
5244
5245ReadEventOperation.prototype._inspectResponse = function(response) {
5246 switch (response.result)
5247 {
5248 case ClientMessage.ReadEventCompleted.ReadEventResult.Success:
5249 this._succeed();
5250 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5251 case ClientMessage.ReadEventCompleted.ReadEventResult.NotFound:
5252 this._succeed();
5253 return new InspectionResult(InspectionDecision.EndOperation, "NotFound");
5254 case ClientMessage.ReadEventCompleted.ReadEventResult.NoStream:
5255 this._succeed();
5256 return new InspectionResult(InspectionDecision.EndOperation, "NoStream");
5257 case ClientMessage.ReadEventCompleted.ReadEventResult.StreamDeleted:
5258 this._succeed();
5259 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
5260 case ClientMessage.ReadEventCompleted.ReadEventResult.Error:
5261 this.fail(new Error("Server error: " + response.error));
5262 return new InspectionResult(InspectionDecision.EndOperation, "Error");
5263 case ClientMessage.ReadEventCompleted.ReadEventResult.AccessDenied:
5264 this.fail(new AccessDeniedError("Read", this._stream));
5265 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5266 default:
5267 throw new Error(util.format("Unexpected ReadEventResult: %s.", response.result));
5268 }
5269};
5270
5271ReadEventOperation.prototype._transformResponse = function(response) {
5272 return new results.EventReadResult(convert(response.result), this._stream, this._eventNumber, response.event);
5273};
5274
5275function convert(result)
5276{
5277 switch (result)
5278 {
5279 case ClientMessage.ReadEventCompleted.ReadEventResult.Success:
5280 return results.EventReadStatus.Success;
5281 case ClientMessage.ReadEventCompleted.ReadEventResult.NotFound:
5282 return results.EventReadStatus.NotFound;
5283 case ClientMessage.ReadEventCompleted.ReadEventResult.NoStream:
5284 return results.EventReadStatus.NoStream;
5285 case ClientMessage.ReadEventCompleted.ReadEventResult.StreamDeleted:
5286 return results.EventReadStatus.StreamDeleted;
5287 default:
5288 throw new Error(util.format("Unexpected ReadEventResult: %s.", result));
5289 }
5290}
5291
5292ReadEventOperation.prototype.toString = function() {
5293 return util.format("Stream: %s, EventNumber: %s, ResolveLinkTo: %s, RequireMaster: %s",
5294 this._stream, this._eventNumber, this._resolveLinkTos, this._requireMaster);
5295};
5296
5297module.exports = ReadEventOperation;
5298
5299/***/ }),
5300/* 59 */
5301/***/ (function(module, exports, __webpack_require__) {
5302
5303var util = __webpack_require__(0);
5304
5305var TcpCommand = __webpack_require__(1);
5306var ClientMessage = __webpack_require__(2);
5307var ReadDirection = __webpack_require__(19);
5308var StatusCode = __webpack_require__(30);
5309var InspectionResult = __webpack_require__(5);
5310var InspectionDecision = __webpack_require__(4);
5311var results = __webpack_require__(3);
5312var AccessDeniedError = __webpack_require__(7);
5313
5314var OperationBase = __webpack_require__(6);
5315
5316function ReadStreamEventsForwardOperation(
5317 log, cb, stream, fromEventNumber, maxCount, resolveLinkTos, requireMaster, userCredentials
5318) {
5319 OperationBase.call(this, log, cb, TcpCommand.ReadStreamEventsForward, TcpCommand.ReadStreamEventsForwardCompleted, userCredentials);
5320 this._responseType = ClientMessage.ReadStreamEventsCompleted;
5321
5322 this._stream = stream;
5323 this._fromEventNumber = fromEventNumber;
5324 this._maxCount = maxCount;
5325 this._resolveLinkTos = resolveLinkTos;
5326 this._requireMaster = requireMaster;
5327}
5328util.inherits(ReadStreamEventsForwardOperation, OperationBase);
5329
5330ReadStreamEventsForwardOperation.prototype._createRequestDto = function() {
5331 return new ClientMessage.ReadStreamEvents({
5332 eventStreamId: this._stream,
5333 fromEventNumber: this._fromEventNumber,
5334 maxCount: this._maxCount,
5335 resolveLinkTos: this._resolveLinkTos,
5336 requireMaster: this._requireMaster
5337 });
5338};
5339
5340ReadStreamEventsForwardOperation.prototype._inspectResponse = function(response) {
5341 switch (response.result)
5342 {
5343 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.Success:
5344 this._succeed();
5345 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5346 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.StreamDeleted:
5347 this._succeed();
5348 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
5349 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.NoStream:
5350 this._succeed();
5351 return new InspectionResult(InspectionDecision.EndOperation, "NoStream");
5352 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.Error:
5353 this.fail(new Error("Server error: " + response.error));
5354 return new InspectionResult(InspectionDecision.EndOperation, "Error");
5355 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.AccessDenied:
5356 this.fail(new AccessDeniedError("Read", this._stream));
5357 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5358 default:
5359 throw new Error(util.format("Unexpected ReadStreamResult: %s.", response.result));
5360 }
5361};
5362
5363ReadStreamEventsForwardOperation.prototype._transformResponse = function(response) {
5364 return new results.StreamEventsSlice(
5365 StatusCode.convert(response.result),
5366 this._stream,
5367 this._fromEventNumber,
5368 ReadDirection.Forward,
5369 response.events,
5370 response.nextEventNumber,
5371 response.lastEventNumber,
5372 response.isEndOfStream
5373 )
5374};
5375
5376ReadStreamEventsForwardOperation.prototype.toString = function() {
5377 return util.format("Stream: %s, FromEventNumber: %d, MaxCount: %d, ResolveLinkTos: %s, RequireMaster: %s",
5378 this._stream, this._fromEventNumber, this._maxCount, this._resolveLinkTos, this._requireMaster);
5379};
5380
5381module.exports = ReadStreamEventsForwardOperation;
5382
5383/***/ }),
5384/* 60 */
5385/***/ (function(module, exports, __webpack_require__) {
5386
5387var util = __webpack_require__(0);
5388
5389var TcpCommand = __webpack_require__(1);
5390var ClientMessage = __webpack_require__(2);
5391var ReadDirection = __webpack_require__(19);
5392var StatusCode = __webpack_require__(30);
5393var InspectionResult = __webpack_require__(5);
5394var InspectionDecision = __webpack_require__(4);
5395var results = __webpack_require__(3);
5396var AccessDeniedError = __webpack_require__(7);
5397
5398var OperationBase = __webpack_require__(6);
5399
5400function ReadStreamEventsBackwardOperation(
5401 log, cb, stream, fromEventNumber, maxCount, resolveLinkTos, requireMaster, userCredentials
5402) {
5403 OperationBase.call(this, log, cb, TcpCommand.ReadStreamEventsBackward, TcpCommand.ReadStreamEventsBackwardCompleted, userCredentials);
5404 this._responseType = ClientMessage.ReadStreamEventsCompleted;
5405
5406 this._stream = stream;
5407 this._fromEventNumber = fromEventNumber;
5408 this._maxCount = maxCount;
5409 this._resolveLinkTos = resolveLinkTos;
5410 this._requireMaster = requireMaster;
5411}
5412util.inherits(ReadStreamEventsBackwardOperation, OperationBase);
5413
5414ReadStreamEventsBackwardOperation.prototype._createRequestDto = function() {
5415 return new ClientMessage.ReadStreamEvents({
5416 eventStreamId: this._stream,
5417 fromEventNumber: this._fromEventNumber,
5418 maxCount: this._maxCount,
5419 resolveLinkTos: this._resolveLinkTos,
5420 requireMaster: this._requireMaster
5421 });
5422};
5423
5424ReadStreamEventsBackwardOperation.prototype._inspectResponse = function(response) {
5425 switch (response.result)
5426 {
5427 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.Success:
5428 this._succeed();
5429 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5430 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.StreamDeleted:
5431 this._succeed();
5432 return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
5433 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.NoStream:
5434 this._succeed();
5435 return new InspectionResult(InspectionDecision.EndOperation, "NoStream");
5436 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.Error:
5437 this.fail(new Error("Server error: " + response.error));
5438 return new InspectionResult(InspectionDecision.EndOperation, "Error");
5439 case ClientMessage.ReadStreamEventsCompleted.ReadStreamResult.AccessDenied:
5440 this.fail(new AccessDeniedError("Read", this._stream));
5441 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5442 default:
5443 throw new Error(util.format("Unexpected ReadStreamResult: %s.", response.result));
5444 }
5445};
5446
5447ReadStreamEventsBackwardOperation.prototype._transformResponse = function(response) {
5448 return new results.StreamEventsSlice(
5449 StatusCode.convert(response.result),
5450 this._stream,
5451 this._fromEventNumber,
5452 ReadDirection.Backward,
5453 response.events,
5454 response.nextEventNumber,
5455 response.lastEventNumber,
5456 response.isEndOfStream
5457 )
5458};
5459
5460ReadStreamEventsBackwardOperation.prototype.toString = function() {
5461 return util.format("Stream: %s, FromEventNumber: %d, MaxCount: %d, ResolveLinkTos: %s, RequireMaster: %s",
5462 this._stream, this._fromEventNumber, this._maxCount, this._resolveLinkTos, this._requireMaster);
5463};
5464
5465module.exports = ReadStreamEventsBackwardOperation;
5466
5467/***/ }),
5468/* 61 */
5469/***/ (function(module, exports, __webpack_require__) {
5470
5471var util = __webpack_require__(0);
5472
5473var TcpCommand = __webpack_require__(1);
5474var ClientMessage = __webpack_require__(2);
5475var ReadDirection = __webpack_require__(19);
5476var InspectionResult = __webpack_require__(5);
5477var InspectionDecision = __webpack_require__(4);
5478var results = __webpack_require__(3);
5479var AccessDeniedError = __webpack_require__(7);
5480
5481var OperationBase = __webpack_require__(6);
5482
5483function ReadAllEventsForwardOperation(
5484 log, cb, position, maxCount, resolveLinkTos, requireMaster, userCredentials
5485) {
5486 OperationBase.call(this, log, cb, TcpCommand.ReadAllEventsForward, TcpCommand.ReadAllEventsForwardCompleted, userCredentials);
5487 this._responseType = ClientMessage.ReadAllEventsCompleted;
5488
5489 this._position = position;
5490 this._maxCount = maxCount;
5491 this._resolveLinkTos = resolveLinkTos;
5492 this._requireMaster = requireMaster;
5493}
5494util.inherits(ReadAllEventsForwardOperation, OperationBase);
5495
5496ReadAllEventsForwardOperation.prototype._createRequestDto = function() {
5497 return new ClientMessage.ReadAllEvents({
5498 commitPosition: this._position.commitPosition,
5499 preparePosition: this._position.preparePosition,
5500 maxCount: this._maxCount,
5501 resolveLinkTos: this._resolveLinkTos,
5502 requireMaster: this._requireMaster
5503 });
5504};
5505
5506ReadAllEventsForwardOperation.prototype._inspectResponse = function(response) {
5507 switch (response.result)
5508 {
5509 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.Success:
5510 this._succeed();
5511 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5512 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.Error:
5513 this.fail(new Error("Server error: " + response.error));
5514 return new InspectionResult(InspectionDecision.EndOperation, "Error");
5515 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.AccessDenied:
5516 this.fail(new AccessDeniedError("Read", "$all"));
5517 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5518 default:
5519 throw new Error(util.format("Unexpected ReadStreamResult: %s.", response.result));
5520 }
5521};
5522
5523ReadAllEventsForwardOperation.prototype._transformResponse = function(response) {
5524 return new results.AllEventsSlice(
5525 ReadDirection.Forward,
5526 new results.Position(response.commitPosition, response.preparePosition),
5527 new results.Position(response.nextCommitPosition, response.nextPreparePosition),
5528 response.events
5529 )
5530};
5531
5532ReadAllEventsForwardOperation.prototype.toString = function() {
5533 return util.format("Position: %j, MaxCount: %d, ResolveLinkTos: %s, RequireMaster: %s",
5534 this._position, this._maxCount, this._resolveLinkTos, this._requireMaster);
5535};
5536
5537module.exports = ReadAllEventsForwardOperation;
5538
5539/***/ }),
5540/* 62 */
5541/***/ (function(module, exports, __webpack_require__) {
5542
5543var util = __webpack_require__(0);
5544
5545var TcpCommand = __webpack_require__(1);
5546var ClientMessage = __webpack_require__(2);
5547var ReadDirection = __webpack_require__(19);
5548var InspectionResult = __webpack_require__(5);
5549var InspectionDecision = __webpack_require__(4);
5550var results = __webpack_require__(3);
5551var AccessDeniedError = __webpack_require__(7);
5552
5553var OperationBase = __webpack_require__(6);
5554
5555function ReadAllEventsBackwardOperation(
5556 log, cb, position, maxCount, resolveLinkTos, requireMaster, userCredentials
5557) {
5558 OperationBase.call(this, log, cb, TcpCommand.ReadAllEventsBackward, TcpCommand.ReadAllEventsBackwardCompleted, userCredentials);
5559 this._responseType = ClientMessage.ReadAllEventsCompleted;
5560
5561 this._position = position;
5562 this._maxCount = maxCount;
5563 this._resolveLinkTos = resolveLinkTos;
5564 this._requireMaster = requireMaster;
5565}
5566util.inherits(ReadAllEventsBackwardOperation, OperationBase);
5567
5568ReadAllEventsBackwardOperation.prototype._createRequestDto = function() {
5569 return new ClientMessage.ReadAllEvents({
5570 commitPosition: this._position.commitPosition,
5571 preparePosition: this._position.preparePosition,
5572 maxCount: this._maxCount,
5573 resolveLinkTos: this._resolveLinkTos,
5574 requireMaster: this._requireMaster
5575 });
5576};
5577
5578ReadAllEventsBackwardOperation.prototype._inspectResponse = function(response) {
5579 switch (response.result)
5580 {
5581 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.Success:
5582 this._succeed();
5583 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5584 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.Error:
5585 this.fail(new Error("Server error: " + response.error));
5586 return new InspectionResult(InspectionDecision.EndOperation, "Error");
5587 case ClientMessage.ReadAllEventsCompleted.ReadAllResult.AccessDenied:
5588 this.fail(new AccessDeniedError("Read", "$all"));
5589 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5590 default:
5591 throw new Error(util.format("Unexpected ReadStreamResult: %s.", response.result));
5592 }
5593};
5594
5595ReadAllEventsBackwardOperation.prototype._transformResponse = function(response) {
5596 return new results.AllEventsSlice(
5597 ReadDirection.Backward,
5598 new results.Position(response.commitPosition, response.preparePosition),
5599 new results.Position(response.nextCommitPosition, response.nextPreparePosition),
5600 response.events
5601 )
5602};
5603
5604ReadAllEventsBackwardOperation.prototype.toString = function() {
5605 return util.format("Position: %j, MaxCount: %d, ResolveLinkTos: %s, RequireMaster: %s",
5606 this._position, this._maxCount, this._resolveLinkTos, this._requireMaster);
5607};
5608
5609module.exports = ReadAllEventsBackwardOperation;
5610
5611/***/ }),
5612/* 63 */
5613/***/ (function(module, exports, __webpack_require__) {
5614
5615var util = __webpack_require__(0);
5616
5617var ensure = __webpack_require__(8);
5618var OperationBase = __webpack_require__(6);
5619var TcpCommand = __webpack_require__(1);
5620var ClientMessage = __webpack_require__(2);
5621var SystemConsumerStrategies = __webpack_require__(17);
5622var InspectionDecision = __webpack_require__(4);
5623var InspectionResult = __webpack_require__(5);
5624var results = __webpack_require__(3);
5625
5626
5627function CreatePersistentSubscriptionOperation(log, cb, stream, groupName, settings, userCredentials) {
5628 OperationBase.call(this, log, cb, TcpCommand.CreatePersistentSubscription, TcpCommand.CreatePersistentSubscriptionCompleted, userCredentials);
5629
5630 ensure.notNull(settings, "settings");
5631 this._resolveLinkTos = settings.resolveLinkTos;
5632 this._stream = stream;
5633 this._groupName = groupName;
5634 this._startFromBeginning = settings.startFrom;
5635 this._maxRetryCount = settings.maxRetryCount;
5636 this._liveBufferSize = settings.liveBufferSize;
5637 this._readBatchSize = settings.readBatchSize;
5638 this._bufferSize = settings.historyBufferSize;
5639 this._recordStatistics = settings.extraStatistics;
5640 this._messageTimeoutMilliseconds = settings.messageTimeout;
5641 this._checkPointAfter = settings.checkPointAfter;
5642 this._minCheckPointCount = settings.minCheckPointCount;
5643 this._maxCheckPointCount = settings.maxCheckPointCount;
5644 this._maxSubscriberCount = settings.maxSubscriberCount;
5645 this._namedConsumerStrategy = settings.namedConsumerStrategy;
5646
5647 this._responseType = ClientMessage.CreatePersistentSubscriptionCompleted;
5648}
5649util.inherits(CreatePersistentSubscriptionOperation, OperationBase);
5650
5651CreatePersistentSubscriptionOperation.prototype._createRequestDto = function() {
5652 return new ClientMessage.CreatePersistentSubscription({
5653 subscriptionGroupName: this._groupName,
5654 eventStreamId: this._stream,
5655 resolveLinkTos: this._resolveLinkTos,
5656 startFrom: this._startFromBeginning,
5657 messageTimeoutMilliseconds: this._messageTimeoutMilliseconds,
5658 recordStatistics: this._recordStatistics,
5659 liveBufferSize: this._liveBufferSize,
5660 readBatchSize: this._readBatchSize,
5661 bufferSize: this._bufferSize,
5662 maxRetryCount: this._maxRetryCount,
5663 preferRoundRobin: this._namedConsumerStrategy === SystemConsumerStrategies.RoundRobin,
5664 checkpointAfterTime: this._checkPointAfter,
5665 checkpointMaxCount: this._maxCheckPointCount,
5666 checkpointMinCount: this._minCheckPointCount,
5667 subscriberMaxCount: this._maxSubscriberCount,
5668 namedConsumerStrategy: this._namedConsumerStrategy
5669 });
5670};
5671
5672CreatePersistentSubscriptionOperation.prototype._inspectResponse = function(response) {
5673 switch (response.result)
5674 {
5675 case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.Success:
5676 this._succeed();
5677 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5678 case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.Fail:
5679 this.fail(new Error(util.format("Subscription group %s on stream %s failed '%s'", this._groupName, this._stream, response.reason)));
5680 return new InspectionResult(InspectionDecision.EndOperation, "Fail");
5681 case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.AccessDenied:
5682 this.fail(new Error(util.format("Write access denied for stream '%s'.", this._stream)));
5683 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5684 case ClientMessage.CreatePersistentSubscriptionCompleted.CreatePersistentSubscriptionResult.AlreadyExists:
5685 this.fail(new Error(util.format("Subscription group %s on stream %s already exists", this._groupName, this._stream)));
5686 return new InspectionResult(InspectionDecision.EndOperation, "AlreadyExists");
5687 default:
5688 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5689 }
5690};
5691
5692CreatePersistentSubscriptionOperation.prototype._transformResponse = function(response) {
5693 return new results.PersistentSubscriptionCreateResult(results.PersistentSubscriptionCreateStatus.Success);
5694};
5695
5696CreatePersistentSubscriptionOperation.prototype.toString = function() {
5697 return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
5698};
5699
5700module.exports = CreatePersistentSubscriptionOperation;
5701
5702/***/ }),
5703/* 64 */
5704/***/ (function(module, exports, __webpack_require__) {
5705
5706var util = __webpack_require__(0);
5707
5708var ensure = __webpack_require__(8);
5709var OperationBase = __webpack_require__(6);
5710var TcpCommand = __webpack_require__(1);
5711var ClientMessage = __webpack_require__(2);
5712var SystemConsumerStrategies = __webpack_require__(17);
5713var InspectionDecision = __webpack_require__(4);
5714var InspectionResult = __webpack_require__(5);
5715var results = __webpack_require__(3);
5716
5717
5718function UpdatePersistentSubscriptionOperation(log, cb, stream, groupName, settings, userCredentials) {
5719 OperationBase.call(this, log, cb, TcpCommand.UpdatePersistentSubscription, TcpCommand.UpdatePersistentSubscriptionCompleted, userCredentials);
5720
5721 ensure.notNull(settings, "settings");
5722 this._resolveLinkTos = settings.resolveLinkTos;
5723 this._stream = stream;
5724 this._groupName = groupName;
5725 this._startFromBeginning = settings.startFrom;
5726 this._maxRetryCount = settings.maxRetryCount;
5727 this._liveBufferSize = settings.liveBufferSize;
5728 this._readBatchSize = settings.readBatchSize;
5729 this._bufferSize = settings.historyBufferSize;
5730 this._recordStatistics = settings.extraStatistics;
5731 this._messageTimeoutMilliseconds = settings.messageTimeout;
5732 this._checkPointAfter = settings.checkPointAfter;
5733 this._minCheckPointCount = settings.minCheckPointCount;
5734 this._maxCheckPointCount = settings.maxCheckPointCount;
5735 this._maxSubscriberCount = settings.maxSubscriberCount;
5736 this._namedConsumerStrategy = settings.namedConsumerStrategy;
5737
5738 this._responseType = ClientMessage.UpdatePersistentSubscriptionCompleted;
5739}
5740util.inherits(UpdatePersistentSubscriptionOperation, OperationBase);
5741
5742UpdatePersistentSubscriptionOperation.prototype._createRequestDto = function() {
5743 return new ClientMessage.UpdatePersistentSubscription({
5744 subscriptionGroupName: this._groupName,
5745 eventStreamId: this._stream,
5746 resolveLinkTos: this._resolveLinkTos,
5747 startFrom: this._startFromBeginning,
5748 messageTimeoutMilliseconds: this._messageTimeoutMilliseconds,
5749 recordStatistics: this._recordStatistics,
5750 liveBufferSize: this._liveBufferSize,
5751 readBatchSize: this._readBatchSize,
5752 bufferSize: this._bufferSize,
5753 maxRetryCount: this._maxRetryCount,
5754 preferRoundRobin: this._namedConsumerStrategy === SystemConsumerStrategies.RoundRobin,
5755 checkpointAfterTime: this._checkPointAfter,
5756 checkpointMaxCount: this._maxCheckPointCount,
5757 checkpointMinCount: this._minCheckPointCount,
5758 subscriberMaxCount: this._maxSubscriberCount,
5759 namedConsumerStrategy: this._namedConsumerStrategy
5760 });
5761};
5762
5763UpdatePersistentSubscriptionOperation.prototype._inspectResponse = function(response) {
5764 switch (response.result)
5765 {
5766 case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.Success:
5767 this._succeed();
5768 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5769 case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.Fail:
5770 this.fail(new Error(util.format("Subscription group %s on stream %s failed '%s'", this._groupName, this._stream, response.reason)));
5771 return new InspectionResult(InspectionDecision.EndOperation, "Fail");
5772 case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.AccessDenied:
5773 this.fail(new Error(util.format("Write access denied for stream '%s'.", this._stream)));
5774 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5775 case ClientMessage.UpdatePersistentSubscriptionCompleted.UpdatePersistentSubscriptionResult.DoesNotExist:
5776 this.fail(new Error(util.format("Subscription group %s on stream %s does not exist", this._groupName, this._stream)));
5777 return new InspectionResult(InspectionDecision.EndOperation, "DoesNotExist");
5778 default:
5779 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5780 }
5781};
5782
5783UpdatePersistentSubscriptionOperation.prototype._transformResponse = function(response) {
5784 return new results.PersistentSubscriptionUpdateResult(results.PersistentSubscriptionUpdateStatus.Success);
5785};
5786
5787UpdatePersistentSubscriptionOperation.prototype.toString = function() {
5788 return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
5789};
5790
5791module.exports = UpdatePersistentSubscriptionOperation;
5792
5793/***/ }),
5794/* 65 */
5795/***/ (function(module, exports, __webpack_require__) {
5796
5797var util = __webpack_require__(0);
5798
5799var OperationBase = __webpack_require__(6);
5800var TcpCommand = __webpack_require__(1);
5801var ClientMessage = __webpack_require__(2);
5802var InspectionDecision = __webpack_require__(4);
5803var InspectionResult = __webpack_require__(5);
5804var results = __webpack_require__(3);
5805
5806
5807function DeletePersistentSubscriptionOperation(log, cb, stream, groupName, userCredentials) {
5808 OperationBase.call(this, log, cb, TcpCommand.DeletePersistentSubscription, TcpCommand.DeletePersistentSubscriptionCompleted, userCredentials);
5809
5810 this._stream = stream;
5811 this._groupName = groupName;
5812
5813 this._responseType = ClientMessage.DeletePersistentSubscriptionCompleted;
5814}
5815util.inherits(DeletePersistentSubscriptionOperation, OperationBase);
5816
5817DeletePersistentSubscriptionOperation.prototype._createRequestDto = function() {
5818 return new ClientMessage.DeletePersistentSubscription({
5819 subscriptionGroupName: this._groupName,
5820 eventStreamId: this._stream
5821 });
5822};
5823
5824DeletePersistentSubscriptionOperation.prototype._inspectResponse = function(response) {
5825 switch (response.result)
5826 {
5827 case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult.Success:
5828 this._succeed();
5829 return new InspectionResult(InspectionDecision.EndOperation, "Success");
5830 case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult.Fail:
5831 this.fail(new Error(util.format("Subscription group %s on stream %s failed '%s'", this._groupName, this._stream, response.reason)));
5832 return new InspectionResult(InspectionDecision.EndOperation, "Fail");
5833 case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult.AccessDenied:
5834 this.fail(new Error(util.format("Write access denied for stream '%s'.", this._stream)));
5835 return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
5836 case ClientMessage.DeletePersistentSubscriptionCompleted.DeletePersistentSubscriptionResult.DoesNotExist:
5837 this.fail(new Error(util.format("Subscription group %s on stream %s does not exist", this._groupName, this._stream)));
5838 return new InspectionResult(InspectionDecision.EndOperation, "DoesNotExist");
5839 default:
5840 throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
5841 }
5842};
5843
5844DeletePersistentSubscriptionOperation.prototype._transformResponse = function(response) {
5845 return new results.PersistentSubscriptionDeleteResult(results.PersistentSubscriptionDeleteStatus.Success);
5846};
5847
5848DeletePersistentSubscriptionOperation.prototype.toString = function() {
5849 return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
5850};
5851
5852module.exports = DeletePersistentSubscriptionOperation;
5853
5854/***/ }),
5855/* 66 */
5856/***/ (function(module, exports, __webpack_require__) {
5857
5858var util = __webpack_require__(0);
5859var Long = __webpack_require__(9);
5860
5861var EventStoreCatchUpSubscription = __webpack_require__(31);
5862var SliceReadStatus = __webpack_require__(21);
5863
5864function EventStoreStreamCatchUpSubscription(
5865 connection, log, streamId, fromEventNumberExclusive, resolveLinkTos, userCredentials,
5866 eventAppeared, liveProcessingStarted, subscriptionDropped,
5867 verboseLogging, readBatchSize
5868){
5869 EventStoreCatchUpSubscription.call(this, connection, log, streamId, resolveLinkTos, userCredentials,
5870 eventAppeared, liveProcessingStarted, subscriptionDropped,
5871 verboseLogging, readBatchSize);
5872
5873 //Ensure.NotNullOrEmpty(streamId, "streamId");
5874
5875 this._lastProcessedEventNumber = fromEventNumberExclusive === null ? Long.fromNumber(-1) : fromEventNumberExclusive;
5876 this._nextReadEventNumber = fromEventNumberExclusive === null ? Long.fromNumber(0) : fromEventNumberExclusive.add(1);
5877}
5878util.inherits(EventStoreStreamCatchUpSubscription, EventStoreCatchUpSubscription);
5879
5880function delay(ms, result) {
5881 return new Promise(function (resolve, reject) {
5882 setTimeout(resolve, ms, result);
5883 })
5884}
5885
5886EventStoreStreamCatchUpSubscription.prototype._readEventsTill = function(
5887 connection, resolveLinkTos, userCredentials, lastCommitPosition, lastEventNumber
5888) {
5889 var self = this;
5890
5891 function processEvents(events, index) {
5892 if (index >= events.length) return Promise.resolve();
5893
5894 return self._tryProcess(events[index])
5895 .then(function() {
5896 return processEvents(events, index + 1);
5897 });
5898 }
5899
5900 function readNext() {
5901 return connection.readStreamEventsForward(self.streamId, self._nextReadEventNumber, self.readBatchSize, resolveLinkTos, userCredentials)
5902 .then(function(slice) {
5903 switch(slice.status) {
5904 case SliceReadStatus.Success:
5905 return processEvents(slice.events, 0)
5906 .then(function() {
5907 self._nextReadEventNumber = slice.nextEventNumber;
5908 var done = Promise.resolve(lastEventNumber === null ? slice.isEndOfStream : slice.nextEventNumber.compare(lastEventNumber) > 0);
5909 if (!done && slice.isEndOfStream) return delay(100, false);
5910 return done;
5911 });
5912 case SliceReadStatus.StreamNotFound:
5913 if (lastEventNumber && lastEventNumber.compare(-1) !== 0) {
5914 throw new Error(util.format("Impossible: stream %s disappeared in the middle of catching up subscription.", self.streamId));
5915 }
5916 return true;
5917 case SliceReadStatus.StreamDeleted:
5918 throw new Error("Stream deleted: " + self.streamId);
5919 default:
5920 throw new Error(util.format("Unexpected StreamEventsSlice.Status: %s.", slice.status));
5921 }
5922 })
5923 .then(function(done) {
5924 if (done || self._shouldStop)
5925 return;
5926 return readNext();
5927 })
5928 }
5929 return readNext()
5930 .then(function() {
5931 if (self._verbose) {
5932 self._log.debug("Catch-up Subscription to %s: finished reading events, nextReadEventNumber = %d.",
5933 self.isSubscribedToAll ? '<all>' : self.streamId, self._nextReadEventNumber);
5934 }
5935 });
5936};
5937
5938EventStoreStreamCatchUpSubscription.prototype._tryProcess = function(e) {
5939 var processed = false;
5940 var promise;
5941 if (e.originalEventNumber.compare(this._lastProcessedEventNumber) > 0) {
5942 promise = this._eventAppeared(this, e);
5943 this._lastProcessedEventNumber = e.originalEventNumber;
5944 processed = true;
5945 }
5946 if (this._verbose) {
5947 this._log.debug("Catch-up Subscription to %s: %s event (%s, %d, %s @ %d).",
5948 this.isSubscribedToAll ? '<all>' : this.streamId, processed ? "processed" : "skipping",
5949 e.originalEvent.eventStreamId, e.originalEvent.eventNumber, e.originalEvent.eventType, e.originalEventNumber);
5950 }
5951 return (promise && promise.then) ? promise : Promise.resolve();
5952};
5953
5954
5955module.exports = EventStoreStreamCatchUpSubscription;
5956
5957/***/ }),
5958/* 67 */
5959/***/ (function(module, exports, __webpack_require__) {
5960
5961var util = __webpack_require__(0);
5962
5963var EventStoreCatchUpSubscription = __webpack_require__(31);
5964var results = __webpack_require__(3);
5965
5966
5967function EventStoreAllCatchUpSubscription(
5968 connection, log, fromPositionExclusive, resolveLinkTos, userCredentials,
5969 eventAppeared, liveProcessingStarted, subscriptionDropped,
5970 verboseLogging, readBatchSize
5971) {
5972 EventStoreCatchUpSubscription.call(this, connection, log, '', resolveLinkTos, userCredentials,
5973 eventAppeared, liveProcessingStarted, subscriptionDropped,
5974 verboseLogging, readBatchSize);
5975
5976 this._lastProcessedPosition = fromPositionExclusive || new results.Position(-1,-1);
5977 this._nextReadPosition = fromPositionExclusive || new results.Position(0,0);
5978}
5979util.inherits(EventStoreAllCatchUpSubscription, EventStoreCatchUpSubscription);
5980
5981EventStoreAllCatchUpSubscription.prototype._readEventsTill = function(
5982 connection, resolveLinkTos, userCredentials, lastCommitPosition, lastEventNumber
5983) {
5984 var self = this;
5985
5986 function processEvents(events, index) {
5987 if (index >= events.length) return Promise.resolve();
5988 if (events[index].originalPosition === null) throw new Error("Subscription event came up with no OriginalPosition.");
5989
5990 return self._tryProcess(events[index])
5991 .then(function() {
5992 return processEvents(events, index + 1);
5993 });
5994 }
5995
5996 function readNext() {
5997 return connection.readAllEventsForward(self._nextReadPosition, self.readBatchSize, resolveLinkTos, userCredentials)
5998 .then(function(slice) {
5999 return processEvents(slice.events, 0)
6000 .then(function() {
6001 self._nextReadPosition = slice.nextPosition;
6002 return (lastCommitPosition === null)
6003 ? slice.isEndOfStream
6004 : slice.nextPosition.compareTo(new results.Position(lastCommitPosition, lastCommitPosition)) >= 0;
6005 });
6006 })
6007 .then(function(done) {
6008 if (done || self._shouldStop) return;
6009 return readNext();
6010 });
6011 }
6012
6013 return readNext()
6014 .then(function() {
6015 if (self._verbose)
6016 self._log.debug("Catch-up Subscription to %s: finished reading events, nextReadPosition = %s.",
6017 self.isSubscribedToAll ? "<all>" : self.streamId, self._nextReadPosition);
6018 });
6019};
6020
6021
6022EventStoreAllCatchUpSubscription.prototype._tryProcess = function(e) {
6023 var processed = false;
6024 var promise;
6025 if (e.originalPosition.compareTo(this._lastProcessedPosition) > 0)
6026 {
6027 promise = this._eventAppeared(this, e);
6028 this._lastProcessedPosition = e.originalPosition;
6029 processed = true;
6030 }
6031 if (this._verbose) {
6032 this._log.debug("Catch-up Subscription to %s: %s event (%s, %d, %s @ %s).",
6033 this.streamId || '<all>', processed ? "processed" : "skipping",
6034 e.originalEvent.eventStreamId, e.originalEvent.eventNumber, e.originalEvent.eventType, e.originalPosition);
6035 }
6036 return (promise && promise.then) ? promise : Promise.resolve();
6037};
6038
6039module.exports = EventStoreAllCatchUpSubscription;
6040
6041
6042/***/ }),
6043/* 68 */
6044/***/ (function(module, exports, __webpack_require__) {
6045
6046var util = __webpack_require__(0);
6047
6048var EventStorePersistentSubscriptionBase = __webpack_require__(69);
6049var messages = __webpack_require__(20);
6050
6051function EventStorePersistentSubscription(
6052 subscriptionId, streamId, eventAppeared, subscriptionDropped, userCredentials, log, verboseLogging, settings,
6053 handler, bufferSize, autoAck
6054) {
6055 bufferSize = bufferSize === undefined ? 10 : bufferSize;
6056 autoAck = autoAck === undefined ? true : !!autoAck;
6057
6058 EventStorePersistentSubscriptionBase.call(this, subscriptionId, streamId, eventAppeared, subscriptionDropped,
6059 userCredentials, log, verboseLogging, settings, bufferSize, autoAck);
6060
6061 this._handler = handler;
6062}
6063util.inherits(EventStorePersistentSubscription, EventStorePersistentSubscriptionBase);
6064
6065EventStorePersistentSubscription.prototype._startSubscription = function(
6066 subscriptionId, streamId, bufferSize, userCredentials, onEventAppeared, onSubscriptionDropped, settings
6067) {
6068 var self = this;
6069 return new Promise(function(resolve, reject){
6070 function cb(err, result) {
6071 if (err) return reject(err);
6072 resolve(result);
6073 }
6074 self._handler.enqueueMessage(new messages.StartPersistentSubscriptionMessage(cb, subscriptionId, streamId,
6075 bufferSize, userCredentials, onEventAppeared, onSubscriptionDropped, settings.maxRetries,
6076 settings.operationTimeout));
6077 });
6078};
6079
6080module.exports = EventStorePersistentSubscription;
6081
6082/***/ }),
6083/* 69 */
6084/***/ (function(module, exports, __webpack_require__) {
6085
6086var util = __webpack_require__(0);
6087var ensure = __webpack_require__(8);
6088var PersistentSubscriptionNakEventAction = __webpack_require__(32);
6089var SubscriptionDropReason = __webpack_require__(14);
6090
6091function DropSubscriptionEvent() {}
6092
6093function EventStorePersistentSubscriptionBase(
6094 subscriptionId, streamId,
6095 eventAppeared, subscriptionDropped,
6096 userCredentials, log, verboseLogging, settings, bufferSize, autoAck
6097) {
6098 bufferSize = bufferSize === undefined ? 10 : bufferSize;
6099 autoAck = autoAck === undefined ? true : autoAck;
6100
6101 this._subscriptionId = subscriptionId;
6102 this._streamId = streamId;
6103 this._eventAppeared = eventAppeared;
6104 this._subscriptionDropped = subscriptionDropped;
6105 this._userCredentials = userCredentials;
6106 this._log = log;
6107 this._verbose = verboseLogging;
6108 this._settings = settings;
6109 this._bufferSize = bufferSize;
6110 this._autoAck = autoAck;
6111
6112 this._subscription = null;
6113 this._dropData = null;
6114 this._queue = [];
6115 this._isProcessing = false;
6116 this._isDropped = false;
6117}
6118
6119EventStorePersistentSubscriptionBase.prototype.start = function() {
6120 this._stopped = false;
6121
6122 var self = this;
6123 return this._startSubscription(this._subscriptionId, this._streamId, this._bufferSize, this._userCredentials,
6124 this._onEventAppeared.bind(this), this._onSubscriptionDropped.bind(this), this._settings)
6125 .then(function(subscription) {
6126 self._log.debug('Subscription started.');
6127 self._subscription = subscription;
6128 return self;
6129 });
6130};
6131
6132EventStorePersistentSubscriptionBase.prototype._startSubscription = function() {
6133 throw new Error("EventStorePersistentSubscriptionBase._startSubscription abstract method called." +
6134 this.constructor.name);
6135};
6136
6137/**
6138 * @param {ResolvedEvent[]|ResolvedEvent} events
6139 */
6140EventStorePersistentSubscriptionBase.prototype.acknowledge = function(events) {
6141 ensure.notNull(events, "events");
6142
6143 if (this._subscription === null) throw new Error("Invalid operation. Subscription is not active yet.");
6144 if (!Array.isArray(events)) events = [events];
6145 var ids = events.map(function(x) { return x.originalEvent.eventId; });
6146 this._subscription.notifyEventsProcessed(ids);
6147};
6148
6149/**
6150 * @param {ResolvedEvent[]|ResolvedEvent} events
6151 * @param {number} action One of PersistentSubscriptionNakEventAction
6152 * @param {string} reason
6153 */
6154EventStorePersistentSubscriptionBase.prototype.fail = function(events, action, reason) {
6155 ensure.notNull(events, "events");
6156 PersistentSubscriptionNakEventAction.isValid(action);
6157 ensure.notNull(reason, "reason");
6158
6159 if (this._subscription === null) throw new Error("Invalid operation. Subscription is not active yet.");
6160 if (!Array.isArray(events)) events = [events];
6161 var ids = events.map(function(x) { return x.originalEvent.eventId; });
6162 this._subscription.notifyEventsFailed(ids, action, reason);
6163};
6164
6165//TODO: this should return a promise
6166EventStorePersistentSubscriptionBase.prototype.stop = function() {
6167 if (this._verbose) this._log.debug("Persistent Subscription to %s: requesting stop...", this._streamId);
6168 this._enqueueSubscriptionDropNotification(SubscriptionDropReason.UserInitiated, null);
6169 //TODO figure out timeout with Promise still running
6170 //if (!_stopped.Wait(timeout))
6171 //throw new TimeoutException(string.Format("Could not stop {0} in time.", GetType().Name));
6172};
6173
6174EventStorePersistentSubscriptionBase.prototype._enqueueSubscriptionDropNotification = function(reason, error) {
6175 // if drop data was already set -- no need to enqueue drop again, somebody did that already
6176 if (!this._dropData) {
6177 this._dropData = {reason: reason, error: error};
6178 this._enqueue(new DropSubscriptionEvent());
6179 }
6180};
6181
6182EventStorePersistentSubscriptionBase.prototype._onSubscriptionDropped = function(subscription, reason, exception) {
6183 this._enqueueSubscriptionDropNotification(reason, exception);
6184};
6185
6186EventStorePersistentSubscriptionBase.prototype._onEventAppeared = function(subscription, resolvedEvent) {
6187 this._enqueue(resolvedEvent);
6188};
6189
6190EventStorePersistentSubscriptionBase.prototype._enqueue = function(resolvedEvent) {
6191 this._queue.push(resolvedEvent);
6192 if (!this._isProcessing) {
6193 this._isProcessing = true;
6194 setImmediate(this._processQueue.bind(this));
6195 }
6196};
6197
6198function runAsync(fn) {
6199 try {
6200 return Promise.resolve(fn());
6201 } catch(e) {
6202 return Promise.reject(e);
6203 }
6204}
6205
6206EventStorePersistentSubscriptionBase.prototype._processQueue = function() {
6207 var ev = this._queue.shift();
6208 if (!ev) {
6209 this._isProcessing = false;
6210 return;
6211 }
6212
6213 if (ev instanceof DropSubscriptionEvent) // drop subscription artificial ResolvedEvent
6214 {
6215 if (this._dropData === null) throw new Error("Drop reason not specified.");
6216 this._dropSubscription(this._dropData.reason, this._dropData.error);
6217 this._isProcessing = false;
6218 return;
6219 }
6220 if (this._dropData !== null)
6221 {
6222 this._dropSubscription(this._dropData.reason, this._dropData.error);
6223 this._isProcessing = false;
6224 return;
6225 }
6226 var self = this;
6227 runAsync(function() {
6228 return self._eventAppeared(self, ev);
6229 })
6230 .then(function() {
6231 if(self._autoAck) self._subscription.notifyEventsProcessed([ev.originalEvent.eventId]);
6232 if (self._verbose) {
6233 self._log.debug("Persistent Subscription to %s: processed event (%s, %d, %s @ %d).",
6234 self._streamId, ev.originalEvent.eventStreamId, ev.originalEvent.eventNumber, ev.originalEvent.eventType,
6235 ev.originalEventNumber);
6236 }
6237 return false;
6238 }, function(err) {
6239 //TODO GFY should we autonak here?
6240 self._dropSubscription(SubscriptionDropReason.EventHandlerException, err);
6241 self._isProcessing = false;
6242 return true;
6243 })
6244 .then(function (faulted) {
6245 if (faulted) return;
6246 self._processQueue();
6247 });
6248};
6249
6250EventStorePersistentSubscriptionBase.prototype._dropSubscription = function(reason, error) {
6251 if (!this._isDropped)
6252 {
6253 this._isDropped = true;
6254 if (this._verbose) {
6255 this._log.debug("Persistent Subscription to %s: dropping subscription, reason: %s %s.",
6256 this._streamId, reason, error);
6257 }
6258
6259 if (this._subscription !== null) this._subscription.unsubscribe();
6260 if (this._subscriptionDropped !== null) {
6261 try {
6262 this._subscriptionDropped(this, reason, error);
6263 } catch (e) {
6264 this._log.error(e, "Persistent Subscription to %s: subscriptionDropped callback failed.", this._streamId);
6265 }
6266 }
6267 this._stopped = true;
6268 }
6269};
6270
6271module.exports = EventStorePersistentSubscriptionBase;
6272
6273
6274/***/ }),
6275/* 70 */
6276/***/ (function(module, exports) {
6277
6278exports.metastreamOf = function(stream) {
6279 return '$$' + stream;
6280};
6281exports.isMetastream = function(stream) {
6282 return stream.indexOf('$$') === 0;
6283};
6284
6285/***/ }),
6286/* 71 */
6287/***/ (function(module, exports) {
6288
6289const SystemEventTypes = Object.freeze({
6290 StreamMetadata: '$metadata'
6291});
6292
6293module.exports = SystemEventTypes;
6294
6295/***/ }),
6296/* 72 */
6297/***/ (function(module, exports) {
6298
6299function StaticEndpointDiscoverer(tcpEndPoint, useSsl) {
6300 this._nodeEndpoints = {
6301 tcpEndPoint: useSsl ? null : tcpEndPoint,
6302 secureTcpEndPoint: useSsl ? tcpEndPoint : null
6303 }
6304}
6305
6306StaticEndpointDiscoverer.prototype.discover = function(failedTcpEndpoint) {
6307 return Promise.resolve(this._nodeEndpoints);
6308};
6309
6310module.exports = StaticEndpointDiscoverer;
6311
6312/***/ }),
6313/* 73 */
6314/***/ (function(module, exports, __webpack_require__) {
6315
6316var http = __webpack_require__(33);
6317var util = __webpack_require__(0);
6318var dns = __webpack_require__(74);
6319var GossipSeed = __webpack_require__(23);
6320
6321function NodeEndPoints(tcpEndPoint, secureTcpEndPoint) {
6322 if (tcpEndPoint === null && secureTcpEndPoint === null) throw new Error('Both endpoints are null.');
6323 Object.defineProperties(this, {
6324 tcpEndPoint: {
6325 enumerable: true,
6326 value: tcpEndPoint
6327 },
6328 secureTcpEndPoint: {
6329 enumerable: true,
6330 value: secureTcpEndPoint
6331 }
6332 });
6333}
6334
6335function ClusterDnsEndPointDiscoverer(log, clusterDns, maxDiscoverAttempts, managerExternalHttpPort, gossipSeeds, gossipTimeout) {
6336 if (!clusterDns && (!gossipSeeds || gossipSeeds.length === 0)) throw new Error('Both clusterDns and gossipSeeds are null/empty.');
6337 this._log = log;
6338 this._clusterDns = clusterDns;
6339 this._maxDiscoverAttempts = maxDiscoverAttempts;
6340 this._managerExternalHttpPort = managerExternalHttpPort;
6341 this._gossipSeeds = gossipSeeds;
6342 this._gossipTimeout = gossipTimeout;
6343 this._oldGossip = null;
6344}
6345
6346ClusterDnsEndPointDiscoverer.prototype.discover = function(failedTcpEndPoint) {
6347 var attempt = 1;
6348 var self = this;
6349 function discover(resolve, reject) {
6350 self._discoverEndPoint(failedTcpEndPoint)
6351 .then(function (endPoints) {
6352 if (!endPoints) {
6353 self._log.info(util.format("Discovering attempt %d/%d failed: no candidate found.", attempt, self._maxDiscoverAttempts));
6354 }
6355 return endPoints;
6356 })
6357 .catch(function (exc) {
6358 self._log.info(util.format("Discovering attempt %d/%d failed with error: %s.\n%s", attempt, self._maxDiscoverAttempts, exc, exc.stack));
6359 })
6360 .then(function (endPoints) {
6361 if (endPoints) return resolve(endPoints);
6362 if (attempt++ === self._maxDiscoverAttempts) {
6363 return reject(new Error('Failed to discover candidate in ' + self._maxDiscoverAttempts + ' attempts.'));
6364 }
6365 setTimeout(discover, 500, resolve, reject);
6366 });
6367 }
6368 return new Promise(function (resolve, reject) {
6369 discover(resolve, reject);
6370 });
6371};
6372
6373/**
6374 * Discover Cluster endpoints
6375 * @param {Object} failedTcpEndPoint
6376 * @returns {Promise.<NodeEndPoints>}
6377 * @private
6378 */
6379ClusterDnsEndPointDiscoverer.prototype._discoverEndPoint = function (failedTcpEndPoint) {
6380 try {
6381 var mainPromise = this._oldGossip
6382 ? Promise.resolve(this._getGossipCandidatesFromOldGossip(this._oldGossip, failedTcpEndPoint))
6383 : this._getGossipCandidatesFromDns();
6384 var self = this;
6385 var j = 0;
6386 return mainPromise.then(function (gossipCandidates) {
6387 var loopPromise = Promise.resolve();
6388 for (var i = 0; i < gossipCandidates.length; i++) {
6389 loopPromise = loopPromise.then(function (endPoints) {
6390 if (endPoints) return endPoints;
6391 return self._tryGetGossipFrom(gossipCandidates[j++])
6392 .then(function (gossip) {
6393 if (!gossip || !gossip.members || gossip.members.length === 0) return;
6394 var bestNode = self._tryDetermineBestNode(gossip.members);
6395 if (bestNode) {
6396 self._oldGossip = gossip.members;
6397 return bestNode;
6398 }
6399 });
6400 });
6401 }
6402 return loopPromise;
6403 });
6404 } catch (e) {
6405 return Promise.reject(e);
6406 }
6407};
6408
6409ClusterDnsEndPointDiscoverer.prototype._getGossipCandidatesFromOldGossip = function (oldGossip, failedTcpEndPoint) {
6410 if (!failedTcpEndPoint) return this._arrangeGossipCandidates(oldGossip);
6411 var gossipCandidates = oldGossip.filter(function(x) {
6412 return !(x.externalTcpPort === failedTcpEndPoint.port && x.externalTcpIp === failedTcpEndPoint.host);
6413 });
6414 return this._arrangeGossipCandidates(gossipCandidates);
6415};
6416
6417ClusterDnsEndPointDiscoverer.prototype._arrangeGossipCandidates = function (members) {
6418 var result = new Array(members.length);
6419 var i = -1;
6420 var j = members.length;
6421 for (var k = 0; k < members.length; ++k)
6422 {
6423 if (members[k].state === 'Manager') {
6424 result[--j] = new GossipSeed({host: members[k].externalHttpIp, port: members[k].externalHttpPort});
6425 } else {
6426 result[++i] = new GossipSeed({host: members[k].externalHttpIp, port: members[k].externalHttpPort});
6427 }
6428 }
6429 this._randomShuffle(result, 0, i); // shuffle nodes
6430 this._randomShuffle(result, j, members.length - 1); // shuffle managers
6431 return result;
6432};
6433
6434ClusterDnsEndPointDiscoverer.prototype._getGossipCandidatesFromDns = function () {
6435 var self = this;
6436 return new Promise(function (resolve, reject) {
6437 if (self._gossipSeeds && self._gossipSeeds.length > 0) {
6438 var endpoints = self._gossipSeeds;
6439 self._randomShuffle(endpoints, 0, endpoints.length - 1);
6440 resolve(endpoints);
6441 } else {
6442 const dnsOptions = {
6443 family: 4,
6444 hints: dns.ADDRCONFIG | dns.V4MAPPED,
6445 all: true
6446 };
6447 dns.lookup(self._clusterDns, dnsOptions, function (err, addresses) {
6448 if (err) {
6449 return reject(err);
6450 }
6451 if (!addresses || addresses.length === 0) {
6452 return reject(new Error('No result from dns lookup for ' + self._clusterDns));
6453 }
6454 var endpoints = addresses.map(function (x) {
6455 return new GossipSeed({host: x.address, port: self._managerExternalHttpPort});
6456 });
6457 resolve(endpoints);
6458 });
6459 }
6460 });
6461};
6462
6463ClusterDnsEndPointDiscoverer.prototype._tryGetGossipFrom = function (endPoint) {
6464 var options = {
6465 host: endPoint.endPoint.host,
6466 port: endPoint.endPoint.port,
6467 path: '/gossip?format=json'
6468 };
6469 if (endPoint.hostHeader) {
6470 options.headers = {'Host': endPoint.hostHeader};
6471 }
6472 this._log.info('Try get gossip from', endPoint);
6473 var self = this;
6474 return new Promise(function (resolve, reject) {
6475 var timedout = false;
6476 http.request(options, function (res) {
6477 if (timedout) return;
6478 var result = '';
6479 if (res.statusCode !== 200) {
6480 self._log.info('Trying to get gossip from', endPoint, 'failed with status code:', res.statusCode);
6481 resolve();
6482 return;
6483 }
6484 res.on('data', function (chunk) {
6485 result += chunk.toString();
6486 });
6487 res.on('end', function () {
6488 try {
6489 result = JSON.parse(result);
6490 } catch (e) {
6491 return resolve();
6492 }
6493 resolve(result);
6494 });
6495 })
6496 .setTimeout(self._gossipTimeout, function () {
6497 self._log.info('Trying to get gossip from', endPoint, 'timed out.');
6498 timedout = true;
6499 resolve();
6500 })
6501 .on('error', function (e) {
6502 if (timedout) return;
6503 self._log.info('Trying to get gossip from', endPoint, 'failed with error:', e);
6504 resolve();
6505 })
6506 .end();
6507 });
6508};
6509
6510const VNodeStates = Object.freeze({
6511 'Initializing': 0,
6512 'Unknown': 1,
6513 'PreReplica': 2,
6514 'CatchingUp': 3,
6515 'Clone': 4,
6516 'Slave': 5,
6517 'PreMaster': 6,
6518 'Master': 7,
6519 'Manager': 8,
6520 'ShuttingDown': 9,
6521 'Shutdown': 10
6522});
6523
6524ClusterDnsEndPointDiscoverer.prototype._tryDetermineBestNode = function (members) {
6525 var notAllowedStates = [
6526 'Manager',
6527 'ShuttingDown',
6528 'Shutdown'
6529 ];
6530 var node = members
6531 .filter(function (x) {
6532 return (x.isAlive && notAllowedStates.indexOf(x.state) === -1);
6533 })
6534 .sort(function (a, b) {
6535 return VNodeStates[b.state] - VNodeStates[a.state];
6536 })[0];
6537 if (!node)
6538 {
6539 //_log.Info("Unable to locate suitable node. Gossip info:\n{0}.", string.Join("\n", members.Select(x => x.ToString())));
6540 return null;
6541 }
6542
6543 var normTcp = {host: node.externalTcpIp, port: node.externalTcpPort};
6544 var secTcp = node.externalSecureTcpPort > 0
6545 ? {host: externalTcpIp, port: node.externalSecureTcpPort}
6546 : null;
6547 this._log.info(util.format("Discovering: found best choice [%j,%j] (%s).", normTcp, secTcp === null ? "n/a" : secTcp, node.state));
6548 return new NodeEndPoints(normTcp, secTcp);
6549};
6550
6551function rndNext(min, max) {
6552 min = Math.ceil(min);
6553 max = Math.floor(max);
6554 return Math.floor(Math.random() * (max - min)) + min;
6555}
6556
6557ClusterDnsEndPointDiscoverer.prototype._randomShuffle = function (arr, i, j) {
6558 if (i >= j) return;
6559 for (var k = i; k <= j; ++k)
6560 {
6561 var index = rndNext(k, j + 1);
6562 var tmp = arr[index];
6563 arr[index] = arr[k];
6564 arr[k] = tmp;
6565 }
6566};
6567
6568module.exports = ClusterDnsEndPointDiscoverer;
6569
6570/***/ }),
6571/* 74 */
6572/***/ (function(module, exports) {
6573
6574module.exports = require("dns");
6575
6576/***/ }),
6577/* 75 */
6578/***/ (function(module, exports, __webpack_require__) {
6579
6580const ensure = __webpack_require__(8);
6581const ProjectionsClient = __webpack_require__(76);
6582
6583/**
6584 * Creates a new instance of ProjectionsManager.
6585 * @param {Logger} log Instance of Logger to use for logging.
6586 * @param {string} httpEndPoint HTTP endpoint of an Event Store server.
6587 * @param {number} operationTimeout Operation timeout in milliseconds.
6588 * @constructor
6589 */
6590function ProjectionsManager(log, httpEndPoint, operationTimeout) {
6591 ensure.notNull(log, "log");
6592 ensure.notNull(httpEndPoint, "httpEndPoint");
6593 this._client = new ProjectionsClient(log, operationTimeout);
6594 this._httpEndPoint = httpEndPoint;
6595}
6596
6597/**
6598 * Enables a projection.
6599 * @param name The name of the projection.
6600 * @param userCredentials Credentials for a user with permission to enable a projection.
6601 * @returns {Promise<void>}
6602 */
6603ProjectionsManager.prototype.enable = function(name, userCredentials) {
6604 return this._client.enable(this._httpEndPoint, name, userCredentials);
6605};
6606
6607/**
6608 * Aborts and disables a projection without writing a checkpoint.
6609 * @param name The name of the projection.
6610 * @param userCredentials Credentials for a user with permission to disable a projection.
6611 * @returns {Promise<void>}
6612 */
6613ProjectionsManager.prototype.disable = function(name, userCredentials) {
6614 return this._client.disable(this._httpEndPoint, name, userCredentials);
6615};
6616
6617/**
6618 * Disables a projection.
6619 * @param name The name of the projection.
6620 * @param userCredentials Credentials for a user with permission to disable a projection.
6621 * @returns {Promise<void>}
6622 */
6623ProjectionsManager.prototype.abort = function(name, userCredentials) {
6624 return this._client.abort(this._httpEndPoint, name, userCredentials);
6625};
6626
6627/**
6628 * Reset a projection. (This will re-emit events, streams that are written to from the projection will also be soft deleted)
6629 * @param name The name of the projection.
6630 * @param userCredentials Credentials for a user with permission to reset a projection.
6631 * @returns {Promise<void>}
6632 */
6633ProjectionsManager.prototype.reset = function(name, userCredentials) {
6634 return this._client.reset(this._httpEndPoint, name, userCredentials);
6635};
6636
6637/**
6638 * Creates a one-time query.
6639 * @param query The JavaScript source code for the query.
6640 * @param userCredentials Credentials for a user with permission to create a query.
6641 * @returns {Promise<void>}
6642 */
6643ProjectionsManager.prototype.createOneTime = function(query, userCredentials) {
6644 return this._client.createOneTime(this._httpEndPoint, query, userCredentials);
6645};
6646
6647/**
6648 * Creates a one-time query.
6649 * @param name A name for the query.
6650 * @param query The JavaScript source code for the query.
6651 * @param userCredentials Credentials for a user with permission to create a query.
6652 * @returns {Promise<void>}
6653 */
6654ProjectionsManager.prototype.createTransient = function(name, query, userCredentials) {
6655 return this._client.createTransient(this._httpEndPoint, query, userCredentials);
6656};
6657
6658/**
6659 * Creates a one-time query.
6660 * @param name The name of the projection.
6661 * @param query The JavaScript source code for the query.
6662 * @param trackEmittedStreams Whether the streams emitted by this projection should be tracked.
6663 * @param userCredentials Credentials for a user with permission to create a query.
6664 * @returns {Promise<void>}
6665 */
6666ProjectionsManager.prototype.createContinuous = function(name, query, trackEmittedStreams, userCredentials) {
6667 return this._client.createContinuous(this._httpEndPoint, name, query, trackEmittedStreams, userCredentials);
6668};
6669
6670/**
6671 * Lists the status of all projections.
6672 * @param userCredentials Credentials for the operation.
6673 * @returns {Promise<ProjectionDetails[]>}
6674 */
6675ProjectionsManager.prototype.listAll = function(userCredentials) {
6676 return this._client.listAll(this._httpEndPoint, userCredentials);
6677};
6678
6679/**
6680 * Lists the status of all one-time projections.
6681 * @param userCredentials Credentials for the operation.
6682 * @returns {Promise<ProjectionDetails[]>}
6683 */
6684ProjectionsManager.prototype.listOneTime = function(userCredentials) {
6685 return this._client.listOneTime(this._httpEndPoint, userCredentials);
6686};
6687
6688/**
6689 * Lists the status of all continuous projections.
6690 * @param userCredentials Credentials for the operation.
6691 * @returns {Promise<ProjectionDetails[]>}
6692 */
6693ProjectionsManager.prototype.listContinuous = function(userCredentials) {
6694 return this._client.listContinuous(this._httpEndPoint, userCredentials);
6695};
6696
6697/**
6698 * Gets the status of a projection.
6699 * @param name The name of the projection.
6700 * @param userCredentials Credentials for the operation.
6701 * @returns {Promise<string>} String of JSON containing projection status.
6702 */
6703ProjectionsManager.prototype.getStatus = function(name, userCredentials) {
6704 return this._client.getStatus(this._httpEndPoint, name, userCredentials);
6705};
6706
6707/**
6708 * Gets the state of a projection.
6709 * @param name The name of the projection.
6710 * @param userCredentials Credentials for the operation.
6711 * @returns {Promise<string>} String of JSON containing projection state.
6712 */
6713ProjectionsManager.prototype.getState = function(name, userCredentials) {
6714 return this._client.getState(this._httpEndPoint, name, userCredentials);
6715};
6716
6717/**
6718 * Gets the state of a projection for a specified partition.
6719 * @param name The name of the projection.
6720 * @param partitionId The id of the partition.
6721 * @param userCredentials Credentials for the operation.
6722 * @returns {Promise<string>} String of JSON containing projection state.
6723 */
6724ProjectionsManager.prototype.getPartitionState = function(name, partitionId, userCredentials) {
6725 return this._client.getPartitionState(this._httpEndPoint, name, partitionId, userCredentials);
6726};
6727
6728/**
6729 * Gets the state of a projection.
6730 * @param name The name of the projection.
6731 * @param userCredentials Credentials for the operation.
6732 * @returns {Promise<string>} String of JSON containing projection state.
6733 */
6734ProjectionsManager.prototype.getResult = function(name, userCredentials) {
6735 return this._client.getResult(this._httpEndPoint, name, userCredentials);
6736};
6737
6738/**
6739 * Gets the state of a projection for a specified partition.
6740 * @param name The name of the projection.
6741 * @param partitionId The id of the partition.
6742 * @param userCredentials Credentials for the operation.
6743 * @returns {Promise<string>} String of JSON containing projection state.
6744 */
6745ProjectionsManager.prototype.getPartitionResult = function(name, partitionId, userCredentials) {
6746 return this._client.getPartitionResult(this._httpEndPoint, name, partitionId, userCredentials);
6747};
6748
6749/**
6750 * Gets the statistics of a projection.
6751 * @param name The name of the projection.
6752 * @param userCredentials Credentials for the operation.
6753 * @returns {Promise<string>} String of JSON containing projection statistics.
6754 */
6755ProjectionsManager.prototype.getStatistics = function(name, userCredentials) {
6756 return this._client.getStatistics(this._httpEndPoint, name, userCredentials);
6757};
6758
6759/**
6760 * Gets the status of a query.
6761 * @param name The name of the query.
6762 * @param userCredentials Credentials for the operation.
6763 * @returns {Promise<string>} String of JSON containing query status.
6764 */
6765ProjectionsManager.prototype.getQuery = function(name, userCredentials) {
6766 return this._client.getQuery(this._httpEndPoint, name, userCredentials);
6767};
6768
6769/**
6770 * Updates the definition of a query.
6771 * @param name The name of the query.
6772 * @param query The JavaScript source code for the query.
6773 * @param userCredentials Credentials for the operation.
6774 * @returns {Promise<void>}
6775 */
6776ProjectionsManager.prototype.updateQuery = function(name, query, userCredentials) {
6777 return this._client.updateQuery(this._httpEndPoint, name, query, userCredentials);
6778};
6779
6780/**
6781 * Updates the definition of a query.
6782 * @param name The name of the projection.
6783 * @param deleteEmittedStreams Whether to delete the streams that were emitted by this projection.
6784 * @param deleteStateStream Where to delete the state stream for this projection
6785 * @param deleteCheckpointStream Where to delete the checkpoint stream for this projection
6786 * @param userCredentials Credentials for a user with permission to delete a projection.
6787 * @returns {Promise<void>}
6788 */
6789ProjectionsManager.prototype.delete = function(name, deleteEmittedStreams, deleteStateStream, deleteCheckpointStream, userCredentials) {
6790 return this._client.delete(this._httpEndPoint, name, deleteEmittedStreams, deleteStateStream, deleteCheckpointStream, userCredentials);
6791};
6792
6793module.exports = ProjectionsManager;
6794
6795/***/ }),
6796/* 76 */
6797/***/ (function(module, exports, __webpack_require__) {
6798
6799const http = __webpack_require__(33);
6800const url = __webpack_require__(77);
6801const util = __webpack_require__(0);
6802const ProjectionCommandFailedError = __webpack_require__(35);
6803
6804const HTTP_OK = 200;
6805const HTTP_CREATED = 201;
6806
6807function safeParseJson(json) {
6808 try {
6809 return JSON.parse(json);
6810 } catch(e) {
6811 return null;
6812 }
6813}
6814
6815function ProjectionsClient(log, operationTimeout) {
6816 this._log = log;
6817 this._operationTimeout = operationTimeout;
6818}
6819
6820ProjectionsClient.prototype.enable = function(httpEndPoint, name, userCredentials) {
6821 return this.sendPost(httpEndPoint + '/projection/' + name + '/command/enable', '', userCredentials, HTTP_OK);
6822};
6823
6824ProjectionsClient.prototype.disable = function(httpEndPoint, name, userCredentials) {
6825 return this.sendPost(httpEndPoint + '/projection/' + name + '/command/disable', '', userCredentials, HTTP_OK);
6826};
6827
6828ProjectionsClient.prototype.abort = function(httpEndPoint, name, userCredentials) {
6829 return this.sendPost(httpEndPoint + '/projection/' + name + '/command/abort', '', userCredentials, HTTP_OK);
6830};
6831
6832ProjectionsClient.prototype.reset = function(httpEndPoint, name, userCredentials) {
6833 return this.sendPost(httpEndPoint + '/projection/' + name + '/command/reset', '', userCredentials, HTTP_OK);
6834};
6835
6836ProjectionsClient.prototype.createOneTime = function(httpEndPoint, query, userCredentials) {
6837 return this.sendPost(httpEndPoint + '/projections/onetime?type=JS', query, userCredentials, HTTP_CREATED);
6838};
6839
6840ProjectionsClient.prototype.createTransient = function(httpEndPoint, name, query, userCredentials) {
6841 return this.sendPost(httpEndPoint + '/projections/transient?name=' + name + '&type=JS', query, userCredentials, HTTP_CREATED);
6842};
6843
6844ProjectionsClient.prototype.createContinuous = function(httpEndPoint, name, query, trackEmittedStreams, userCredentials) {
6845 return this.sendPost(httpEndPoint + '/projections/continuous?name=' + name + '&type=JS&emit=1&trackemittedstreams=' + trackEmittedStreams, query, userCredentials, HTTP_CREATED);
6846};
6847
6848ProjectionsClient.prototype.listAll = function(httpEndPoint, userCredentials) {
6849 return this.sendGet(httpEndPoint + '/projections/any', userCredentials, HTTP_OK)
6850 .then(function (json) {
6851 var r = safeParseJson(json);
6852 if (r && r.projections) return r.projections;
6853 return null;
6854 });
6855};
6856
6857ProjectionsClient.prototype.listOneTime = function(httpEndPoint, userCredentials) {
6858 return this.sendGet(httpEndPoint + '/projections/onetime', userCredentials, HTTP_OK)
6859 .then(function (json) {
6860 var r = safeParseJson(json);
6861 if (r && r.projections) return r.projections;
6862 return null;
6863 });
6864};
6865
6866ProjectionsClient.prototype.listContinuous = function(httpEndPoint, userCredentials) {
6867 return this.sendGet(httpEndPoint + '/projections/continuous', userCredentials, HTTP_OK)
6868 .then(function (json) {
6869 var r = safeParseJson(json);
6870 if (r && r.projections) return r.projections;
6871 return null;
6872 });
6873};
6874
6875ProjectionsClient.prototype.getStatus = function(httpEndPoint, name, userCredentials) {
6876 return this.sendGet(httpEndPoint + '/projection/' + name, userCredentials, HTTP_OK);
6877};
6878
6879ProjectionsClient.prototype.getState = function(httpEndPoint, name, userCredentials) {
6880 return this.sendGet(httpEndPoint + '/projection/' + name + '/state', userCredentials, HTTP_OK);
6881};
6882
6883ProjectionsClient.prototype.getPartitionState = function(httpEndPoint, name, partitionId, userCredentials) {
6884 return this.sendGet(httpEndPoint + '/projection/' + name + '/state?partition=' + partitionId, userCredentials, HTTP_OK);
6885};
6886
6887ProjectionsClient.prototype.getResult = function(httpEndPoint, name, userCredentials) {
6888 return this.sendGet(httpEndPoint + '/projection/' + name + '/result', userCredentials, HTTP_OK);
6889};
6890
6891ProjectionsClient.prototype.getPartitionResult = function(httpEndPoint, name, partitionId, userCredentials) {
6892 return this.sendGet(httpEndPoint + '/projection/' + name + '/result?partition=' + partitionId, userCredentials, HTTP_OK);
6893};
6894
6895ProjectionsClient.prototype.getStatistics = function(httpEndPoint, name, userCredentials) {
6896 return this.sendGet(httpEndPoint + '/projection/' + name + '/statistics', userCredentials, HTTP_OK);
6897};
6898
6899ProjectionsClient.prototype.getQuery = function(httpEndPoint, name, userCredentials) {
6900 return this.sendGet(httpEndPoint + '/projection/' + name + '/query', userCredentials, HTTP_OK);
6901};
6902
6903ProjectionsClient.prototype.updateQuery = function(httpEndPoint, name, query, userCredentials) {
6904 return this.sendPut(httpEndPoint + '/projection/' + name + '/query?type=JS', query, userCredentials, HTTP_OK);
6905};
6906
6907ProjectionsClient.prototype.delete = function(httpEndPoint, name, deleteEmittedStreams, deleteStateStream, deleteCheckpointStream, userCredentials) {
6908 return this.sendDelete(httpEndPoint + '/projection/' + name + '?deleteStateStream=' + deleteStateStream + '&deleteCheckpointStream=' + deleteCheckpointStream + '&deleteEmittedStreams=' + deleteEmittedStreams, '', userCredentials, HTTP_OK);
6909};
6910
6911ProjectionsClient.prototype.request = function(method, _url, data, userCredentials, expectedCode) {
6912 const options = url.parse(_url);
6913 options.method = method;
6914 if (userCredentials) {
6915 options.auth = [userCredentials.username, userCredentials.password].join(':');
6916 }
6917 var self = this;
6918 return new Promise(function (resolve, reject) {
6919 const timeout = setTimeout(function () {
6920 reject(new Error(util.format('Request timed out for %s on %s', method, _url)))
6921 }, self._operationTimeout);
6922 const req = http.request(options, function (res) {
6923 const hasExpectedCode = res.statusCode === expectedCode;
6924 var result = '';
6925 res.setEncoding('utf8');
6926 res.on('data', function (chunk) {
6927 result += chunk;
6928 });
6929 res.on('end', function () {
6930 if (hasExpectedCode) {
6931 clearTimeout(timeout);
6932 resolve(result);
6933 } else {
6934 clearTimeout(timeout);
6935 reject(new ProjectionCommandFailedError(
6936 res.statusCode,
6937 util.format('Server returned %d (%s) for %s on %s', res.statusCode, res.statusMessage, method, _url)
6938 ));
6939 }
6940 });
6941 });
6942 req.on('error', reject);
6943 if (data) {
6944 req.setHeader('Content-Length', data.length);
6945 req.setHeader('Content-Type', 'application/json');
6946 req.write(data);
6947 }
6948 req.end();
6949 });
6950};
6951
6952function voidResult() {}
6953
6954ProjectionsClient.prototype.sendGet = function(_url, userCredentials, expectedCode) {
6955 return this.request('GET', _url, null, userCredentials, expectedCode);
6956};
6957
6958ProjectionsClient.prototype.sendPost = function(_url, data, userCredentials, expectedCode) {
6959 return this.request('POST', _url, data, userCredentials, expectedCode)
6960 .then(voidResult);
6961};
6962
6963ProjectionsClient.prototype.sendPut = function(_url, data, userCredentials, expectedCode) {
6964 return this.request('PUT', _url, data, userCredentials, expectedCode)
6965 .then(voidResult);
6966};
6967
6968ProjectionsClient.prototype.sendDelete = function(_url, data, userCredentials, expectedCode) {
6969 return this.request('DELETE', _url, data, userCredentials, expectedCode)
6970 .then(voidResult);
6971};
6972
6973module.exports = ProjectionsClient;
6974
6975
6976/***/ }),
6977/* 77 */
6978/***/ (function(module, exports) {
6979
6980module.exports = require("url");
6981
6982/***/ }),
6983/* 78 */
6984/***/ (function(module, exports) {
6985
6986const SystemMetadata = Object.freeze({
6987 maxAge: '$maxAge',
6988 maxCount: '$maxCount',
6989 truncateBefore: '$tb',
6990 cacheControl: '$cacheControl',
6991 acl: '$acl',
6992 aclRead: '$r',
6993 aclWrite: '$w',
6994 aclDelete: '$d',
6995 aclMetaRead: '$mr',
6996 aclMetaWrite: '$mw',
6997 userStreamAcl: '$userStreamAcl',
6998 systemStreamAcl: '$systemStreamAcl'
6999});
7000
7001module.exports = SystemMetadata;
7002
7003/***/ }),
7004/* 79 */
7005/***/ (function(module, exports, __webpack_require__) {
7006
7007var util = __webpack_require__(0);
7008var fs = __webpack_require__(80);
7009var os = __webpack_require__(81);
7010
7011function FileLogger(filePath, append) {
7012 this._filePath = filePath;
7013 if (!append) {
7014 try {
7015 fs.unlinkSync(filePath);
7016 } catch(e) {}
7017 }
7018}
7019
7020function createLine(level, args, argsStartIndex) {
7021 var msg = util.format.apply(util, Array.prototype.slice.call(args, argsStartIndex));
7022 return util.format('%s %s - %s%s', new Date().toISOString().substr(11,12), level, msg, os.EOL);
7023}
7024
7025FileLogger.prototype.debug = function() {
7026 var line = createLine('DEBUG', arguments, 0);
7027 fs.appendFileSync(this._filePath, line);
7028};
7029
7030FileLogger.prototype.info = function() {
7031 var line = createLine('INFO', arguments, 0);
7032 fs.appendFileSync(this._filePath, line);
7033};
7034
7035FileLogger.prototype.error = function(e) {
7036 var hasError = e instanceof Error;
7037 var line = createLine('ERROR', arguments, hasError ? 1 : 0);
7038 if (hasError) {
7039 line += e.stack + os.EOL;
7040 }
7041 fs.appendFileSync(this._filePath, line);
7042};
7043
7044
7045module.exports = FileLogger;
7046
7047/***/ }),
7048/* 80 */
7049/***/ (function(module, exports) {
7050
7051module.exports = require("fs");
7052
7053/***/ }),
7054/* 81 */
7055/***/ (function(module, exports) {
7056
7057module.exports = require("os");
7058
7059/***/ })
7060/******/ ]);
\No newline at end of file