@mojaloop/event-stream-processor 12.0.1

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 (52) hide show
  1. package/.circleci/config.yml +12 -0
  2. package/.editorconfig +18 -0
  3. package/.grype.yaml +37 -0
  4. package/.ncurc.yaml +7 -0
  5. package/.nvmrc +1 -0
  6. package/.nycrc.yml +19 -0
  7. package/CHANGELOG.md +89 -0
  8. package/CODEOWNERS +38 -0
  9. package/Dockerfile +49 -0
  10. package/LICENSE.md +9 -0
  11. package/README.md +178 -0
  12. package/audit-ci.jsonc +10 -0
  13. package/audit-resolve.json +21 -0
  14. package/config/default.json +133 -0
  15. package/config/policy-rollover-mojaloop.json +24 -0
  16. package/config/template-mojaloop.json +222 -0
  17. package/docker/configs/apm-server.docker.yml +1015 -0
  18. package/docker/docker-compose.yaml +170 -0
  19. package/docker/kafka-consume.sh +1 -0
  20. package/docker/kafka-produces-multi.sh +1 -0
  21. package/docker/kafka-produces-single.sh +1 -0
  22. package/docker/msg-example.single +1 -0
  23. package/docker/msg-examples.multi +8 -0
  24. package/package.json +124 -0
  25. package/sbom-v12.0.0-snapshot.25.csv +1233 -0
  26. package/src/index.js +44 -0
  27. package/src/lib/config.js +10 -0
  28. package/src/lib/efk/index.js +104 -0
  29. package/src/lib/healthCheck/subServiceHealth.js +85 -0
  30. package/src/lib/tracer/index.js +21 -0
  31. package/src/observables/apmTracerObservable.js +303 -0
  32. package/src/observables/elastic-logger.js +80 -0
  33. package/src/observables/fluentd-logger.js +20 -0
  34. package/src/observables/index.js +35 -0
  35. package/src/observables/testing_agents.-js +33 -0
  36. package/src/setup.js +128 -0
  37. package/src/templates/register.js +72 -0
  38. package/test/sample-data/messages.json +4327 -0
  39. package/test/unit/index.test.js +88 -0
  40. package/test/unit/lib/config.test.js +77 -0
  41. package/test/unit/lib/efk/index.test.js +187 -0
  42. package/test/unit/lib/healthCheck/subServiceHealth.test.js +119 -0
  43. package/test/unit/lib/tracer/index.test.js +59 -0
  44. package/test/unit/observables/apmTracerObservable.test.js +788 -0
  45. package/test/unit/observables/elastic-logger.test.js +187 -0
  46. package/test/unit/observables/fluentd-logger.test.js +101 -0
  47. package/test/unit/observables/index.test.js +47 -0
  48. package/test/unit/templates/register.test.js +66 -0
  49. package/test/util/scripts/docker-efk/docker-compose.yml +74 -0
  50. package/test/util/scripts/docker-efk/fluentd/Dockerfile +2 -0
  51. package/test/util/scripts/docker-efk/fluentd/conf/fluent.conf +18 -0
  52. package/test/util/scripts/docker-efk/misc/clients-td-agent.conf +14 -0
