@weave-js/core 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/.eslintrc.js +1 -1
  2. package/jest.config.js +1 -1
  3. package/lib/ExtendableError.js +7 -7
  4. package/lib/broker/context.js +49 -49
  5. package/lib/broker/defaultOptions.js +8 -9
  6. package/lib/broker/index.js +160 -164
  7. package/lib/buildRuntime.js +34 -34
  8. package/lib/cache/adapters/base.js +50 -74
  9. package/lib/cache/adapters/inMemory.js +58 -58
  10. package/lib/cache/adapters/inMemoryLru.js +57 -57
  11. package/lib/cache/adapters/index.js +3 -39
  12. package/lib/cache/getCacheKeyByObject.js +31 -0
  13. package/lib/cache/getPropertyFromDataOrMetadata.js +20 -0
  14. package/lib/cache/lock.js +30 -24
  15. package/lib/constants.js +5 -5
  16. package/lib/errorHandler.js +8 -8
  17. package/lib/errors.js +35 -35
  18. package/lib/helper/defineAction.js +2 -2
  19. package/lib/helper/defineBrokerOptions.js +2 -2
  20. package/lib/helper/defineService.js +2 -2
  21. package/lib/index.js +21 -21
  22. package/lib/logger/base.js +38 -29
  23. package/lib/logger/format/asHumanReadable.js +15 -15
  24. package/lib/logger/format/asJson.js +10 -10
  25. package/lib/logger/format/index.js +3 -3
  26. package/lib/logger/index.js +24 -24
  27. package/lib/logger/levels.js +21 -21
  28. package/lib/logger/tools.js +15 -15
  29. package/lib/logger/utils/colorize.js +23 -23
  30. package/lib/logger/utils/format.js +75 -65
  31. package/lib/metrics/common.js +47 -47
  32. package/lib/metrics/constants.js +44 -44
  33. package/lib/metrics/exporter/base.js +8 -8
  34. package/lib/metrics/exporter/event.js +20 -20
  35. package/lib/metrics/exporter/index.js +15 -15
  36. package/lib/metrics/index.js +2 -2
  37. package/lib/metrics/types/base.js +20 -20
  38. package/lib/metrics/types/counter.js +6 -6
  39. package/lib/metrics/types/gauge.js +24 -24
  40. package/lib/metrics/types/histogram.js +26 -26
  41. package/lib/metrics/types/index.js +6 -6
  42. package/lib/metrics/types/info.js +17 -17
  43. package/lib/middlewares/action-hooks/index.js +38 -38
  44. package/lib/middlewares/bulkhead/index.js +34 -34
  45. package/lib/middlewares/cache/index.js +37 -37
  46. package/lib/middlewares/circuit-breaker/index.js +62 -62
  47. package/lib/middlewares/context-tracker/index.js +39 -39
  48. package/lib/middlewares/error-handler/index.js +14 -14
  49. package/lib/middlewares/index.js +2 -2
  50. package/lib/middlewares/metrics/getMiddlewareWrapper.js +17 -17
  51. package/lib/middlewares/metrics/index.js +29 -29
  52. package/lib/middlewares/retry/index.js +15 -15
  53. package/lib/middlewares/timeout/index.js +16 -16
  54. package/lib/middlewares/tracing/index.js +37 -37
  55. package/lib/middlewares/tracing/tags.js +6 -6
  56. package/lib/middlewares/validator/index.js +31 -31
  57. package/lib/registry/actionEndpoint.js +8 -8
  58. package/lib/registry/collections/actionCollection.js +39 -35
  59. package/lib/registry/collections/endpointCollection.js +63 -63
  60. package/lib/registry/collections/eventCollection.js +62 -62
  61. package/lib/registry/collections/nodeCollection.js +45 -45
  62. package/lib/registry/collections/serviceCollection.js +61 -55
  63. package/lib/registry/eventEndpoint.js +14 -14
  64. package/lib/registry/load-balancer/base.js +3 -3
  65. package/lib/registry/load-balancer/index.js +7 -7
  66. package/lib/registry/node.js +27 -27
  67. package/lib/registry/registry.js +139 -136
  68. package/lib/registry/service/parseAction.js +16 -16
  69. package/lib/registry/service/parseEvent.js +18 -18
  70. package/lib/registry/service/reduceMixins.js +10 -10
  71. package/lib/registry/service/service.js +72 -72
  72. package/lib/registry/serviceItem.js +21 -21
  73. package/lib/runtime/initActionInvoker.js +21 -21
  74. package/lib/runtime/initCache.js +7 -7
  75. package/lib/runtime/initContextFactory.js +22 -22
  76. package/lib/runtime/initEventbus.js +49 -49
  77. package/lib/runtime/initLogger.js +11 -11
  78. package/lib/runtime/initMetrics.js +54 -54
  79. package/lib/runtime/initMiddlewareManager.js +21 -21
  80. package/lib/runtime/initRegistry.js +6 -6
  81. package/lib/runtime/initServiceManager.js +85 -68
  82. package/lib/runtime/initTracing.js +23 -23
  83. package/lib/runtime/initTransport.js +5 -5
  84. package/lib/runtime/initUuidFactory.js +4 -4
  85. package/lib/runtime/initValidator.js +5 -5
  86. package/lib/tracing/collectors/base.js +22 -22
  87. package/lib/tracing/collectors/event.js +33 -33
  88. package/lib/tracing/collectors/index.js +15 -15
  89. package/lib/tracing/span.js +26 -26
  90. package/lib/tracing/time.js +8 -8
  91. package/lib/transport/InboundTransformStream.js +26 -26
  92. package/lib/transport/adapters/adapteBase.js +30 -30
  93. package/lib/transport/adapters/adapters.js +4 -4
  94. package/lib/transport/adapters/dummy/index.js +18 -18
  95. package/lib/transport/adapters/fromURI.js +13 -13
  96. package/lib/transport/adapters/getAdapterByName.js +5 -5
  97. package/lib/transport/adapters/index.js +12 -12
  98. package/lib/transport/adapters/tcp/discovery/codec.js +4 -4
  99. package/lib/transport/adapters/tcp/discovery/index.js +62 -62
  100. package/lib/transport/adapters/tcp/index.js +169 -171
  101. package/lib/transport/adapters/tcp/tcp-messagetypes.js +7 -7
  102. package/lib/transport/adapters/tcp/tcpReader.js +39 -39
  103. package/lib/transport/adapters/tcp/tcpWriteStream.js +26 -26
  104. package/lib/transport/adapters/tcp/tcpWriter.js +57 -57
  105. package/lib/transport/adapters/tcp/utils.js +12 -12
  106. package/lib/transport/createMessage.js +4 -4
  107. package/lib/transport/createTransport.js +254 -254
  108. package/lib/transport/errorPayloadFactory.js +14 -17
  109. package/lib/transport/messageHandlers.js +200 -200
  110. package/lib/transport/messageTypes.js +19 -19
  111. package/lib/types.js +28 -15
  112. package/lib/utils/index.js +1 -1
  113. package/lib/utils/options.js +44 -44
  114. package/lib/utils/restoreError.js +4 -4
  115. package/package.json +4 -4
  116. package/lib/cache/base.js +0 -136
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Author: Kevin Ries (kevin@fachw3rk.de)
2
+ * Author: Kevin Ries (kevin.ries@fachwerk.io)
3
3
  * -----
