Compare commits

...

79 Commits

Author SHA1 Message Date
Nicolas Dextraze c67d0d25a2
Merge pull request #102 from PrestaShopCorp/fixShuffle 2 years ago
maniolias 5bc2aaa093 refactor: delete unused code 2 years ago
maniolias 401f6c3190 fix(shuffle): fix shuffle methode for array with length <= 1 2 years ago
Nicolas Dextraze 40736d9da3 relese version to 0.2.17 2 years ago
Nicolas Dextraze 853ae875b8
Merge pull request #101 from PrestaShopCorp/feature/cluster 2 years ago
maniolias da6d059547 feat(cluster): create way to test single/gossip/cluster 2 years ago
maniolias e9834daa31 feat(tcp): add timeout when trying to connect to a TCP endpoint 2 years ago
maniolias f79a0444f6 feat(cluster): rewrite cluster discovering 2 years ago
Nicolas Dextraze eb56e077f9
Merge pull request #95 from aliabbasjaffri/HA-Cluster-Connectivity-Issue 2 years ago
Ali Abbas Jaffri 11f882501f 🐛 Adding object reference to externalTcpIp: Solves locating cluster via gossip seeds 2 years ago
Nicolas Dextraze 195a6d40ce Attempt at fixing Typescript dependencies issues 3 years ago
Nicolas Dextraze 55b9ddd856 Minor improvement to protobuf isolation 3 years ago
Nicolas Dextraze fe82aebfec Fix #91 3 years ago
Nicolas Dextraze 3f7798d46e Update package-lock.json and yarn.lock 3 years ago
Nicolas Dextraze 6ad2d34114 Added some more tests around RecordedEvent properties type 3 years ago
Nicolas Dextraze 67dab18d53 Fixed Buffer deprecated warnings when using node >= v10 3 years ago
Nicolas Dextraze 78677ba53e Add missing created to RecordedEvent typescript definition 3 years ago
Nicolas Dextraze bbf25ee8b5 Update dev dependencies 3 years ago
Nicolas Dextraze 732b691e40 Move typescript dependencies back to dev 3 years ago
Nicolas Dextraze 941f671ed2 Fix missing warn in Loggers 3 years ago
Nicolas Dextraze 343eaa85df
Merge pull request #86 from MajorBreakfast/patch-1 3 years ago
Josef Brandl e0fcf9a72d
Make type definition of expectedVersion match implementation 3 years ago
Nicolas Dextraze 02642c5cfb Fix appendToStream with expectedVersion any and same event not working due to protobufjs bug 3 years ago
Nicolas Dextraze d64f181dbb release version 0.2.12 3 years ago
Nicolas Dextraze 9e31b17c44
Merge pull request #80 from jdextraze/jdextraze/simple-queued-handler-log-issue 3 years ago
Jonathan Dextraze 4ae4c1e010 Fix error with logging in SimpleQueuedHandler handler 3 years ago
Nicolas Dextraze 76a405ace2 Publish version 0.2.11 3 years ago
Nicolas Dextraze 930b900426
Merge pull request #78 from Poimen/fix-issue-76 3 years ago
Nicolas Dextraze 934251d7fa
Merge pull request #77 from Poimen/fix-issue-75 3 years ago
Richard Shephard 1449b43b8d Fix missing = in delete uri 3 years ago
Richard Shephard 2f4850680f Fix incorrect variables used after undefined removal 3 years ago
Richard Shephard 8f68923008 Remove undefine's check as the options will need to be provided anyways... 3 years ago
Richard Shephard 8e54a22cd2 Fix uri for reset 3 years ago
Richard Shephard 6663b42903 Fix sendDelete call to provide empty data so header is correct 3 years ago
Richard Shephard ad8d16d112 Fix documentation 3 years ago
Richard Shephard bebd04a398 Fix client endpoint used 3 years ago
Richard Shephard 4d981596eb Fix typings for delete (there is no deleteQuery) in projection manager 3 years ago
Richard Shephard 7ccced45aa Add reset endpoint 3 years ago
Richard Shephard 88df807508 Update documentation for strict-event-emitter-types dependency 3 years ago
Richard Shephard 35f720f94f Added extra parameters to delete projections 3 years ago
Nicolas Dextraze 6d49f51e7d fix issue #74 - projections manager create continuous trackEmittedStreams parameter should be lowercase 3 years ago
Nicolas Dextraze d8baed4c5d fix issue #73 - move types dependencies from dev dependencies so they install for dependant 3 years ago
Nicolas Dextraze 7e5327c278 Published version 0.2.10 and moved types dependencies to devDependencies 3 years ago
Nicolas Dextraze bb53c01fe8
Merge pull request #69 from sebastianneb/68-debug 3 years ago
Neb, Sebastian 20818869f1 Fix for issue #68 by using self._log_debug instead of this._log.debug 3 years ago
Nicolas Dextraze 16f172c6f2
Merge pull request #66 from Ulrikop/ts-declarations 3 years ago
Nicolas Dextraze 7db060af6e Removed some console 3 years ago
Nicolas Dextraze 2c272a19f5
Merge pull request #67 from JurJean/remove-subscription-started-log 3 years ago
Jur Jean 7dc4658719 Merge branch 'master' of github.com:nicdex/node-eventstore-client into remove-subscription-started-log 3 years ago
Jur Jean 811368c1af Removed the console log about subscription started 3 years ago
Ulrikop fcf27fba20 Changes ts declaration for EventStoreNodeConnection so that it offers all EventEmitter methods. 3 years ago
Nicolas Dextraze e9d86a3c4d Fix issue #63 - export PersistentSubscriptionNakEventAction 4 years ago
Nicolas Dextraze 0db2b93b79
Merge pull request #62 from JurJean/invalid-missing-content-type 4 years ago
Jur Jean ef26ed636f Send Content-Length to eliminate missing Content-Type error in some cases 4 years ago
Nicolas Dextraze 2893454e8a Updated messages.proto to have optional event for ResolvedEvent and ResolvedIndexedEvent and regenarated protobuf code 4 years ago
Nicolas Dextraze a0642ab081 Re-add optional (allowing null) on ResolvedEvent event property in protobuf 4 years ago
Nicolas Dextraze 760d31cc31 Published 0.2.5 to npm 4 years ago
Nicolas Dextraze c1f17a7d99 #61 fixed subscriptionDropped being called only once 4 years ago
Nicolas Dextraze 96145fbe49 Published 0.2.4, adding package-lock.json 4 years ago
Nicolas Dextraze 5ac4a206ad
Merge pull request #59 from sledorze/master 4 years ago
Stéphane Le Dorze e1f99cecbc
Fix definitions of PersistenSubscriptions 4 years ago
Nicolas Dextraze 0a64b37b6f Fix issue with fake-server 4 years ago
Nicolas Dextraze 3421d41068 Adding a fake server for testing purpose 4 years ago
Nicolas Dextraze 215708014c Add Object.freeze on private enums 4 years ago
Nicolas Dextraze c3a63ff8b7
Merge pull request #58 from cdimitroulas/improve-docs 4 years ago
Christos Dimitroulas d8c0bfb03a improve docs for createConnection 4 years ago
Nicolas Dextraze 34e8262dc8 Make Ssl tests opt-in 4 years ago
Nicolas Dextraze bc2fbe14e3 Adding SSL support, release 0.2.3 4 years ago
Nicolas Dextraze 9fc5d64ceb Adding start/end as static Position 4 years ago
Nicolas Dextraze 2bdd74e041
Merge pull request #53 from paullucas/master 4 years ago
Paul fde6ad2e77 Use jsdoc version 3.5.5 4 years ago
Nicolas Dextraze 4a2065c0a7 Release npm package version to 0.2.1 5 years ago
Nicolas Dextraze 67dd275b5d Fix potential error handling bug due to missing EventEmitter.call(this) in EventStoreNodeConnection and EventStoreConnectionLogicHandler 5 years ago
Nicolas Dextraze 8997a8c398 Update README 5 years ago
Nicolas Dextraze a5807483a2 Merge branch 'v4_proto' 5 years ago
Nicolas Dextraze e79ad8f9c4 Use Long in Stream catchup subscription 5 years ago
Nicolas Dextraze 4584517ede Update tests, typescript declaration 5 years ago
Nicolas Dextraze e6af223f0d Fix identify client serialize 5 years ago
Nicolas Dextraze 990351738c Update proto 5 years ago
  1. 11
      .idea/codeStyles/Project.xml
  2. 5
      .idea/codeStyles/codeStyleConfig.xml
  3. 2
      .idea/misc.xml
  4. 68
      README.md
  5. 147
      docker-compose-cluster.yaml
  6. 54
      docker-compose-single.yaml
  7. 207
      index.d.ts
  8. 10576
      package-lock.json
  9. 40
      package.json
  10. 62
      samples/issue-60.js
  11. 50
      samples/subscribe-all-from-events.js
  12. 59
      src/client.js
  13. 5
      src/clientOperations/appendToStreamOperation.js
  14. 1
      src/clientOperations/commitTransactionOperation.js
  15. 2
      src/clientOperations/connectToPersistentSubscriptionOperation.js
  16. 3
      src/clientOperations/createPersistentSubscriptionOperation.js
  17. 4
      src/clientOperations/deletePersistentSubscriptionOperation.js
  18. 1
      src/clientOperations/deleteStreamOperation.js
  19. 10
      src/clientOperations/operationBase.js
  20. 3
      src/clientOperations/readAllEventsBackwardOperation.js
  21. 3
      src/clientOperations/readAllEventsForwardOperation.js
  22. 3
      src/clientOperations/readEventOperation.js
  23. 3
      src/clientOperations/readStreamEventsBackwardOperation.js
  24. 3
      src/clientOperations/readStreamEventsForwardOperation.js
  25. 4
      src/clientOperations/startTransactionOperation.js
  26. 50
      src/clientOperations/subscriptionOperation.js
  27. 3
      src/clientOperations/transactionalWriteOperation.js
  28. 3
      src/clientOperations/updatePersistentSubscriptionOperation.js
  29. 4
      src/clientOperations/volatileSubscriptionOperation.js
  30. 3
      src/common/bufferSegment.js
  31. 6
      src/common/guid-parse.js
  32. 2
      src/common/hash.js
  33. 7
      src/common/log/fileLogger.js
  34. 5
      src/common/log/noopLogger.js
  35. 6
      src/common/systemEventTypes.js
  36. 5
      src/common/systemMetadata.js
  37. 4
      src/common/systemStreams.js
  38. 42
      src/common/utils/ensure.js
  39. 28
      src/common/utils/shuffle.js
  40. 163
      src/core/cluster/clusterDiscoverer.js
  41. 36
      src/core/cluster/clusterInfo.js
  42. 73
      src/core/cluster/memberInfo.js
  43. 23
      src/core/cluster/nodeEndpoints.js
  44. 254
      src/core/clusterDnsEndPointDiscoverer.js
  45. 94
      src/core/eventStoreConnectionLogicHandler.js
  46. 1
      src/core/messages.js
  47. 8
      src/core/operationsManager.js
  48. 17
      src/core/simpleQueuedHandler.js
  49. 2
      src/errors/projectionCommandFailedError.js
  50. 6
      src/eventData.js
  51. 10
      src/eventStoreAllCatchUpSubscription.js
  52. 41
      src/eventStoreCatchUpSubscription.js
  53. 68
      src/eventStoreConnection.js
  54. 80
      src/eventStoreNodeConnection.js
  55. 22
      src/eventStorePersistentSubscriptionBase.js
  56. 32
      src/eventStoreStreamCatchUpSubscription.js
  57. 2
      src/eventStoreSubscription.js
  58. 7
      src/gossipSeed.js
  59. 22151
      src/messages/messages.js
  60. 45
      src/messages/messages.proto
  61. 2
      src/persistentEventStoreSubscription.js
  62. 19
      src/persistentSubscriptionNakEventAction.js
  63. 5
      src/persistentSubscriptionSettings.js
  64. 13
      src/projections/projectionsClient.js
  65. 22
      src/projections/projectionsManager.js
  66. 6
      src/readDirection.js
  67. 89
      src/results.js
  68. 7
      src/sliceReadStatus.js
  69. 4
      src/subscriptionDropReason.js
  70. 7
      src/systemConsumerStrategies.js
  71. 4
      src/systemData/inspectionDecision.js
  72. 2
      src/systemData/inspectionResult.js
  73. 4
      src/systemData/statusCode.js
  74. 18
      src/systemData/tcpCommand.js
  75. 4
      src/systemData/tcpFlags.js
  76. 29
      src/systemData/tcpPackage.js
  77. 10
      src/transport/tcp/lengthPrefixMessageFramer.js
  78. 68
      src/transport/tcp/tcpConnection.js
  79. 30
      src/transport/tcp/tcpPackageConnection.js
  80. 17
      src/utils/modules.js
  81. 2
      src/volatileEventStoreSubscription.js
  82. 34
      test/appendToStream_test.js
  83. 2
      test/cluster/dns_test.js
  84. 2
      test/cluster/gossipSeeds_test.js
  85. 215
      test/common/base_test.js
  86. 213
      test/connection_test.js
  87. 15
      test/deleteStream_test.js
  88. 98
      test/fixtures/gossip.json
  89. 9
      test/metadata_test.js
  90. 24
      test/persistentSubscription_test.js
  91. 6
      test/projections_test.js
  92. 4
      test/readAllEventsBackward_test.js
  93. 4
      test/readAllEventsForward_test.js
  94. 36
      test/readEvent_test.js
  95. 38
      test/readStreamEventsBackward_test.js
  96. 38
      test/readStreamEventsForward_test.js
  97. 60
      test/subscribeToAllFrom_test.js
  98. 29
      test/subscribeToAll_test.js
  99. 75
      test/subscribeToStreamFrom_test.js
  100. 32
      test/subscribeToStream_test.js
  101. Some files were not shown because too many files have changed in this diff Show More