package/src/index.js ADDED
@@ -0,0 +1,44 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+ * Valentin Genev <valentin.genev@modusbox.com>
25
+ * Deon Botha <deon.botha@modusbox.com>
26
+ --------------
27
+ ******/
28
+
29
+ 'use strict'
30
+ const setup = require('./setup').setup
31
+ const Logger = require('@mojaloop/central-services-logger')
32
+
33
+ try {
34
+ // Lets have a catch-all for any unhandled Promises
35
+ process.on('unhandledRejection', (reason, promise) => {
36
+ console.error('unhandledRejection - promise', promise)
37
+ Logger.error(`Event Stream Processor error ${reason}`)
38
+ })
39
+
40
+ // Setup the application
41
+ setup()
42
+ } catch (err) {
43
+ Logger.error(`Event Stream Processor error ${err.stack}`)
44
+ }
@@ -0,0 +1,10 @@
1
+ const RC = require('parse-strings-in-object')(require('rc')('EVENTSP', require('../../config/default.json')))
2
+
3
+ module.exports = {
4
+ PORT: RC.PORT,
5
+ EFK_CLIENT: RC.EFK_CLIENT,
6
+ APM: RC.APM,
7
+ KAFKA_CONFIG: RC.KAFKA,
8
+ CACHE: RC.CACHE,
9
+ SPAN: RC.SPAN
10
+ }
@@ -0,0 +1,104 @@
1
+ /*****
2
+ * @file This registers all handlers for the central-ledger API
3
+ License
4
+ --------------
5
+ Copyright © 2020-2025 Mojaloop Foundation
6
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
11
+
12
+ Contributors
13
+ --------------
14
+ This is the official list of the Mojaloop project contributors for this file.
15
+ Names of the original copyright holders (individuals or organizations)
16
+ should be listed with a '*' in the first column. People who have
17
+ contributed from an organization can be listed under the organization
18
+ that actually holds the copyright for their contributions (see the
19
+ Mojaloop Foundation for an example). Those individuals should have
20
+ their names indented and be marked with a '-'. Email address can be added
21
+ optionally within square brackets <email>.
22
+
23
+ * Mojaloop Foundation
24
+ - Name Surname <name.surname@mojaloop.io>
25
+
26
+ * ModusBox
27
+ - Valentin Genev <valentin.genev@modusbox.com>
28
+ - Miguel de Barros <miguel.debarros@modusbox.com>
29
+
30
+ --------------
31
+ ******/
32
+
33
+ 'use strict'
34
+
35
+ const flogger = require('fluent-logger')
36
+ const Config = require('../../lib/config')
37
+ const Logger = require('@mojaloop/central-services-logger')
38
+ const Mustache = require('mustache')
39
+ const Moment = require('moment')
40
+
41
+ const initLogger = async (prefix, options) => {
42
+ flogger.configure(prefix, options)
43
+
44
+ flogger.on('connect', () => {
45
+ Promise.resolve({ status: 'succes' })
46
+ })
47
+
48
+ flogger.on('error', (error) => {
49
+ Promise.reject(error)
50
+ })
51
+ }
52
+
53
+ const elasticsearch = require('elasticsearch')
54
+
55
+ const ElasticSearchClient = (() => {
56
+ let instance
57
+ let index
58
+ let currentDate
59
+ const createInstance = async () => {
60
+ try {
61
+ const client = new elasticsearch.Client({
62
+ host: Config.EFK_CLIENT.host,
63
+ log: Config.EFK_CLIENT.log
64
+ })
65
+ const resultPing = await client.ping({
66
+ // ping usually has a 3000ms timeout
67
+ requestTimeout: 1000
68
+ })
69
+ Logger.info(`elasticsearch client connection result - ${resultPing}`)
70
+ return client
71
+ } catch (e) {
72
+ Logger.error(e.stack)
73
+ throw e
74
+ }
75
+ }
76
+
77
+ return {
78
+ getIndex: () => {
79
+ const nowDate = Moment()
80
+ if (!index || nowDate.diff(currentDate, 'days') > 0) {
81
+ const indexConfig = Config.EFK_CLIENT.index
82
+ currentDate = nowDate
83
+ const dateString = currentDate.format('YYYY.MM.DD')
84
+ index = Mustache.render(indexConfig.template, {
85
+ index: indexConfig.name,
86
+ date: dateString
87
+ })
88
+ }
89
+ return index
90
+ },
91
+ getInstance: async () => {
92
+ if (!instance) {
93
+ instance = await createInstance()
94
+ }
95
+ return instance
96
+ }
97
+ }
98
+ })()
99
+
100
+ module.exports = {
101
+ initLogger,
102
+ logger: flogger,
103
+ ElasticSearchClient
104
+ }
@@ -0,0 +1,85 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+
25
+ * Lewis Daly <lewis@vesselstech.com>
26
+ --------------
27
+ ******/
28
+ 'use strict'
29
+
30
+ const { statusEnum, serviceName } = require('@mojaloop/central-services-shared').HealthCheck.HealthCheckEnums
31
+ const Logger = require('@mojaloop/central-services-logger')
32
+ const Util = require('@mojaloop/central-services-stream').Util
33
+ const Consumer = Util.Consumer
34
+
35
+ /**
36
+ * @function getSubServiceHealthBroker
37
+ *
38
+ * @description
39
+ * Gets the health for the broker, by checking that each consumer is healthy.
40
+ * Uses the consumer's isHealthy() method from central-services-stream which performs:
41
+ * - isConnected() - basic connection status
42
+ * - isAssigned() - consumer has partition assignments
43
+ * - isPollHealthy() - last poll was within healthCheckPollInterval
44
+ * - getMetadataSync() - all subscribed topics exist in broker metadata
45
+ *
46
+ * @returns Promise<SubServiceHealth> The SubService health object for the broker
47
+ */
48
+ const getSubServiceHealthBroker = async () => {
49
+ let status = statusEnum.OK
50
+
51
+ try {
52
+ const consumerTopics = Consumer.getListOfTopics()
53
+ const results = await Promise.all(
54
+ consumerTopics.map(async (topic) => {
55
+ try {
56
+ const consumer = Consumer.getConsumer(topic)
57
+ const isHealthy = await consumer.isHealthy()
58
+ if (!isHealthy) {
59
+ Logger.isWarnEnabled && Logger.warn(`Consumer is not healthy for topic ${topic}`)
60
+ }
61
+ return isHealthy
62
+ } catch (err) {
63
+ Logger.isWarnEnabled && Logger.warn(`isHealthy check failed for topic ${topic}: ${err.message}`)
64
+ return false
65
+ }
66
+ })
67
+ )
68
+
69
+ if (results.some(healthy => !healthy)) {
70
+ status = statusEnum.DOWN
71
+ }
72
+ } catch (err) {
73
+ Logger.isWarnEnabled && Logger.warn(`getSubServiceHealthBroker failed with error ${err.message}.`)
74
+ status = statusEnum.DOWN
75
+ }
76
+
77
+ return {
78
+ name: serviceName.broker,
79
+ status
80
+ }
81
+ }
82
+
83
+ module.exports = {
84
+ getSubServiceHealthBroker
85
+ }
@@ -0,0 +1,21 @@
1
+ const Agent = require('@mojaloop/elastic-apm-node')
2
+ const Tracer = require('@mojaloop/elastic-apm-node-opentracing')
3
+ const Config = require('../config')
4
+
5
+ const agent = (function () {
6
+ const self = Agent.start(Config.APM)
7
+ this.agent = self
8
+ self.captureError()
9
+ return this
10
+ })()
11
+
12
+ const tracer = (function () {
13
+ const self = new Tracer(agent.agent)
14
+ this.tracer = self
15
+ return this
16
+ })()
17
+
18
+ module.exports = {
19
+ agent: agent.agent,
20
+ tracer: tracer.tracer
21
+ }
@@ -0,0 +1,303 @@
1
+ const Rx = require('rxjs')
2
+ const Logger = require('@mojaloop/central-services-logger')
3
+ const crypto = require('crypto')
4
+ const Config = require('../lib/config')
5
+ const Catbox = require('@hapi/catbox')
6
+ const CatboxMemory = require('@hapi/catbox-memory')
7
+ const TraceParent = require('traceparent')
8
+ const deserializeError = require('deserialize-error')
9
+ const { Tracer, EventStatusType } = require('@mojaloop/event-sdk')
10
+ const { merge } = require('lodash')
11
+ const { tracer } = require('../lib/tracer')
12
+
13
+ const clientOptions = Config.CACHE.CATBOX_MEMORY
14
+ let client
15
+ const schedulers = {}
16
+
17
+ const initializeCache = async () => {
18
+ client = new Catbox.Client(CatboxMemory, clientOptions)
19
+ await client.start()
20
+ return true
21
+ }
22
+
23
+ const getKey = (traceId, tags) => {
24
+ const incomingVendor = (!!tags && !!tags.tracestate) ? (tags.tracestate).split(',')[0].split('=')[0] : null
25
+ return {
26
+ segment: `${Config.CACHE.segment}`,
27
+ id: incomingVendor ? `${traceId}_${incomingVendor}` : traceId
28
+ }
29
+ }
30
+
31
+ const updateTraceToCache = async (key, trace) => {
32
+ try {
33
+ const currentTrace = await client.get(key)
34
+ if (currentTrace && (currentTrace.ttl > (Config.CACHE.ttl - Config.CACHE.expectSpanTimeout) && schedulers[key.id] && schedulers[key.id].id)) schedulers[key.id].unsubscribe()
35
+ await client.set(key, trace, Config.CACHE.ttl)
36
+ schedulers[key.id] = Rx.asyncScheduler.schedule(finishStaleTrace, Config.CACHE.expectSpanTimeout, key.id)
37
+ } catch (e) {
38
+ Logger.error(e.stack)
39
+ }
40
+ }
41
+
42
+ const extractContextObservable = ({ message }) => {
43
+ return Rx.Observable.create(observable => {
44
+ try {
45
+ Logger.debug(`Received event message :: Payload: \n${JSON.stringify(message.value, null, 2)}`)
46
+ Logger.info(`Received Event :: transactionId: ${message.value.metadata.trace.tags.transactionId} :: type: ${message.value.metadata.trace.tags.transactionType} :: action: ${message.value.metadata.trace.tags.transactionAction} *** Span :: traceId: ${message.value.metadata.trace.traceId} :: spanId: ${message.value.metadata.trace.spanId} :: tracestate: ${message.value.metadata.trace.tags.tracestate}`)
47
+ const spanContext = Tracer.extractContextFromMessage(message.value)
48
+ observable.next({ spanContext, state: message.value.metadata.event.state, content: message.value.content })
49
+ } catch (e) {
50
+ Logger.error(e.stack)
51
+ observable.error(e)
52
+ }
53
+ })
54
+ }
55
+
56
+ const cacheSpanContextObservable = ({ spanContext, state, content }) => {
57
+ return Rx.Observable.create(async observable => {
58
+ const { traceId, parentSpanId, tags, service, spanId } = spanContext
59
+ const key = getKey(traceId, tags)
60
+ const isStartSpan = () => {
61
+ const { transactionType, transactionAction } = tags
62
+ if (Config.SPAN.START_CRITERIA[transactionType]) {
63
+ for (const criteria of Config.SPAN.START_CRITERIA[transactionType]) {
64
+ if (criteria[transactionAction] && (criteria[transactionAction].service === service)) {
65
+ return true
66
+ }
67
+ }
68
+ }
69
+ return false
70
+ }
71
+
72
+ try {
73
+ let cachedTrace = await client.get(key)
74
+ let cachedTraceItem
75
+ if ((!isStartSpan() && !parentSpanId) || (!!parentSpanId && !cachedTrace)) {
76
+ sendSpanToApm({ spanContext, state, content })
77
+ return observable.complete()
78
+ } else {
79
+ if (!cachedTrace) cachedTrace = { item: { spans: {}, masterSpan: null, lastSpan: null } }
80
+ cachedTraceItem = cachedTrace.item
81
+ if (!parentSpanId) {
82
+ const newSpanId = crypto.randomBytes(8).toString('hex')
83
+ const newChildContext = merge({ parentSpanId: newSpanId }, { ...spanContext })
84
+ const newMasterSpanContext = merge({ tags: { ...tags, masterSpan: newSpanId } }, { ...spanContext }, { spanId: newSpanId, service: `master-${tags.transactionType}` })
85
+ cachedTraceItem.spans[newSpanId] = { spanContext: newMasterSpanContext, state, content }
86
+ cachedTraceItem.masterSpan = newMasterSpanContext
87
+ spanContext = newChildContext
88
+ }
89
+ cachedTraceItem.spans[spanId] = { spanContext, state, content }
90
+ await updateTraceToCache(key, cachedTraceItem, traceId)
91
+ observable.next({ traceId, tags, latestSpanId: spanId })
92
+ }
93
+ // await client.set(key, cachedTrace, Config.CACHE.ttl)
94
+ } catch (e) {
95
+ Logger.error(e.stack)
96
+ observable.error(e)
97
+ }
98
+ })
99
+ }
100
+
101
+ const findLastSpanObservable = ({ traceId, tags, latestSpanId }) => {
102
+ return Rx.Observable.create(async observable => {
103
+ const key = getKey(traceId, tags)
104
+
105
+ const cachedTrace = (await client.get(key)).item
106
+ if (!cachedTrace) {
107
+ return observable.complete()
108
+ }
109
+ const sortedSpans = Array.from(Object.entries(cachedTrace.spans)).sort((a, b) => a[1].spanContext.startTimestamp > b[1].spanContext.startTimestamp ? -1 : a[1].spanContext.startTimestamp < b[1].spanContext.startTimestamp ? 1 : 0)
110
+ for (const spanKey of sortedSpans) {
111
+ const { spanContext, state, content } = cachedTrace.spans[spanKey[0]]
112
+ const { parentSpanId, tags, service, spanId } = spanContext
113
+ const { status, code } = state
114
+ const parentSpan = cachedTrace.spans[parentSpanId]
115
+ if (!parentSpan) continue
116
+ const parentSpanTags = parentSpan ? parentSpan.spanContext.tags : null
117
+ const errorTags = ('errorCode' in parentSpanTags)
118
+ ? { errorCode: parentSpanTags.errorCode }
119
+ : ('code' in parentSpan.state && parentSpan.state.status === EventStatusType.failed)
120
+ ? { errorCode: parentSpan.state.code }
121
+ : null
122
+ const masterTags = ('masterSpan' in parentSpanTags) ? { masterSpan: parentSpanTags.masterSpan } : null
123
+ const tagsToApply = merge({ ...errorTags }, { tags: { ...tags, ...masterTags } })
124
+ cachedTrace.spans[spanId] = { spanContext: merge(tagsToApply, { ...spanContext }), state, content }
125
+
126
+ const isLastSpan = () => {
127
+ const { transactionAction, transactionType } = tags
128
+ const isError = (!!(code) && status === EventStatusType.failed) || !!errorTags
129
+ if (Config.SPAN.END_CRITERIA[transactionType]) {
130
+ for (const criteria of Config.SPAN.END_CRITERIA[transactionType]) {
131
+ if (criteria[transactionAction]) {
132
+ if (criteria[transactionAction].service === service) {
133
+ if (('isError' in criteria[transactionAction]) && criteria[transactionAction].isError && isError) {
134
+ return true
135
+ } else if (!('isError' in criteria[transactionAction])) {
136
+ return true
137
+ }
138
+ }
139
+ }
140
+ }
141
+ }
142
+ return false
143
+ }
144
+
145
+ if (isLastSpan() || Config.SPAN.END_CRITERIA.exceptionList.includes(service)) { // TODO remove exceptionList when all traces have right tags
146
+ cachedTrace.lastSpan = spanContext
147
+ await updateTraceToCache(key, cachedTrace, traceId)
148
+ return observable.next({ traceId, tags })
149
+ }
150
+ }
151
+ await updateTraceToCache(key, cachedTrace, traceId)
152
+ // TODO: Investigate the reason/cause for this error being thrown when the next line is uncommented: "TypeError: teardown.unsubscribe is not a function" to be thrown.
153
+ // observable.complete()
154
+ })
155
+ }
156
+
157
+ const recreateTraceObservable = ({ traceId, tags }) => {
158
+ const key = getKey(traceId, tags)
159
+ return Rx.Observable.create(async observable => {
160
+ try {
161
+ const cachedTrace = (await client.get(key)).item
162
+ if (cachedTrace.lastSpan && cachedTrace.masterSpan) {
163
+ const sortedSpans = Array.from(Object.values(cachedTrace.spans)).sort((a, b) => a.spanContext.finishTimestamp > b.spanContext.finishTimestamp ? 1 : a.spanContext.finishTimestamp < b.spanContext.finishTimestamp ? -1 : 0)
164
+ let previousSpan
165
+ let currentSpan
166
+ const parentFound = []
167
+ for (const [index, span] of sortedSpans.entries()) {
168
+ currentSpan = span
169
+ if (currentSpan.spanContext.service === 'master-transfer' && !currentSpan.spanContext.parentSpanId) {
170
+ sortedSpans[index].spanContext.finishTimestamp = sortedSpans[sortedSpans.length - 1].spanContext.finishTimestamp
171
+ sortedSpans.unshift(currentSpan)
172
+ sortedSpans.splice(index, 1)
173
+ previousSpan = span
174
+ } else {
175
+ if (currentSpan.parentSpanId === previousSpan.spanId) {
176
+ parentFound.push(previousSpan.spanContext.spanId)
177
+ previousSpan = currentSpan
178
+ } else if (!parentFound.includes(currentSpan.spanContext.spanId)) {
179
+ break
180
+ } else {
181
+ previousSpan = currentSpan
182
+ }
183
+ }
184
+ }
185
+ if (parentFound.length > 0) {
186
+ return observable.next(sortedSpans)
187
+ } else {
188
+ return observable.complete()
189
+ }
190
+ }
191
+ } catch (e) {
192
+ Logger.error(e.stack)
193
+ observable.error(e)
194
+ }
195
+ })
196
+ }
197
+
198
+ const sendSpanToApm = currentSpan => {
199
+ const { service, traceId, parentSpanId, spanId, startTimestamp, finishTimestamp, flags, tags = {}, version = 0 } = currentSpan.spanContext
200
+ const { status, code, description } = currentSpan.state
201
+ const { content } = currentSpan
202
+ const versionBuffer = Buffer.alloc(1).fill(version)
203
+ const flagsBuffer = Buffer.alloc(1).fill(flags | 0x01)
204
+ const traceIdBuffer = Buffer.from(traceId, 'hex')
205
+ const spanIdBuffer = Buffer.from(spanId, 'hex')
206
+ const parentSpanIdBuffer = parentSpanId && Buffer.from(parentSpanId, 'hex')
207
+ Logger.info(`Send span to APM :: traceId: ${traceId} :: spanId: ${spanId} :: parentSpanId: ${parentSpanId} :: flags: ${flagsBuffer.toString('hex')} *** Event :: type: ${tags.transactionType} :: action: ${tags.transactionAction}`)
208
+ const context =
209
+ parentSpanIdBuffer
210
+ ? new TraceParent(Buffer.concat([versionBuffer, traceIdBuffer, spanIdBuffer, flagsBuffer, parentSpanIdBuffer]))
211
+ : new TraceParent(Buffer.concat([versionBuffer, traceIdBuffer, spanIdBuffer, flagsBuffer]))
212
+ const span = tracer.startSpan(`${service}`, { startTime: Date.parse(startTimestamp), tags }, context)
213
+ if (status === EventStatusType.failed) {
214
+ span.setTag('error', true)
215
+ !!code && span.setTag('errorCode', code)
216
+ !!description && span.setTag('errorDescription', `error code: ${code} :: description: ${description}`)
217
+ if (!content.error) {
218
+ const passedError = content.payload ? new Error(content.payload) : Object.assign(new Error(description), content)
219
+ span.log({
220
+ event: 'error',
221
+ 'error.object': passedError
222
+ })
223
+ } else {
224
+ span.log({
225
+ event: 'error',
226
+ 'error.object': deserializeError(content.error)
227
+ })
228
+ }
229
+ }
230
+ span.finish(Date.parse(finishTimestamp))
231
+ return currentSpan
232
+ }
233
+
234
+ const sendTraceToApmObservable = (trace) => {
235
+ const { traceId, tags } = trace[0].spanContext
236
+ const key = getKey(traceId, tags)
237
+ return Rx.Observable.create(async observable => {
238
+ try {
239
+ for (const currentSpan of trace) {
240
+ sendSpanToApm(currentSpan)
241
+ }
242
+ await client.drop(key)
243
+ if (schedulers[traceId]) {
244
+ schedulers[traceId].unsubscribe()
245
+ delete schedulers[traceId]
246
+ }
247
+ observable.next(traceId)
248
+ } catch (e) {
249
+ Logger.error(e.stack)
250
+ observable.error(e)
251
+ }
252
+ })
253
+ }
254
+
255
+ const finishStaleTrace = async (keyId) => {
256
+ const key = {
257
+ segment: `${Config.CACHE.segment}`,
258
+ id: keyId
259
+ }
260
+ try {
261
+ const cachedTraceElement = await client.get(key)
262
+ if (!cachedTraceElement) return
263
+ const cachedTrace = cachedTraceElement.item
264
+ const sortedSpans = Array.from(Object.values(cachedTrace.spans)).sort((a, b) => b.spanContext.startTimestamp > a.spanContext.startTimestamp ? -1 : b.spanContext.startTimestamp < a.spanContext.startTimestamp ? 1 : 0)
265
+ const resultTrace = []
266
+ cachedTrace.lastSpan = sortedSpans[sortedSpans.length - 1].spanContext
267
+ for (const spanId in sortedSpans) {
268
+ const span = sortedSpans[spanId]
269
+ if (span.spanContext.service === `master-${span.spanContext.tags.transactionType}`) {
270
+ span.spanContext.finishTimestamp = sortedSpans[sortedSpans.length - 1].spanContext.finishTimestamp
271
+ span.spanContext.tags.staleTrace = true
272
+ resultTrace.unshift(span)
273
+ continue
274
+ } else if (cachedTrace.lastSpan && span.spanContext.spanId === cachedTrace.lastSpan.spanId) {
275
+ resultTrace.push(span)
276
+ break
277
+ } else if (sortedSpans[Number(spanId) + 1].spanContext.parentSpanId === span.spanContext.spanId) {
278
+ resultTrace.push(span)
279
+ continue
280
+ } else {
281
+ span.spanContext.tags.missingParent = true
282
+ sortedSpans[Number(spanId) + 1].spanContext.parentSpanId = span.spanContext.spanId
283
+ resultTrace.push(span)
284
+ }
285
+ }
286
+ for (const span of resultTrace) {
287
+ sendSpanToApm(span)
288
+ }
289
+ delete schedulers[keyId]
290
+ await client.drop(key)
291
+ } catch (e) {
292
+ Logger.error(e.stack)
293
+ }
294
+ }
295
+
296
+ module.exports = {
297
+ extractContextObservable,
298
+ initializeCache,
299
+ findLastSpanObservable,
300
+ cacheSpanContextObservable,
301
+ recreateTraceObservable,
302
+ sendTraceToApmObservable
303
+ }
@@ -0,0 +1,80 @@
1
+ /*****
2
+ * @file This registers all handlers for the central-ledger API
3
+ License
4
+ --------------
5
+ Copyright © 2020-2025 Mojaloop Foundation
6
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
11
+
12
+ Contributors
13
+ --------------
14
+ This is the official list of the Mojaloop project contributors for this file.
15
+ Names of the original copyright holders (individuals or organizations)
16
+ should be listed with a '*' in the first column. People who have
17
+ contributed from an organization can be listed under the organization
18
+ that actually holds the copyright for their contributions (see the
19
+ Mojaloop Foundation for an example). Those individuals should have
20
+ their names indented and be marked with a '-'. Email address can be added
21
+ optionally within square brackets <email>.
22
+
23
+ * Mojaloop Foundation
24
+ - Name Surname <name.surname@mojaloop.io>
25
+
26
+ * ModusBox
27
+ - Valentin Genev <valentin.genev@modusbox.com>
28
+ - Miguel de Barros <miguel.debarros@modusbox.com>
29
+
30
+ --------------
31
+ ******/
32
+
33
+ const addElasticsearchMetaData = (value) => {
34
+ if (value.metadata && value.metadata.event && value.metadata.trace) {
35
+ const elasticsearchMetaData = {
36
+ processor: {
37
+ name: 'transaction',
38
+ event: 'transaction'
39
+ },
40
+ trace: {
41
+ id: value.metadata.trace.traceId
42
+ },
43
+ '@timestamp': value.metadata.event.createdAt,
44
+ transaction: {
45
+ result: (value.metadata.event.state.status === 'success') ? 'success' : 'error',
46
+ name: value.metadata.trace.service,
47
+ id: value.metadata.trace.spanId,
48
+ sampled: !value.metadata.trace.sampled
49
+ }
50
+ }
51
+ return { ...value, ...elasticsearchMetaData }
52
+ } else {
53
+ return value
54
+ }
55
+ }
56
+
57
+ const Rx = require('rxjs')
58
+ const { ElasticSearchClient } = require('../lib/efk')
59
+ const Logger = require('@mojaloop/central-services-logger')
60
+
61
+ const elasticsearchClientObservable = ({ message }) => {
62
+ return Rx.Observable.create(async observable => {
63
+ try {
64
+ const client = await ElasticSearchClient.getInstance()
65
+ await client.index({
66
+ index: ElasticSearchClient.getIndex(),
67
+ body: addElasticsearchMetaData(message.value)
68
+ })
69
+ // TODO: Investigate the reason/cause for this error being thrown when the next line is uncommented: "TypeError: teardown.unsubscribe is not a function" to be thrown.
70
+ // observable.complete()
71
+ } catch (e) {
72
+ observable.error(e)
73
+ Logger.error(e.stack)
74
+ }
75
+ })
76
+ }
77
+
78
+ module.exports = {
79
+ elasticsearchClientObservable
80
+ }
@@ -0,0 +1,20 @@
1
+ const Rx = require('rxjs')
2
+ const logger = require('../lib/efk').flogger
3
+ const Config = require('../lib/config')
4
+
5
+ const FluentdLoggerObservable = ({ message }) => {
6
+ return Rx.Observable.create(observable => {
7
+ try {
8
+ logger.emit(Config.efk.namespace, message.value, (err) => {
9
+ if (err) { observable.error(err) }
10
+ })
11
+ observable.complete()
12
+ } catch (e) {
13
+ observable.error(e)
14
+ }
15
+ })
16
+ }
17
+
18
+ module.exports = {
19
+ FluentdLoggerObservable
20
+ }