4
4
  * Copyright 2021 Fachwerk
5
5
  */
@@ -13,12 +13,12 @@
13
13
  */
14
14
 
15
15
  // Own packages
16
- const { WeaveError, WeaveQueueSizeExceededError } = require('../errors')
17
- const { createMessage } = require('./createMessage')
18
- const MessageTypes = require('./messageTypes')
19
- const utils = require('@weave-js/utils')
20
- const createMessageHandler = require('./messageHandlers')
21
- const { errorPayloadFactory } = require('./errorPayloadFactory')
16
+ const { WeaveError, WeaveQueueSizeExceededError } = require('../errors');
17
+ const { createMessage } = require('./createMessage');
18
+ const MessageTypes = require('./messageTypes');
19
+ const utils = require('@weave-js/utils');
20
+ const createMessageHandler = require('./messageHandlers');
21
+ const { errorPayloadFactory } = require('./errorPayloadFactory');
22
22
 
23
23
  /**
24
24
  * Create a Transport adapter
@@ -27,13 +27,13 @@ const { errorPayloadFactory } = require('./errorPayloadFactory')
27
27
  * @returns {Transport} transport
28
28
  */
29
29
  exports.createTransport = (runtime, adapter) => {
30
- const transport = Object.create(null)
31
- const { nodeId, middlewareHandler, createLogger } = runtime
30
+ const transport = Object.create(null);
31
+ const { nodeId, middlewareHandler, createLogger } = runtime;
32
32
 
33
- let heartbeatTimer
34
- let checkNodesTimer
35
- let checkOfflineNodesTimer
36
- let updateLocalNodeTimer
33
+ let heartbeatTimer;
34
+ let checkNodesTimer;
35
+ let checkOfflineNodesTimer;
36
+ let updateLocalNodeTimer;
37
37
 
38
38
  // Pending action store
39
39
  const pending = {
@@ -42,16 +42,16 @@ exports.createTransport = (runtime, adapter) => {
42
42
  responseStreams: new Map(),
43
43
  outboundResponseStreams: new Map(),
44
44
  outboundRequestStreams: new Map()
45
- }
46
-
47
- transport.log = createLogger('TRANSPORT')
48
- transport.reconnectInProgress = false
49
- transport.isConnected = false
50
- transport.isDisconnecting = false
51
- transport.isReady = false
52
- transport.pending = pending
53
- transport.resolveConnect = null
54
- transport.adapterName = adapter.name
45
+ };
46
+
47
+ transport.log = createLogger('TRANSPORT');
48
+ transport.reconnectInProgress = false;
49
+ transport.isConnected = false;
50
+ transport.isDisconnecting = false;
51
+ transport.isReady = false;
52
+ transport.pending = pending;
53
+ transport.resolveConnect = null;
54
+ transport.adapterName = adapter.name;
55
55
  transport.statistics = {
56
56
  received: {
57
57
  packages: 0
@@ -59,68 +59,68 @@ exports.createTransport = (runtime, adapter) => {
59
59
  sent: {
60
60
  packages: 0
61
61
  }
62
- }
62
+ };
63
63
 
64
- const getErrorPayload = errorPayloadFactory(runtime)
64
+ const getErrorPayload = errorPayloadFactory(runtime);
65
65
 
66
66
  transport.connect = () => {
67
67
  return new Promise(resolve => {
68
- transport.resolveConnect = resolve
69
- transport.log.info('Connecting to transport adapter...')
68
+ transport.resolveConnect = resolve;
69
+ transport.log.info('Connecting to transport adapter...');
70
70
 
71
71
  const doConnect = (isTryReconnect) => {
72
72
  const errorHandler = (error) => {
73
73
  // Skip reconnect, if the adapter is disconnecting or an reconnect is in progress.
74
74
  if (transport.isDisconnecting || transport.reconnectInProgress) {
75
- return
75
+ return;
76
76
  }
77
77
 
78
- transport.log.warn('Connection failed')
79
- transport.log.debug(error)
78
+ transport.log.warn('Connection failed');
79
+ transport.log.debug(error);
80
80
 
81
- transport.reconnectInProgress = true
81
+ transport.reconnectInProgress = true;
82
82
 
83
83
  if (!error.skipRetry) {
84
84
  setTimeout(() => {
85
- transport.log.info('Reconnecting')
86
- doConnect(true)
87
- }, 5 * 1000)
85
+ transport.log.info('Reconnecting');
86
+ doConnect(true);
87
+ }, 5 * 1000);
88
88
  }
89
- }
89
+ };
90
90
  return adapter
91
91
  .connect(isTryReconnect, errorHandler)
92
- .catch(errorHandler)
93
- }
92
+ .catch(errorHandler);
93
+ };
94
94
 
95
- doConnect(false)
96
- })
97
- }
95
+ doConnect(false);
96
+ });
97
+ };
98
98
 