11
.idea/codeStyles/Project.xml

@ -0,0 +1,11 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<codeStyleSettings language="JavaScript">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

5
.idea/codeStyles/codeStyleConfig.xml

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

2
.idea/misc.xml

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES5" />
<option name="languageLevel" value="ES6" />
</component>
</project>

68
README.md

@ -1,11 +1,14 @@
# node-eventstore-client
A port of the EventStore .Net ClientAPI to Node.js
## Learning
If you want to learn more about EventSourcing/CQRS/EventModeling, you can join the virtual workshop offered by my employer Adaptech Group, see info at [https://www.adaptechgroup.com/virtual-workshop/](https://www.adaptechgroup.com/virtual-workshop/).
## Status
### Missing features:
- Ssl connection
- Set system settings
### Areas to improve
@ -24,7 +27,14 @@ Install using `npm install node-eventstore-client`
### Dependencies
- Node.js >= 4.0
- Modules: [long](https://www.npmjs.org/package/long), [protobufjs](https://www.npmjs.org/package/protobufjs), [uuid](https://www.npmjs.org/package/uuid) (installed via `npm install`)
- Modules: [long](https://www.npmjs.org/package/long), [protobufjs](https://www.npmjs.org/package/protobufjs), [uuid](https://www.npmjs.org/package/uuid), [strict-event-emitter-types](https://www.npmjs.com/package/strict-event-emitter-types) (installed via `npm install`)
### Install and run an Eventstore on localhost
See https://eventstore.org/docs/introduction/4.1.0/
*Note: If you are using a version of EventStore prior to 3.9.4, you need to use version 0.1.x of this package `npm install node-eventstore-client@^0.1`.*
### API Documentation
@ -35,11 +45,7 @@ The offline documentation can be found in the module folder `./node_modules/node
#### Online
The online documentation can be found at [https://dev.nicdex.com/node-eventstore-client/docs/](https://dev.nicdex.com/node-eventstore-client/docs/)
### Install & run an Eventstore on localhost
See http://docs.geteventstore.com/introduction/3.9.0/ .
### Example: Storing an event
Save to ```app.js:```
@ -110,14 +116,60 @@ To generate a test event, open a separate console and run:
## Running the tests
### Local testing
To run the tests it is recommended that you use an in-memory instance of the eventstore so you don't pollute your dev instance.
EventStore.ClusterNode.exe --run-projections=all --memdb
EventStore.ClusterNode.exe --run-projections=all --memdb –certificate-file=yourcert.pfx
or
./run-node.sh --run-projections=all --memdb –certificate-file=yourcert.p12
You can also use docker-compose :
```bash
# start the single node cluster
npm run compose:single:start
# if you want to wait for the cluster to be available
npm run compose:wait
# run the tests
npm run test
# to cleanup (stop containres, delete volumes)
npm run compose:single:stop
```
For SSL setup see:
https://eventstore.org/docs/server/setting_up_ssl/
or
https://eventstore.org/docs/server/setting_up_ssl_linux/
To execute the tests suites simply run
npm test
### Isolated environment
To be able to run the tests for different connection types (tcp, gossip, cluster) docker-compose files are available to setup the environment and run the tests.
#### Prerequisites
* docker
* docker-compose
#### Run
To execute the tests suites for single node cluster (tcp connection) simply run
npm run test:single
To execute the tests suites for multiple nodes cluster (gossip connection) simply run
npm run test:gossip
To execute the tests suites for multiple nodes cluster (dns discovery connection) simply run
npm run test:cluster
## Porting .Net Task to Node.js
Any async commands returns a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) object in replacement of .Net Task.

147
docker-compose-cluster.yaml

@ -0,0 +1,147 @@
version: '3.4'
services:
eventstore.db:
image: eventstore/eventstore:release-5.0.8
environment:
- EVENTSTORE_WORKER_THREADS=5
- EVENTSTORE_CLUSTER_SIZE=3
- EVENTSTORE_RUN_PROJECTIONS=All
- EVENTSTORE_DB=/var/lib/eventstore-data
- EVENTSTORE_INDEX=/var/lib/eventstore-index
- EVENTSTORE_LOG=/var/log/eventstore
- EVENTSTORE_CLUSTER_GOSSIP_PORT=2112
- EVENTSTORE_INT_TCP_PORT=1112
- EVENTSTORE_EXT_TCP_PORT=1113
- EVENTSTORE_INT_HTTP_PORT=2112
- EVENTSTORE_EXT_HTTP_PORT=2113
- EVENTSTORE_DISCOVER_VIA_DNS=true
- EVENTSTORE_CLUSTER_DNS=eventstore.local
- EVENTSTORE_INT_IP=192.168.33.10
- EVENTSTORE_EXT_IP=192.168.33.10
ports:
- "1112:1112"
- "1113:1113"
- "2112:2112"
- "2113:2113"
networks:
app_net:
aliases:
- eventstore.local
ipv4_address: 192.168.33.10
volumes:
- type: volume
source: eventstore-volume-data
target: /var/lib/eventstore-data
- type: volume
source: eventstore-volume-index
target: /var/lib/eventstore-index
- type: volume
source: eventstore-volume-logs
target: /var/log/eventstore
eventstore.db2:
image: eventstore/eventstore:release-5.0.8
environment:
- EVENTSTORE_WORKER_THREADS=5
- EVENTSTORE_CLUSTER_SIZE=3
- EVENTSTORE_RUN_PROJECTIONS=All
- EVENTSTORE_DB=/var/lib/eventstore-data
- EVENTSTORE_INDEX=/var/lib/eventstore-index
- EVENTSTORE_LOG=/var/log/eventstore
- EVENTSTORE_CLUSTER_GOSSIP_PORT=2112
- EVENTSTORE_INT_TCP_PORT=1112
- EVENTSTORE_EXT_TCP_PORT=1113
- EVENTSTORE_INT_HTTP_PORT=2112
- EVENTSTORE_EXT_HTTP_PORT=2113
- EVENTSTORE_DISCOVER_VIA_DNS=true
- EVENTSTORE_CLUSTER_DNS=eventstore.local
- EVENTSTORE_INT_IP=192.168.33.11
- EVENTSTORE_EXT_IP=192.168.33.11
expose:
- "1113"
- "1112"
- "2112"
- "2113"
networks:
app_net:
aliases:
- eventstore.local
ipv4_address: 192.168.33.11
volumes:
- type: volume
source: eventstore-volume-data2
target: /var/lib/eventstore-data
- type: volume
source: eventstore-volume-index2
target: /var/lib/eventstore-index
- type: volume
source: eventstore-volume-logs2
target: /var/log/eventstore
eventstore.db3:
image: eventstore/eventstore:release-5.0.8
environment:
- EVENTSTORE_WORKER_THREADS=5
- EVENTSTORE_CLUSTER_SIZE=3
- EVENTSTORE_RUN_PROJECTIONS=All
- EVENTSTORE_DB=/var/lib/eventstore-data
- EVENTSTORE_INDEX=/var/lib/eventstore-index
- EVENTSTORE_LOG=/var/log/eventstore
- EVENTSTORE_CLUSTER_GOSSIP_PORT=2112
- EVENTSTORE_INT_TCP_PORT=1112
- EVENTSTORE_EXT_TCP_PORT=1113
- EVENTSTORE_INT_HTTP_PORT=2112
- EVENTSTORE_EXT_HTTP_PORT=2113
- EVENTSTORE_DISCOVER_VIA_DNS=true
- EVENTSTORE_CLUSTER_DNS=eventstore.local
- EVENTSTORE_INT_IP=192.168.33.12
- EVENTSTORE_EXT_IP=192.168.33.12
expose:
- "1113"
- "1112"
- "2112"
- "2113"
networks:
app_net:
aliases:
- eventstore.local
ipv4_address: 192.168.33.12
volumes:
- type: volume
source: eventstore-volume-data3
target: /var/lib/eventstore-data
- type: volume
source: eventstore-volume-index3
target: /var/lib/eventstore-index
- type: volume
source: eventstore-volume-logs3
target: /var/log/eventstore
nodejs:
image: node:14
working_dir: /var/code
volumes:
- .:/var/code
- /var/code/node_modules
command: bash -c "tail -f /dev/null"
networks:
- app_net
volumes:
eventstore-volume-data:
eventstore-volume-index:
eventstore-volume-logs:
eventstore-volume-data2:
eventstore-volume-index2:
eventstore-volume-logs2:
eventstore-volume-data3:
eventstore-volume-index3:
eventstore-volume-logs3:
networks:
app_net:
ipam:
driver: default
config:
- subnet: "192.168.33.0/24"

54
docker-compose-single.yaml

@ -0,0 +1,54 @@
version: '3.4'
services:
eventstore.db:
image: eventstore/eventstore:release-5.0.8
environment:
- EVENTSTORE_CLUSTER_SIZE=1
- EVENTSTORE_RUN_PROJECTIONS=All
- EVENTSTORE_START_STANDARD_PROJECTIONS=True
- EVENTSTORE_DB=/var/lib/eventstore-data
- EVENTSTORE_INDEX=/var/lib/eventstore-index
- EVENTSTORE_LOG=/var/log/eventstore
- EVENTSTORE_EXT_TCP_PORT=1113
- EVENTSTORE_EXT_HTTP_PORT=2113
- EVENTSTORE_INT_IP=192.168.33.10
- EVENTSTORE_EXT_IP=192.168.33.10
ports:
- "1113:1113"
- "2113:2113"
volumes:
- type: volume
source: eventstore-volume-data
target: /var/lib/eventstore-data
- type: volume
source: eventstore-volume-index
target: /var/lib/eventstore-index
- type: volume
source: eventstore-volume-logs
target: /var/log/eventstore
networks:
app_net:
ipv4_address: 192.168.33.10
nodejs:
image: node:14
working_dir: /var/code
volumes:
- .:/var/code
- /var/code/node_modules
command: bash -c "tail -f /dev/null"
networks:
- app_net
volumes:
eventstore-volume-data:
eventstore-volume-index:
eventstore-volume-logs:
networks:
app_net:
ipam:
driver: default
config:
- subnet: "192.168.33.0/24"

207
index.d.ts vendored

@ -1,14 +1,18 @@
/// <reference types="node" />
/// <reference types="Long" />
import { EventEmitter } from 'events';
import { StrictEventEmitter } from 'strict-event-emitter-types';
// Expose classes
export class Position {
constructor(commitPosition: number|Long, preparePosition: number|Long);
readonly commitPosition: Long;
readonly preparePosition: Long;
static readonly start: number;
static readonly end: number;
}
// Expose classes
export class UserCredentials {
constructor(username: string, password: string);
readonly username: string;
@ -16,7 +20,7 @@ export class UserCredentials {
}
export class PersistentSubscriptionSettings {
constructor(resolveLinkTos: boolean, startFrom: number, extraStatistics: boolean, messageTimeout: number,
constructor(resolveLinkTos: boolean, startFrom: Long|number, extraStatistics: boolean, messageTimeout: number,
maxRetryCount: number, liveBufferSize: number, readBatchSize: number, historyBufferSize: number,
checkPointAfter: number, minCheckPointCount: number, maxCheckPointCount: number,
maxSubscriberCount: number, namedConsumerStrategy: string)
@ -35,13 +39,65 @@ export class GossipSeed {
readonly hostHeader: string;
}
export interface ProjectionDetails {
readonly coreProcessingTime: number,
readonly version: number,
readonly epoch: number,
readonly effectiveName: string,
readonly writesInProgress: number,
readonly readsInProgress: number,
readonly partitionsCached: number,
readonly status: string,
readonly stateReason: string,
readonly name: string,
readonly mode: string,
readonly position: string,
readonly progress: number,
readonly lastCheckpoint: string,
readonly eventsProcessedAfterRestart: number,
readonly statusUrl: string,
readonly stateUrl: string,
readonly resultUrl: string,
readonly queryUrl: string,
readonly enableCommandUrl: string,
readonly disableCommandUrl: string,
readonly checkpointStatus: string,
readonly bufferedEvents: number,
readonly writePendingEventsBeforeCheckpoint: number,
readonly writePendingEventsAfterCheckpoint: number
}
export class ProjectionsManager {
constructor(log: Logger, httpEndPoint: string, operationTimeout: number);
enable(name: string, userCredentials: UserCredentials): Promise<void>;
disable(name: string, userCredentials: UserCredentials): Promise<void>;
abort(name: string, userCredentials: UserCredentials): Promise<void>;
reset(name: string, userCredentials: UserCredentials): Promise<void>;
createOneTime(query: string, userCredentials: UserCredentials): Promise<void>;
createTransient(name: string, query: string, userCredentials: UserCredentials): Promise<void>;
createContinuous(name: string, query: string, trackEmittedStreams: boolean, userCredentials: UserCredentials): Promise<void>;
listAll(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
listOneTime(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
listContinuous(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
getStatus(name: string, userCredentials: UserCredentials): Promise<string>;
getState(name: string, userCredentials: UserCredentials): Promise<string>;
getPartitionState(name: string, partitionId: string, userCredentials: UserCredentials): Promise<string>;
getResult(name: string, userCredentials: UserCredentials): Promise<string>;
getPartitionResult(name: string, partitionId: string, userCredentials: UserCredentials): Promise<string>;
getStatistics(name: string, userCredentials: UserCredentials): Promise<string>;
getQuery(name: string, userCredentials: UserCredentials): Promise<string>;
getState(name: string, userCredentials: UserCredentials): Promise<string>;
updateQuery(name: string, query: string, userCredentials: UserCredentials): Promise<void>;
delete(name: string, deleteEmittedStreams: boolean, deleteStateStream: boolean, deleteCheckpointStream: boolean, userCredentials: UserCredentials): Promise<void>;
}
// Expose errors
export class WrongExpectedVersionError {
readonly name: string;
readonly action: string;
readonly message: string;
readonly stream?: string;
readonly expectedVersion?: number;
readonly expectedVersion?: Long;
readonly transactionId?: Long;
}
@ -59,12 +115,17 @@ export class AccessDeniedError {
readonly transactionId?: Long;
}
// Expose enums/constants
export class ProjectionCommandFailedError {
readonly httpStatusCode: number;
readonly message: string;
}
// Expose enums/constants
export namespace expectedVersion {
const any: number;
const noStream: number;
const emptyStream: number;
const streamExists: number;
}
export namespace positions {
@ -72,12 +133,17 @@ export namespace positions {
const end: Position;
}
export namespace streamPosition {
const start: number;
const end: number;
}
//TODO
// systemMetadata
// eventReadStatus
// sliceReadStatus
// Expose loggers
export interface Logger {
debug(fmt: string, ...args: any[]): void;
info(fmt: string, ...args: any[]): void;
@ -98,18 +164,18 @@ export class FileLogger implements Logger {
error(fmt: string, ...args: any[]): void;
}
//
// Expose results
export interface WriteResult {
readonly nextExpectedVersion: number;
readonly nextExpectedVersion: Long;
readonly logPosition: Position;
}
export interface RecordedEvent {
readonly eventStreamId: string;
readonly eventId: string;
readonly eventNumber: number;
readonly eventNumber: Long;
readonly eventType: string;
readonly created: Date;
readonly createdEpoch: number;
readonly data?: Buffer;
readonly metadata?: Buffer;
@ -123,17 +189,17 @@ export interface ResolvedEvent {
readonly isResolved: boolean;
readonly originalPosition?: Position;
readonly originalStreamId: string;
readonly originalEventNumber: number;
readonly originalEventNumber: Long;
}
export interface StreamEventsSlice {
readonly status: string; // TODO: enum
readonly stream: string;
readonly fromEventNumber: number;
readonly fromEventNumber: Long;
readonly readDirection: string; // TODO: enum
readonly events: ResolvedEvent[];
readonly nextEventNumber: number;
readonly lastEventNumber: number;
readonly nextEventNumber: Long;
readonly lastEventNumber: Long;
readonly isEndOfStream: boolean;
}
@ -159,7 +225,7 @@ export interface EventStoreTransaction {
export interface EventReadResult {
readonly status: string;
readonly stream: string;
readonly eventNumber: number;
readonly eventNumber: Long;
readonly event: ResolvedEvent | null;
}
@ -167,7 +233,7 @@ export interface EventStoreSubscription {
readonly isSubscribedToAll: boolean;
readonly streamId: string;
readonly lastCommitPosition: Position;
readonly lastEventNumber: number;
readonly lastEventNumber: Long;
close(): void;
unsubscribe(): void;
@ -194,7 +260,7 @@ export interface EventStorePersistentSubscription {
export interface RawStreamMetadataResult {
readonly stream: string;
readonly isStreamDeleted: boolean;
readonly metastreamVersion: number;
readonly metastreamVersion: Long;
readonly streamMetadata: any;
}
@ -229,12 +295,12 @@ export interface TcpEndPoint {
}
export interface HeartbeatInfo {
connectionId: string;
remoteEndPoint: TcpEndPoint;
requestSentAt: number;
requestPkgNumber: number;
responseReceivedAt: number;
responsePkgNumber: number;
readonly connectionId: string;
readonly remoteEndPoint: TcpEndPoint;
readonly requestSentAt: number;
readonly requestPkgNumber: number;
readonly responseReceivedAt: number;
readonly responsePkgNumber: number;
}
export interface EventData {
@ -245,40 +311,47 @@ export interface EventData {
readonly metadata: Buffer;
}
export interface EventStoreNodeConnection {
interface EventStoreNodeConnectionEvents {
connected: TcpEndPoint;
disconnected: TcpEndPoint;
reconnecting: void;
closed:string;
error: Error;
heartbeatInfo: HeartbeatInfo;
}
type EventStoreNodeConnectionEventEmitter = StrictEventEmitter<EventEmitter, EventStoreNodeConnectionEvents>;
export class EventStoreNodeConnection extends (EventEmitter as { new(): EventStoreNodeConnectionEventEmitter }) {
connect(): Promise<void>;
close(): void;
// write actions
deleteStream(stream: string, expectedVersion: number, hardDelete?: boolean, userCredentials?: UserCredentials): Promise<DeleteResult>;
appendToStream(stream: string, expectedVersion: number, eventOrEvents: EventData | EventData[], userCredentials?: UserCredentials): Promise<WriteResult>;
startTransaction(stream: string, expectedVersion: number, userCredentials?: UserCredentials): Promise<EventStoreTransaction>;
deleteStream(stream: string, expectedVersion: Long|number, hardDelete?: boolean, userCredentials?: UserCredentials): Promise<DeleteResult>;
appendToStream(stream: string, expectedVersion: Long|number, eventOrEvents: EventData | EventData[], userCredentials?: UserCredentials): Promise<WriteResult>;
startTransaction(stream: string, expectedVersion: Long|number, userCredentials?: UserCredentials): Promise<EventStoreTransaction>;
continueTransaction(transactionId: number, userCredentials?: UserCredentials): EventStoreTransaction;
// read actions
readEvent(stream: string, eventNumber: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<EventReadResult>;
readStreamEventsForward(stream: string, start: number, count: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<StreamEventsSlice>;
readStreamEventsBackward(stream: string, start: number, count: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<StreamEventsSlice>;
readEvent(stream: string, eventNumber: Long|number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<EventReadResult>;
readStreamEventsForward(stream: string, start: Long|number, count: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<StreamEventsSlice>;
readStreamEventsBackward(stream: string, start: Long|number, count: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<StreamEventsSlice>;
readAllEventsForward(position: Position, maxCount: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<AllEventsSlice>;
readAllEventsBackward(position: Position, maxCount: number, resolveLinkTos?: boolean, userCredentials?: UserCredentials): Promise<AllEventsSlice>;
// subscription actions
subscribeToStream(stream: string, resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreSubscription>, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreSubscription>, userCredentials?: UserCredentials): Promise<EventStoreSubscription>;
subscribeToStreamFrom(stream: string, lastCheckpoint: number | null, resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreCatchUpSubscription>, liveProcessingStarted?: LiveProcessingStartedCallback, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreCatchUpSubscription>, userCredentials?: UserCredentials, readBatchSize?: number): EventStoreCatchUpSubscription;
subscribeToStreamFrom(stream: string, lastCheckpoint: Long|number|null, resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreCatchUpSubscription>, liveProcessingStarted?: LiveProcessingStartedCallback, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreCatchUpSubscription>, userCredentials?: UserCredentials, readBatchSize?: number): EventStoreCatchUpSubscription;
subscribeToAll(resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreSubscription>, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreSubscription>, userCredentials?: UserCredentials): Promise<EventStoreSubscription>;
subscribeToAllFrom(lastCheckpoint: Position | null, resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreCatchUpSubscription>, liveProcessingStarted?: LiveProcessingStartedCallback, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreCatchUpSubscription>, userCredentials?: UserCredentials, readBatchSize?: number): EventStoreCatchUpSubscription;
subscribeToAllFrom(lastCheckpoint: Position|null, resolveLinkTos: boolean, eventAppeared: EventAppearedCallback<EventStoreCatchUpSubscription>, liveProcessingStarted?: LiveProcessingStartedCallback, subscriptionDropped?: SubscriptionDroppedCallback<EventStoreCatchUpSubscription>, userCredentials?: UserCredentials, readBatchSize?: number): EventStoreCatchUpSubscription;
// persistent subscriptions
createPersistentSubscription(stream: string, groupName: string, settings: PersistentSubscriptionSettings, userCredentials?: PersistentSubscriptionSettings): Promise<PersistentSubscriptionCreateResult>;
updatePersistentSubscription(stream: string, groupName: string, settings: PersistentSubscriptionSettings, userCredentials?: PersistentSubscriptionSettings): Promise<PersistentSubscriptionUpdateResult>;
deletePersistentSubscription(stream: string, groupName: string, userCredentials?: PersistentSubscriptionSettings): Promise<PersistentSubscriptionDeleteResult>
createPersistentSubscription(stream: string, groupName: string, settings: PersistentSubscriptionSettings, userCredentials?: UserCredentials): Promise<PersistentSubscriptionCreateResult>;
updatePersistentSubscription(stream: string, groupName: string, settings: PersistentSubscriptionSettings, userCredentials?: UserCredentials): Promise<PersistentSubscriptionUpdateResult>;
deletePersistentSubscription(stream: string, groupName: string, userCredentials?: UserCredentials): Promise<PersistentSubscriptionDeleteResult>
connectToPersistentSubscription(stream: string, groupName: string, eventAppeared: EventAppearedCallback<EventStorePersistentSubscription>, subscriptionDropped?: SubscriptionDroppedCallback<EventStorePersistentSubscription>, userCredentials?: UserCredentials, bufferSize?: number, autoAck?: boolean): Promise<EventStorePersistentSubscription>;
// metadata actions
setStreamMetadataRaw(stream: string, expectedMetastreamVersion: number, metadata: any, userCredentials?: UserCredentials): Promise<WriteResult>;
setStreamMetadataRaw(stream: string, expectedMetastreamVersion: Long|number, metadata: any, userCredentials?: UserCredentials): Promise<WriteResult>;
getStreamMetadataRaw(stream: string, userCredentials?: UserCredentials): Promise<RawStreamMetadataResult>;
on(event: "connected" | "disconnected" | "reconnecting" | "closed" | "error" | "heartbeatInfo", listener: (arg: Error | string | TcpEndPoint | HeartbeatInfo) => void): this;
once(event: "connected" | "disconnected" | "reconnecting" | "closed" | "error" | "heartbeatInfo", listener: (arg: Error | string | TcpEndPoint | HeartbeatInfo) => void): this;
}
// Expose helper functions
export interface ConnectionSettings {
log?: Logger,
verboseLogging?: boolean,
@ -307,62 +380,12 @@ export interface ConnectionSettings {
// Cluster Settings
clusterDns?: string,
maxDiscoverAttempts?: number,
discoverDelay?: number,
externalGossipPort?: number,
gossipTimeout?: number
}
// Expose Helper functions
export function createConnection(settings: ConnectionSettings, endPointOrGossipSeed: string | TcpEndPoint | GossipSeed[], connectionName?: string): EventStoreNodeConnection;
export function createJsonEventData(eventId: string, event: any, metadata?: any, type?: string): EventData;
export function createEventData(eventId: string, type: string, isJson: boolean, data: Buffer, metadata?: Buffer): EventData;
// Projections
export interface ProjectionDetails {
coreProcessingTime: number,
version: number,
epoch: number,
effectiveName: string,
writesInProgress: number,
readsInProgress: number,
partitionsCached: number,
status: string,
stateReason: string,
name: string,
mode: string,
position: string,
progress: number,
lastCheckpoint: string,
eventsProcessedAfterRestart: number,
statusUrl: string,
stateUrl: string,
resultUrl: string,
queryUrl: string,
enableCommandUrl: string,
disableCommandUrl: string,
checkpointStatus: string,
bufferedEvents: number,
writePendingEventsBeforeCheckpoint: number,
writePendingEventsAfterCheckpoint: number
}
export class ProjectionsManager {
constructor(log: Logger, httpEndPoint: string, operationTimeout: number);
enable(name: string, userCredentials: UserCredentials): Promise<void>;
disable(name: string, userCredentials: UserCredentials): Promise<void>;
abort(name: string, userCredentials: UserCredentials): Promise<void>;
createOneTime(query: string, userCredentials: UserCredentials): Promise<void>;
createTransient(name: string, query: string, userCredentials: UserCredentials): Promise<void>;
createContinuous(name: string, query: string, trackEmittedStreams: boolean, userCredentials: UserCredentials): Promise<void>;
listAll(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
listOneTime(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
listContinuous(userCredentials: UserCredentials): Promise<ProjectionDetails[]>;
getStatus(name: string, userCredentials: UserCredentials): Promise<string>;
getState(name: string, userCredentials: UserCredentials): Promise<string>;
getPartitionState(name: string, partitionId: string, userCredentials: UserCredentials): Promise<string>;
getResult(name: string, userCredentials: UserCredentials): Promise<string>;
getPartitionResult(name: string, partitionId: string, userCredentials: UserCredentials): Promise<string>;
getStatistics(name: string, userCredentials: UserCredentials): Promise<string>;
getQuery(name: string, userCredentials: UserCredentials): Promise<string>;
getState(name: string, userCredentials: UserCredentials): Promise<string>;
updateQuery(name: string, query: string, userCredentials: UserCredentials): Promise<void>;
deleteQuery(name: string, deleteEmittedStreams: boolean, userCredentials: UserCredentials): Promise<void>;
}

10576
package-lock.json generated

File diff suppressed because it is too large Load Diff

40
package.json

@ -1,20 +1,33 @@
{
"name": "node-eventstore-client",
"version": "0.1.9",
"version": "0.2.17",
"description": "A port of the EventStore .Net ClientAPI to Node.js",
"main": "index.js",
"types": "index.d.ts",
"engines": {
"node": ">=4.0"
"node": ">=5.10"
},
"engineStrict": true,
"scripts": {
"clean": "rm lib/dist.js",
"build": "webpack",
"clean": "rm -f lib/dist.js",
"prebuild": "npm run clean",
"build": "webpack -o ./lib/dist.js",
"pretest": "npm run build",
"test": "nodeunit",
"test-debug": "TESTS_VERBOSE_LOGGING=1 nodeunit",
"prepublish": "npm run build && npm run gendocs",
"test:jest:watch": "jest --watch --coverage",
"test:single": "npm run compose:single:start && npm run compose:wait && npm run compose:single:test ; npm run compose:single:stop",
"test:gossip": "npm run compose:cluster:start && npm run compose:wait && npm run compose:gossip:test ; npm run compose:cluster:stop",
"test:cluster": "npm run compose:cluster:start && npm run compose:wait && npm run compose:cluster:test ; npm run compose:cluster:stop",
"compose:single:start": "docker-compose -f docker-compose-single.yaml up --build -d",
"compose:cluster:start": "docker-compose -f docker-compose-cluster.yaml up --build -d",
"compose:single:stop": "docker-compose -f docker-compose-single.yaml down -v --remove-orphans",
"compose:cluster:stop": "docker-compose -f docker-compose-cluster.yaml down -v --remove-orphans",
"compose:wait": "while [[ \"$(curl -s -o /dev/null -w ''%{http_code}'' localhost:2113/ping)\" != \"200\" ]]; do sleep 5; done",
"compose:single:test": "docker-compose -f docker-compose-single.yaml exec nodejs bash -c \"npm i && npm run build && EVENTSTORE_CONNECTION_TYPE=tcp EVENTSTORE_HOST=192.168.33.10 npm run test-debug\"",
"compose:cluster:test": "docker-compose -f docker-compose-cluster.yaml exec nodejs bash -c \"npm i && npm run build && EVENTSTORE_CONNECTION_TYPE=gossip EVENTSTORE_HOST=192.168.33.10 EVENTSTORE_HOST_1=192.168.33.10 EVENTSTORE_HOST_2=192.168.33.11 EVENTSTORE_HOST_3=192.168.33.12 npm run test-debug\"",
"compose:gossip:test": "docker-compose -f docker-compose-cluster.yaml exec nodejs bash -c \"npm i && npm run build && EVENTSTORE_CONNECTION_TYPE=dns EVENTSTORE_HOST=192.168.33.10 npm run test-debug\"",
"prepublishOnly": "npm run build && npm run gendocs",
"gendocs": "rm -rf docs && jsdoc src -r -d docs"
},
"files": [
@ -45,15 +58,18 @@
},
"homepage": "https://github.com/nicdex/node-eventstore-client#readme",
"dependencies": {
"@types/long": "^3.0.31",
"@types/node": "^6.0.47",
"long": "^3.2",
"protobufjs": "^6.7.3",
"@types/long": "^3.0.32",
"@types/node": ">=5.10",
"long": "^3.2.0",
"protobufjs": "^6.8.8",
"strict-event-emitter-types": "^1.2.0",
"uuid": "^3.0.1"
},
"devDependencies": {
"jsdoc": "^3.5.3",
"nodeunit": "^0.11.1",
"webpack": "^3.3.0"
"jest": "^26.4.2",
"jsdoc": "^3.6.3",
"nodeunit": "^0.11.3",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10"
}
}

62
samples/issue-60.js

@ -0,0 +1,62 @@
const client = require('../src/client'); // RWM: Import from npm installed package rather than from src
//const client = require("node-eventstore-client");
const resolveLinkTos = true;
function resumeEvent(event) {
return [
event.originalEvent.eventType,
[event.originalEventNumber.toNumber(), event.originalStreamId].join('@'),
event.originalPosition
].join(" ")
}
const eventAppeared = (subscription, event) => console.log("Event received", resumeEvent(event));
const subscriptionDropped = (subscription, reason, error) => console.log("Subscription dropped", reason, error);
const libeProcessingStarted = () => console.log("Live processing started.");
const credentials = new client.UserCredentials("admin", "changeit");
const settings = {
maxReconnections: 10,
reconnectionDelay: 1000, // RWM: slow down the reconnection attempts. 10 seconds to restore connection.
};
if (process.env.ENABLE_LOGGING) settings.log = console;
if (process.env.VERBOSE) settings.verboseLogging = true;
const endpoint = "tcp://localhost:1113";
const connection = client.createConnection(settings, endpoint);
connection.connect().catch(err => console.log("Connection failed", err));
connection.on('heartbeatInfo', heartbeatInfo =>
console.log('Heartbeat latency', heartbeatInfo.responseReceivedAt - heartbeatInfo.requestSentAt, 'ms')
);
connection.once("connected", tcpEndPoint => {
console.log(`Connected to eventstore at ${tcpEndPoint.host}:${tcpEndPoint.port}`);
// RWM: subscribe Stream instead of All
connection.subscribeToStreamFrom(
"test", // RWM: Stream to subscribe to
null,
resolveLinkTos,
eventAppeared,
libeProcessingStarted,
subscriptionDropped,
credentials
);
});
connection.on("error", error =>
console.log(`Error occurred on connection: ${error}`)
)
connection.on("closed", reason =>
console.log(`Connection closed, reason: ${reason}`)
)
// RWM: Handle the reconnecting event, for better awareness of what's happening
connection.on("reconnecting", msg =>
console.log(`Reconnecting, msg: ${JSON.stringify(msg, null, 4)}`)
)

50
samples/subscribe-all-from-events.js

@ -0,0 +1,50 @@
const client = require('../src/client');
//const client = require("node-eventstore-client");
const resolveLinkTos = true;
function resumeEvent(event) {
return [
event.originalEvent.eventType,
[event.originalEventNumber.toNumber(), event.originalStreamId].join('@'),
event.originalPosition
].join(" ")
}
const eventAppeared = (subscription, event) => console.log("Event received", resumeEvent(event));
const subscriptionDropped = (subscription, reason, error) => console.log("Subscription dropped", reason, error);
const libeProcessingStarted = () => console.log("Live processing started.");
const credentials = new client.UserCredentials("admin", "changeit");
const settings = {};
const endpoint = "tcp://localhost:1113";
const connection = client.createConnection(settings, endpoint);
connection.connect().catch(err => console.log("Connection failed", err));
connection.on('heartbeatInfo', heartbeatInfo =>
console.log('Heartbeat latency', heartbeatInfo.responseReceivedAt - heartbeatInfo.requestSentAt, 'ms')
);
connection.once("connected", tcpEndPoint => {
console.log(`Connected to eventstore at ${tcpEndPoint.host}:${tcpEndPoint.port}`);
connection.subscribeToAllFrom(
null,
resolveLinkTos,
eventAppeared,
libeProcessingStarted,
subscriptionDropped,
credentials
);
});
connection.on("error", error =>
console.log(`Error occurred on connection: ${error}`)
)
connection.on("closed", reason =>
console.log(`Connection closed, reason: ${reason}`)
)

59
src/client.js

@ -4,15 +4,23 @@ var results = require('./results');
const expectedVersion = {
any: -2,
noStream: -1,
emptyStream: -1
emptyStream: -1,
streamExists: -4
};
Object.freeze(expectedVersion);
const positions = {
start: new results.Position(0, 0),
end: new results.Position(-1, -1)
};
Object.freeze(positions);
const streamPosition = {
start: 0,
end: -1
};
Object.freeze(streamPosition);
/**
* Create an EventData object from JavaScript event/metadata that will be serialized as json
* @public
@ -25,8 +33,8 @@ Object.freeze(positions);
function createJsonEventData(eventId, event, metadata, type) {
if (!event || typeof event !== 'object') throw new TypeError("data must be an object.");
var eventBuf = new Buffer(JSON.stringify(event));
var metaBuf = metadata ? new Buffer(JSON.stringify(metadata)) : null;
var eventBuf = Buffer.from(JSON.stringify(event));
var metaBuf = metadata ? Buffer.from(JSON.stringify(metadata)) : null;
return new EventData(eventId, type || event.constructor.name, true, eventBuf, metaBuf);
}
@ -45,28 +53,31 @@ function createEventData(eventId, type, isJson, data, metadata) {
}
// Expose classes
module.exports.Position = results.Position;
module.exports.UserCredentials = require('./systemData/userCredentials');
module.exports.PersistentSubscriptionSettings = require('./persistentSubscriptionSettings');
module.exports.SystemConsumerStrategies = require('./systemConsumerStrategies');
module.exports.GossipSeed = require('./gossipSeed');
module.exports.EventStoreConnection = require('./eventStoreConnection');
module.exports.ProjectionsManager = require('./projections/projectionsManager');
exports.Position = results.Position;
exports.UserCredentials = require('./systemData/userCredentials');
exports.PersistentSubscriptionSettings = require('./persistentSubscriptionSettings');
exports.SystemConsumerStrategies = require('./systemConsumerStrategies');
exports.GossipSeed = require('./gossipSeed');
exports.EventStoreConnection = require('./eventStoreConnection');
exports.ProjectionsManager = require('./projections/projectionsManager');
// Expose errors
module.exports.WrongExpectedVersionError = require('./errors/wrongExpectedVersionError');
module.exports.StreamDeletedError = require('./errors/streamDeletedError');
module.exports.AccessDeniedError = require('./errors/accessDeniedError');
module.exports.ProjectionCommandFailedError = require('./errors/projectionCommandFailedError');
exports.WrongExpectedVersionError = require('./errors/wrongExpectedVersionError');
exports.StreamDeletedError = require('./errors/streamDeletedError');
exports.AccessDeniedError = require('./errors/accessDeniedError');
exports.ProjectionCommandFailedError = require('./errors/projectionCommandFailedError');
// Expose enums/constants
module.exports.expectedVersion = expectedVersion;
module.exports.positions = positions;
module.exports.systemMetadata = require('./common/systemMetadata');
module.exports.eventReadStatus = results.EventReadStatus;
module.exports.sliceReadStatus = require('./sliceReadStatus');
exports.expectedVersion = expectedVersion;
exports.positions = positions;
exports.streamPosition = streamPosition;
exports.systemMetadata = require('./common/systemMetadata');
exports.eventReadStatus = results.EventReadStatus;
exports.sliceReadStatus = require('./sliceReadStatus');
exports.persistentSubscriptionNakEventAction =
exports.PersistentSubscriptionNakEventAction = require('./persistentSubscriptionNakEventAction');
// Expose loggers
module.exports.NoopLogger = require('./common/log/noopLogger');
module.exports.FileLogger = require('./common/log/fileLogger');
exports.NoopLogger = require('./common/log/noopLogger');
exports.FileLogger = require('./common/log/fileLogger');
// Expose Helper functions
module.exports.createConnection = require('./eventStoreConnection').create;
module.exports.createJsonEventData = createJsonEventData;
module.exports.createEventData = createEventData;
exports.createConnection = require('./eventStoreConnection').create;
exports.createJsonEventData = createJsonEventData;
exports.createEventData = createEventData;

5
src/clientOperations/appendToStreamOperation.js

@ -44,8 +44,7 @@ AppendToStreamOperation.prototype._inspectResponse = function(response) {
switch (response.result)
{
case ClientMessage.OperationResult.Success:
if (this._wasCommitTimeout)
this.log.debug("IDEMPOTENT WRITE SUCCEEDED FOR %s.", this);
if (this._wasCommitTimeout) this.log.debug("IDEMPOTENT WRITE SUCCEEDED FOR %s.", this);
this._succeed();
return new InspectionResult(InspectionDecision.EndOperation, "Success");
case ClientMessage.OperationResult.PrepareTimeout:
@ -80,4 +79,4 @@ AppendToStreamOperation.prototype.toString = function() {
return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
};
module.exports = AppendToStreamOperation;
module.exports = AppendToStreamOperation;

1
src/clientOperations/commitTransactionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var InspectionDecision = require('../systemData/inspectionDecision');

2
src/clientOperations/connectToPersistentSubscriptionOperation.js

@ -124,4 +124,4 @@ ConnectToPersistentSubscriptionOperation.prototype.notifyEventsFailed = function
this._enqueueSend(pkg);
};
module.exports = ConnectToPersistentSubscriptionOperation;
module.exports = ConnectToPersistentSubscriptionOperation;

3
src/clientOperations/createPersistentSubscriptionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var ensure = require('../common/utils/ensure');
var OperationBase = require('../clientOperations/operationBase');
@ -84,4 +83,4 @@ CreatePersistentSubscriptionOperation.prototype.toString = function() {
return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
};
module.exports = CreatePersistentSubscriptionOperation;
module.exports = CreatePersistentSubscriptionOperation;

4
src/clientOperations/deletePersistentSubscriptionOperation.js

@ -1,7 +1,5 @@
var util = require('util');
var uuid = require('uuid');
var ensure =