99
99
  transport.disconnect = () => {
100
- transport.isDisconnecting = true
101
- transport.isConnected = false
102
- transport.isReady = false
100
+ transport.isDisconnecting = true;
101
+ transport.isConnected = false;
102
+ transport.isReady = false;
103
103
 
104
- runtime.eventBus.broadcastLocal('$transporter.disconnected', { isGraceful: true })
104
+ runtime.eventBus.broadcastLocal('$transporter.disconnected', { isGraceful: true });
105
105
 
106
- stopTimers()
106
+ stopTimers();
107
107
 
108
- const message = createMessage(MessageTypes.MESSAGE_DISCONNECT)
108
+ const message = createMessage(MessageTypes.MESSAGE_DISCONNECT);
109
109
  return transport.send(message)
110
110
  .then(() => {
111
- adapter.close()
111
+ adapter.close();
112
112
  })
113
113
  .then(() => {
114
- transport.isDisconnecting = false
115
- })
116
- }
114
+ transport.isDisconnecting = false;
115
+ });
116
+ };
117
117
 
118
118
  transport.setReady = async () => {
119
119
  if (transport.isConnected) {
120
- transport.isReady = true
121
- await transport.sendNodeInfo()
120
+ transport.isReady = true;
121
+ await transport.sendNodeInfo();
122
122
  }
123
- }
123
+ };
124
124
 
125
125
  /**
126
126
  * Send node information.
@@ -129,18 +129,18 @@ exports.createTransport = (runtime, adapter) => {
129
129
  */
130
130
  transport.sendNodeInfo = async (sender) => {
131
131
  if (!transport.isConnected || !transport.isReady) {
132
- return Promise.resolve()
132
+ return Promise.resolve();
133
133
  }
134
134
 
135
135
  // Collect own node info and send it to remote nodes
136
- const info = runtime.registry.getLocalNodeInfo()
136
+ const info = runtime.registry.getLocalNodeInfo();
137
137
  const message = createMessage(MessageTypes.MESSAGE_INFO, sender, {
138
138
  ...info,
139
139
  instanceId: runtime.state.instanceId
140
- })
140
+ });
141
141
 
142
- return transport.send(message)
143
- }
142
+ return transport.send(message);
143
+ };
144
144
 
145
145
  /**
146
146
  * Send a message
@@ -148,24 +148,24 @@ exports.createTransport = (runtime, adapter) => {
148
148
  * @returns {Promise} Promise
149
149
  */
150
150
  transport.send = async (message) => {
151
- transport.statistics.sent.packages = transport.statistics.sent.packages + 1
152
- transport.log.verbose(`Send ${message.type.toUpperCase()} packet to ${message.targetNodeId || 'all nodes'}`)
153
- return adapter.preSend(message)
154
- }
151
+ transport.statistics.sent.packages = transport.statistics.sent.packages + 1;
152
+ transport.log.verbose(`Send ${message.type.toUpperCase()} packet to ${message.targetNodeId || 'all nodes'}`);
153
+ return adapter.preSend(message);
154
+ };
155
155
 
156
156
  transport.sendPing = (nodeId) => {
157
- const pingMessage = createMessage(MessageTypes.MESSAGE_PING, nodeId, { dispatchTime: Date.now() })
158
- return transport.send(pingMessage)
159
- }
157
+ const pingMessage = createMessage(MessageTypes.MESSAGE_PING, nodeId, { dispatchTime: Date.now() });
158
+ return transport.send(pingMessage);
159
+ };
160
160
 
161
161
  /**
162
162
  * Send discovery message to all nodes.
163
163
  * @returns {void}
164
164
  */
165
165
  transport.discoverNodes = () => {
166
- const discoveryMessage = createMessage(MessageTypes.MESSAGE_DISCOVERY)
167
- transport.send(discoveryMessage)
168
- }
166
+ const discoveryMessage = createMessage(MessageTypes.MESSAGE_DISCOVERY);
167
+ transport.send(discoveryMessage);
168
+ };
169
169
 
170
170
  /**
171
171
  * Send discovery message to all nodes.
@@ -173,9 +173,9 @@ exports.createTransport = (runtime, adapter) => {
173
173
  * @returns {Promise<void>} - Promise
174
174
  */
175
175
  transport.discoverNode = async (target) => {
176
- const discoveryMessage = createMessage(MessageTypes.MESSAGE_DISCOVERY, target)
177
- return transport.send(discoveryMessage)
178
- }
176
+ const discoveryMessage = createMessage(MessageTypes.MESSAGE_DISCOVERY, target);
177
+ return transport.send(discoveryMessage);
178
+ };
179
179
 
180
180
  /**
181
181
  * Send an event
@@ -183,7 +183,7 @@ exports.createTransport = (runtime, adapter) => {
183
183
  * @returns {Promise<void>} - Promise
184
184
  */
185
185
  transport.sendEvent = async (context) => {
186
- const isBroadcast = context.eventType === 'broadcast'
186
+ const isBroadcast = context.eventType === 'broadcast';
187
187
 
188
188
  const payload = {
189
189
  data: context.data,
@@ -195,46 +195,46 @@ exports.createTransport = (runtime, adapter) => {
195
195
  requestId: context.requestId,
196
196
  parentId: context.parentId,
197
197
  isBroadcast
198
- }
198
+ };
199
199
 
200
- const message = createMessage(MessageTypes.MESSAGE_EVENT, context.endpoint ? context.nodeId : null, payload)
201
- return transport.send(message)
202
- }
200
+ const message = createMessage(MessageTypes.MESSAGE_EVENT, context.endpoint ? context.nodeId : null, payload);
201
+ return transport.send(message);
202
+ };
203
203
 
204
204
  transport.sendBroadcastEvent = (nodeId, eventName, data, groups) => {
205
- transport.log.verbose(`Send ${eventName} to ${nodeId}`)
205
+ transport.log.verbose(`Send ${eventName} to ${nodeId}`);
206
206
 
207
207
  const payload = {
208
208
  data,
209
209
  eventName,
210
210
  groups,
211
211
  isBroadcast: true
212
- }
212
+ };
213
213
 
214
- const message = createMessage(MessageTypes.MESSAGE_EVENT, nodeId, payload)
215
- return transport.send(message)
216
- }
214
+ const message = createMessage(MessageTypes.MESSAGE_EVENT, nodeId, payload);
215
+ return transport.send(message);
216
+ };
217
217
 
218
218
  transport.removePendingRequestsById = (requestId) => {
219
- pending.requests.delete(requestId)
220
- pending.requestStreams.delete(requestId)
221
- pending.responseStreams.delete(requestId)
222
- pending.outboundResponseStreams.delete(requestId)
223
- pending.outboundRequestStreams.delete(requestId)
224
- }
219
+ pending.requests.delete(requestId);
220
+ pending.requestStreams.delete(requestId);
221
+ pending.responseStreams.delete(requestId);
222
+ pending.outboundResponseStreams.delete(requestId);
223
+ pending.outboundRequestStreams.delete(requestId);
224
+ };
225
225
 
226
226
  transport.removePendingRequestsByNodeId = (nodeId) => {
227
- transport.log.debug(`Remove pending requests for node ${nodeId}.`)
227
+ transport.log.debug(`Remove pending requests for node ${nodeId}.`);
228
228
  pending.requests.forEach((request, requestId) => {
229
229
  if (request.nodeId === nodeId) {
230
- pending.requests.delete(requestId)
230
+ pending.requests.delete(requestId);
231
231
  }
232
- request.reject(new WeaveError(`Remove pending requests for node ${nodeId}.`))
232
+ request.reject(new WeaveError(`Remove pending requests for node ${nodeId}.`));
233
233
 
234
- pending.requestStreams.delete(requestId)
235
- pending.responseStreams.delete(requestId)
236
- })
237
- }
234
+ pending.requestStreams.delete(requestId);
235
+ pending.responseStreams.delete(requestId);
236
+ });
237
+ };
238
238
 
239
239
  transport.sendRequest = (context) => {
240
240
  // If the queue size is set, check the queue size and reject the job when the limit is reached.
@@ -244,11 +244,11 @@ exports.createTransport = (runtime, adapter) => {
244
244
  limit: runtime.options.transport.maxQueueSize,
245
245
  nodeId: context.nodeId,
246
246
  size: pending.requests.size
247
- }))
247
+ }));
248
248
  }
249
249
 
250
250
  return new Promise((resolve, reject) => {
251
- const isStream = utils.isStream(context.options.stream)
251
+ const isStream = utils.isStream(context.options.stream);
252
252
 
253
253
  const request = {
254
254
  targetNodeId: context.nodeId,
@@ -257,11 +257,11 @@ exports.createTransport = (runtime, adapter) => {
257
257
  resolve,
258
258
  reject,
259
259
  isStream
260
- }
260
+ };
261
261
 
262
- transport.log.debug(`Send request for ${request.action} to node ${request.targetNodeId}.`)
262
+ transport.log.debug(`Send request for ${request.action} to node ${request.targetNodeId}.`);
263
263
 
264
- pending.requests.set(context.id, request)
264
+ pending.requests.set(context.id, request);
265
265
 
266
266
  const payload = {
267
267
  id: context.id,
@@ -274,104 +274,104 @@ exports.createTransport = (runtime, adapter) => {
274
274
  requestId: context.requestId,
275
275
  parentId: context.parentId,
276
276
  isStream
277
- }
277
+ };
278
278
 
279
279
  // Handle object mode streams
280
280
  if (isStream) {
281
- const stream = context.options.stream
281
+ const stream = context.options.stream;
282
282
 
283
283
  if (!pending.outboundRequestStreams.has(payload.id)) {
284
- pending.outboundRequestStreams.set(payload.id, stream)
284
+ pending.outboundRequestStreams.set(payload.id, stream);
285
285
  }
286
286
 
287
287
  if (utils.isStreamObjectMode(stream)) {
288
- payload.meta = payload.meta || {}
289
- payload.meta.$isObjectModeStream = true
288
+ payload.meta = payload.meta || {};
289
+ payload.meta.$isObjectModeStream = true;
290
290
  }
291
- payload.sequence = 0
291
+ payload.sequence = 0;
292
292
  }
293
293
 
294
- const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payload)
294
+ const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payload);
295
295
 
296
296
  return transport.send(message)
297
297
  .then(() => {
298
298
  // send stream
299
299
  if (isStream) {
300
- const stream = context.options.stream
301
- payload.meta = {}
300
+ const stream = context.options.stream;
301
+ payload.meta = {};
302
302
 
303
303
  if (utils.isStreamObjectMode(context.options.stream)) {
304
- payload.meta.$isObjectModeStream = true
304
+ payload.meta.$isObjectModeStream = true;
305
305
  }
306
306
 
307
307
  stream.on('data', data => {
308
- stream.pause()
309
- const chunks = []
308
+ stream.pause();
309
+ const chunks = [];
310
310
 
311
311
  // The chunk is larger than maxBufferSize
312
312
  if (data instanceof Buffer && runtime.options.transport.maxChunkSize > 0 && data.length > runtime.options.transport.maxChunkSize) {
313
- const length = data.length
314
- let i = 0
313
+ const length = data.length;
314
+ let i = 0;
315
315
  while (i < length) {
316
- chunks.push(data.slice(i, i += runtime.options.transport.maxChunkSize))
316
+ chunks.push(data.slice(i, i += runtime.options.transport.maxChunkSize));
317
317
  }
318
318
  } else {
319
- chunks.push(data)
319
+ chunks.push(data);
320
320
  }
321
321
 
322
322
  // Send chunks from chunk buffer
323
323
  for (const chunk of chunks) {
324
- const payloadCopy = Object.assign({}, payload)
325
- payloadCopy.sequence = ++payload.sequence
326
- payloadCopy.chunk = chunk
327
- payloadCopy.isStream = true
328
- payload.data = null
329
-
330
- const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy)
331
- transport.send(message)
324
+ const payloadCopy = Object.assign({}, payload);
325
+ payloadCopy.sequence = ++payload.sequence;
326
+ payloadCopy.chunk = chunk;
327
+ payloadCopy.isStream = true;
328
+ payload.data = null;
329
+
330
+ const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy);
331
+ transport.send(message);
332
332
  }
333
333
 
334
334
  // resume stream
335
- stream.resume()
336
- return
337
- })
335
+ stream.resume();
336
+ return;
337
+ });
338
338
 
339
339
  stream.on('end', () => {
340
- const payloadCopy = Object.assign({}, payload)
340
+ const payloadCopy = Object.assign({}, payload);
341
341
 
342
- payloadCopy.sequence = ++payload.sequence
343
- payloadCopy.chunk = null
344
- payloadCopy.isStream = false
342
+ payloadCopy.sequence = ++payload.sequence;
343
+ payloadCopy.chunk = null;
344
+ payloadCopy.isStream = false;
345
345
 
346
- pending.outboundRequestStreams.delete(payload.id)
346
+ pending.outboundRequestStreams.delete(payload.id);
347
347
 
348
- const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy)
349
- return transport.send(message)
350
- })
348
+ const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy);
349
+ return transport.send(message);
350
+ });
351
351
 
352
352
  stream.on('error', (error) => {
353
- const payloadCopy = Object.assign({}, payload)
354
- payloadCopy.sequence = ++payload.sequence
355
- payloadCopy.chunk = null
356
- payloadCopy.isStream = false
353
+ const payloadCopy = Object.assign({}, payload);
354
+ payloadCopy.sequence = ++payload.sequence;
355
+ payloadCopy.chunk = null;
356
+ payloadCopy.isStream = false;
357
357
 
358
358
  if (error) {
359
- payloadCopy.success = false
360
- payloadCopy.error = getErrorPayload(error)
359
+ payloadCopy.success = false;
360
+ payloadCopy.error = getErrorPayload(error);
361
361
  }
362
362
 
363
- pending.outboundRequestStreams.delete(payload.id)
363
+ pending.outboundRequestStreams.delete(payload.id);
364
364
 
365
- const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy)
366
- return transport.send(message)
367
- })
365
+ const message = createMessage(MessageTypes.MESSAGE_REQUEST, context.nodeId, payloadCopy);
366
+ return transport.send(message);
367
+ });
368
368
  }
369
369
  })
370
370
  .catch((error) => {
371
- reject(error)
372
- })
373
- })
374
- }
371
+ reject(error);
372
+ });
373
+ });
374
+ };
375
375
 
376
376
  /**
377
377
  * Send response for an open request.
@@ -384,7 +384,7 @@ exports.createTransport = (runtime, adapter) => {
384
384
  */
385
385
  transport.sendResponse = (target, contextId, data, meta, error) => {
386
386
  // Check if data is a stream
387
- const isStream = utils.isStream(data)
387
+ const isStream = utils.isStream(data);
388
388
 
389
389
  // Build response payload
390
390
  const payload = {
@@ -392,168 +392,168 @@ exports.createTransport = (runtime, adapter) => {
392
392
  meta,
393
393
  data,
394
394
  success: error == null
395
- }
395
+ };
396
396
 
397
397
  // If an error is occurs, we attach the an error object to the payload.
398
398
  if (error) {
399
- payload.error = getErrorPayload(error)
399
+ payload.error = getErrorPayload(error);
400
400
  }
401
401
 
402
402
  if (isStream) {
403
- const stream = data
403
+ const stream = data;
404
404
 
405
405
  if (!pending.outboundResponseStreams.has(payload.id)) {
406
- pending.outboundResponseStreams.set(payload.id, stream)
406
+ pending.outboundResponseStreams.set(payload.id, stream);
407
407
  }
408
408
 
409
- payload.data = null
410
- payload.sequence = 0
411
- payload.isStream = true
409
+ payload.data = null;
410
+ payload.sequence = 0;
411
+ payload.isStream = true;
412
412
 
413
413
  if (utils.isStreamObjectMode(data)) {
414
- payload.meta = payload.meta || {}
415
- payload.meta.$isObjectModeStream = true
414
+ payload.meta = payload.meta || {};
415
+ payload.meta.$isObjectModeStream = true;
416
416
  }
417
417
 
418
- stream.pause()
419
- transport.log.debug('Send new stream chunk to ', target)
418
+ stream.pause();
419
+ transport.log.debug('Send new stream chunk to ', target);
420
420
 
421
421
  stream.on('data', data => {
422
- stream.pause()
423
- const chunks = []
422
+ stream.pause();
423
+ const chunks = [];
424
424
 
425
425
  // chunk is larger than maxBufferSize
426
426
  if (data instanceof Buffer && runtime.options.transport.maxChunkSize > 0 && data.length > runtime.options.transport.maxChunkSize) {
427
- const length = data.length
428
- let i = 0
427
+ const length = data.length;
428
+ let i = 0;
429
429
  while (i < length) {
430
- chunks.push(data.slice(i, i += runtime.options.transport.maxChunkSize))
430
+ chunks.push(data.slice(i, i += runtime.options.transport.maxChunkSize));
431
431
  }
432
432
  } else {
433
- chunks.push(data)
433
+ chunks.push(data);
434
434
  }
435
435
 
436
436
  // Send chunks from chunk buffer
437
437
  for (const chunk of chunks) {
438
- const payloadCopy = Object.assign({}, payload)
439
- payloadCopy.sequence = ++payload.sequence
438
+ const payloadCopy = Object.assign({}, payload);
439
+ payloadCopy.sequence = ++payload.sequence;
440
440
 
441
- payloadCopy.chunk = chunk
442
- transport.log.debug(`Send Stream chunk to ${target}`)
441
+ payloadCopy.chunk = chunk;
442
+ transport.log.debug(`Send Stream chunk to ${target}`);
443
443
 
444
- const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy)
445
- transport.send(message)
444
+ const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy);
445
+ transport.send(message);
446
446
  }
447
447
 
448
448
  // resume stream
449
- stream.resume()
450
- return
451
- })
449
+ stream.resume();
450
+ return;
451
+ });
452
452
 
453
453
  stream.on('end', () => {
454
- const payloadCopy = Object.assign({}, payload)
454
+ const payloadCopy = Object.assign({}, payload);
455
455
 
456
- payloadCopy.sequence = ++payload.sequence
457
- payloadCopy.chunk = null
458
- payloadCopy.isStream = false
456
+ payloadCopy.sequence = ++payload.sequence;
457
+ payloadCopy.chunk = null;
458
+ payloadCopy.isStream = false;
459
459
 
460
- transport.log.debug(`Send end stream chunk to ${target}`)
460
+ transport.log.debug(`Send end stream chunk to ${target}`);
461
461
 
462
- const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy)
463
- transport.send(message)
464
- pending.outboundResponseStreams.delete(payload.id)
465
- })
462
+ const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy);
463
+ transport.send(message);
464
+ pending.outboundResponseStreams.delete(payload.id);
465
+ });
466
466
 
467
467
  stream.on('error', (error) => {
468
- const payloadCopy = Object.assign({}, payload)
468
+ const payloadCopy = Object.assign({}, payload);
469
469
 
470
- payloadCopy.sequence = ++payload.sequence
471
- payloadCopy.isStream = false
472
- payloadCopy.chunk = null
470
+ payloadCopy.sequence = ++payload.sequence;
471
+ payloadCopy.isStream = false;
472
+ payloadCopy.chunk = null;
473
473
 
474
474
  if (error) {
475
- payloadCopy.success = false
476
- payloadCopy.error = getErrorPayload(error)
475
+ payloadCopy.success = false;
476
+ payloadCopy.error = getErrorPayload(error);
477
477
  }
478
478
 
479
- transport.log.debug(`Send closing chunk to ${target}`)
479
+ transport.log.debug(`Send closing chunk to ${target}`);
480
480
 
481
- const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy)
482
- transport.send(message)
483
- pending.outboundResponseStreams.delete(payload.id)
484
- })
481
+ const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payloadCopy);
482
+ transport.send(message);
483
+ pending.outboundResponseStreams.delete(payload.id);
484
+ });
485
485
 
486
- payload.data = null
487
- const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payload)
486
+ payload.data = null;
487
+ const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payload);
488
488
  return transport.send(message)
489
- .then(() => stream.resume())
489
+ .then(() => stream.resume());
490
490
  }
491
491
 
492
- const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payload)
493
- return transport.send(message)
494
- }
492
+ const message = createMessage(MessageTypes.MESSAGE_RESPONSE, target, payload);
493
+ return transport.send(message);
494
+ };
495
495
 
496
496
  const onConnect = ({ wasReconnect = false, useHeartbeatTimer = true, useRemoteNodeCheckTimer = true, useOfflineCheckTimer = true }) =>
497
497
  Promise.resolve()
498
498
  .then(() => {
499
499
  if (!wasReconnect) {
500
- return makeSubscriptions()
500
+ return makeSubscriptions();
501
501
  }
502
502
  })
503
503
  .then(() => transport.discoverNodes())
504
504
  .then(() => utils.promiseDelay(Promise.resolve(), 500))
505
505
  .then(() => {
506
- transport.isConnected = true
506
+ transport.isConnected = true;
507
507
 
508
- runtime.eventBus.broadcastLocal('$transporter.connected', { wasReconnect })
508
+ runtime.eventBus.broadcastLocal('$transporter.connected', { wasReconnect });
509
509
 
510
510
  if (transport.resolveConnect) {
511
- transport.resolveConnect()
512
- transport.resolveConnect = null
511
+ transport.resolveConnect();
512
+ transport.resolveConnect = null;
513
513
  }
514
514
  })
515
515
  .then(() => {
516
- startUpdateLocalNodeTimer()
516
+ startUpdateLocalNodeTimer();
517
517
 
518
518
  if (useHeartbeatTimer) {
519
- startHeartbeatTimer()
519
+ startHeartbeatTimer();
520
520
  }
521
521
 
522
522
  if (useRemoteNodeCheckTimer) {
523
- startRemoteNodeCheckTimer()
523
+ startRemoteNodeCheckTimer();
524
524
  }
525
525
 
526
526
  if (useOfflineCheckTimer) {
527
- startOfflineNodeCheckTimer()
527
+ startOfflineNodeCheckTimer();
528
528
  }
529
- })
529
+ });
530
530
 
531
531
  const onDisconnect = () => {
532
532
  Promise.resolve()
533
533
  .then(() => {
534
- transport.isConnected = false
535
- runtime.bus.emit('$transporter.disconnected')
534
+ transport.isConnected = false;
535
+ runtime.bus.emit('$transporter.disconnected');
536
536
  })
537
537
  .then(() => {
538
- stopTimers()
539
- })
540
- }
538
+ stopTimers();
539
+ });
540
+ };
541
541
 
542
- let messageHandler = createMessageHandler(runtime, transport)
542
+ let messageHandler = createMessageHandler(runtime, transport);
543
543
 
544
544
  // Wrap message handler for middlewares
545
- messageHandler = middlewareHandler.wrapMethod('transportMessageHandler', messageHandler, transport)
545
+ messageHandler = middlewareHandler.wrapMethod('transportMessageHandler', messageHandler, transport);
546
546
 
547
547
  adapter.init(runtime, transport)
548
548
  .then(() => {
549
- adapter.bus.on('$adapter.connected', onConnect)
550
- adapter.bus.on('$adapter.disconnected', onDisconnect)
551
- adapter.bus.on('$adapter.message', messageHandler)
552
- })
549
+ adapter.bus.on('$adapter.connected', onConnect);
550
+ adapter.bus.on('$adapter.disconnected', onDisconnect);
551
+ adapter.bus.on('$adapter.message', messageHandler);
552
+ });
553
553
 
554
- transport.send = middlewareHandler.wrapMethod('transportSend', transport.send, transport)
554
+ transport.send = middlewareHandler.wrapMethod('transportSend', transport.send, transport);
555
555
 
556
- return transport
556
+ return transport;
557
557
 
558
558
  function makeSubscriptions () {
559
559
  return Promise.all([
@@ -572,80 +572,80 @@ exports.createTransport = (runtime, adapter) => {
572
572
  adapter.subscribe(MessageTypes.MESSAGE_RESPONSE_STREAM_RESUME, nodeId),
573
573
  adapter.subscribe(MessageTypes.MESSAGE_REQUEST_STREAM_BACKPRESSURE, nodeId),
574
574
  adapter.subscribe(MessageTypes.MESSAGE_REQUEST_STREAM_RESUME, nodeId)
575
- ])
575
+ ]);
576
576
  }
577
577
 
578
578
  function startHeartbeatTimer () {
579
- heartbeatTimer = setInterval(() => sendHeartbeat(), runtime.options.transport.heartbeatInterval)
580
- heartbeatTimer.unref()
579
+ heartbeatTimer = setInterval(() => sendHeartbeat(), runtime.options.transport.heartbeatInterval);
580
+ heartbeatTimer.unref();
581
581
  }
582
582
 
583
583
  function startRemoteNodeCheckTimer () {
584
- checkNodesTimer = setInterval(() => checkRemoteNodes(), runtime.options.transport.heartbeatTimeout)
585
- checkNodesTimer.unref()
584
+ checkNodesTimer = setInterval(() => checkRemoteNodes(), runtime.options.transport.heartbeatTimeout);
585
+ checkNodesTimer.unref();
586
586
  }
587
587
 
588
588
  function startOfflineNodeCheckTimer () {
589
- checkOfflineNodesTimer = setInterval(() => checkOfflineNodes(), runtime.options.transport.offlineNodeCheckInterval)
590
- checkOfflineNodesTimer.unref()
589
+ checkOfflineNodesTimer = setInterval(() => checkOfflineNodes(), runtime.options.transport.offlineNodeCheckInterval);
590
+ checkOfflineNodesTimer.unref();
591
591
  }
592
592
 
593
593
  function startUpdateLocalNodeTimer () {
594
594
  updateLocalNodeTimer = setInterval(() => {
595
- const node = runtime.registry.nodeCollection.localNode
596
- node.updateLocalInfo(true)
597
- }, runtime.options.transport.localNodeUpdateInterval)
595
+ const node = runtime.registry.nodeCollection.localNode;
596
+ node.updateLocalInfo(true);
597
+ }, runtime.options.transport.localNodeUpdateInterval);
598
598
 
599
- updateLocalNodeTimer.unref()
599
+ updateLocalNodeTimer.unref();
600
600
  }
601
601
 
602
602
  function stopTimers () {
603
- clearInterval(heartbeatTimer)
604
- clearInterval(checkNodesTimer)
605
- clearInterval(checkOfflineNodesTimer)
606
- clearInterval(updateLocalNodeTimer)
603
+ clearInterval(heartbeatTimer);
604
+ clearInterval(checkNodesTimer);
605
+ clearInterval(checkOfflineNodesTimer);
606
+ clearInterval(updateLocalNodeTimer);
607
607
  }
608
608
 
609
609
  function sendHeartbeat () {
610
- const node = runtime.registry.nodeCollection.localNode
611
- node.updateLocalInfo()
610
+ const node = runtime.registry.nodeCollection.localNode;
611
+ node.updateLocalInfo();
612
612
 
613
- transport.log.verbose(`Send heartbeat from ${node.id}`)
613
+ transport.log.verbose(`Send heartbeat from ${node.id}`);
614
614
 
615
615
  const payload = {
616
616
  cpu: node.cpu,
617
617
  cpuSequence: node.cpuSequence,
618
618
  sequence: node.sequence
619
- }
619
+ };
620
620
 
621
- const message = createMessage(MessageTypes.MESSAGE_HEARTBEAT, null, payload)
622
- transport.send(message)
621
+ const message = createMessage(MessageTypes.MESSAGE_HEARTBEAT, null, payload);
622
+ transport.send(message);
623
623
  }
624
624
 
625
625
  function checkRemoteNodes () {
626
- const now = Date.now()
626
+ const now = Date.now();
627
627
  runtime.registry.nodeCollection.list({ withServices: true }).forEach(node => {
628
628
  if (node.isLocal || !node.isAvailable) {
629
- return
629
+ return;
630
630
  }
631
631
 
632
632
  if (now - (node.lastHeartbeatTime || 0) > runtime.options.transport.heartbeatTimeout) {
633
- runtime.registry.nodeDisconnected(node.id, true)
633
+ runtime.registry.nodeDisconnected(node.id, true);
634
634
  }
635
- })
635
+ });
636
636
  }
637
637
 
638
638
  // Removes the node after a given time from the registry.
639
639
  function checkOfflineNodes () {
640
- const now = Date.now()
640
+ const now = Date.now();
641
641
  runtime.registry.nodeCollection.list({}).forEach(node => {
642
642
  if (node.isLocal || node.isAvailable) {
643
- return
643
+ return;
644
644
  }
645
645
 
646
646
  if ((now - node.offlineTime) > runtime.options.transport.maxOfflineTime) {
647
- runtime.registry.removeNode(node.id)
647
+ runtime.registry.removeNode(node.id);
648
648
  }
649
- })
649
+ });
650
650
  }
651
- }
651
+ };