-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aedes-instrumentation.spec.ts
299 lines (275 loc) · 9.17 KB
/
aedes-instrumentation.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { context, propagation } from '@opentelemetry/api'
import { W3CTraceContextPropagator } from '@opentelemetry/core'
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import {
InMemoryMetricExporter,
MeterProvider,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics'
import {
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base'
import { SemanticAttributes } from '@opentelemetry/semantic-conventions'
import type Aedes from 'aedes'
import type { AedesPublishPacket } from 'aedes'
import type * as MqttClient from 'mqtt'
import type { IPublishPacket } from 'mqtt-packet'
import * as semver from 'semver'
import assert from 'node:assert/strict'
import { createServer } from 'node:net'
import { afterEach, beforeEach, describe, it, mock } from 'node:test'
import { promisify } from 'node:util'
import {
AedesAttributes,
AedesInstrumentation,
CONNECTION_ATTRIBUTES,
MqttPacketInstrumentation,
} from '../src'
import { AedesClient, HandleConnect } from '../src/internal-types'
import { NO_RESOLVE, waitForEvent } from './helpers'
// polyfill for JS new feature
if (semver.lt(process.versions.node, '20.0.0')) {
Object.defineProperty(Symbol, 'dispose', {
configurable: true,
value: Symbol('Symbol.dispose'),
})
Object.defineProperty(Symbol, 'asyncDispose', {
configurable: true,
value: Symbol('Symbol.asyncDispose'),
})
}
let Client: typeof MqttClient
let Broker: typeof Aedes
let ConnectHandler: HandleConnect
const getBroker = async () => {
const broker = new Broker()
const tcpServer = createServer(broker.handle.bind(broker))
await new Promise((resolve) => {
broker.once('closed', () => {
tcpServer.close()
})
tcpServer.listen(1883, () => {
return resolve(broker)
})
})
return {
broker,
tcpServer,
[Symbol.asyncDispose]: async () => {
await new Promise((resolve) => {
broker.close(() => {
tcpServer.close(() => {
resolve(null)
})
})
})
},
}
}
const getMqttClient = async (wait?: boolean) => {
const client = wait
? await Client.connectAsync('mqtt://localhost:1883')
: Client.connect('mqtt://localhost:1883')
return {
client,
[Symbol.asyncDispose]: async () => {
await client.endAsync()
},
}
}
describe('Aedes', () => {
const mqttPacketInstrumentation = new MqttPacketInstrumentation()
const instrumentation = new AedesInstrumentation()
const tracerProvider = new NodeTracerProvider()
const memorySpanExporter = new InMemorySpanExporter()
const spanProcessor = new SimpleSpanProcessor(memorySpanExporter)
tracerProvider.addSpanProcessor(spanProcessor)
const memoryMetricExporter = new InMemoryMetricExporter(0)
const metricProvider = new MeterProvider()
metricProvider.addMetricReader(
new PeriodicExportingMetricReader({
exporter: memoryMetricExporter,
})
)
const contextManager = new AsyncHooksContextManager()
beforeEach(() => {
contextManager.enable()
context.setGlobalContextManager(contextManager)
instrumentation.setTracerProvider(tracerProvider)
instrumentation.setMeterProvider(metricProvider)
instrumentation.enable()
mqttPacketInstrumentation.enable()
propagation.setGlobalPropagator(new W3CTraceContextPropagator())
/* eslint-disable @typescript-eslint/no-var-requires */
Client = require('mqtt')
Broker = require('aedes')
ConnectHandler = require('aedes/lib/handlers/connect')
/* eslint-enable @typescript-eslint/no-var-requires */
})
afterEach(() => {
contextManager.disable()
contextManager.enable()
memorySpanExporter.reset()
memoryMetricExporter.reset()
mqttPacketInstrumentation.disable()
instrumentation.disable()
})
/*
* this test is flaky.
* `handleConnect` seems to be correctly unpatched by the instrumentation disable method
* but still the `mqtt.connect` span is created when a client connects to the broker
*
*/
it('should not generate any spans when disabled', async () => {
mqttPacketInstrumentation.disable()
instrumentation.disable()
assert.strictEqual(instrumentation.getConfig().enabled, false)
assert.strictEqual(
instrumentation.isWrapped(Broker.prototype, 'handle'),
false
)
assert.strictEqual(
instrumentation.isWrapped(ConnectHandler, 'handleConnect'),
false
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await using brokerWrapper = await getBroker()
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await using clientWrapper = await getMqttClient(true)
const spans = memorySpanExporter.getFinishedSpans()
assert.strictEqual(spans.length, 0)
})
it('should create a span when a client is connected', async () => {
await using brokerWrapper = await getBroker()
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await using clientWrapper = await getMqttClient()
const client = await waitForEvent(
brokerWrapper.broker,
'clientReady',
(client: AedesClient) => client
)
const span = memorySpanExporter
.getFinishedSpans()
.find((span) => span.name.includes('mqtt.connect'))
assert.notStrictEqual(span, undefined)
assert.strictEqual(
client[CONNECTION_ATTRIBUTES][AedesAttributes.CLIENT_ID],
client.id
)
assert.strictEqual(
client[CONNECTION_ATTRIBUTES][SemanticAttributes.MESSAGING_SYSTEM],
AedesAttributes.MESSAGING_SYSTEM
)
assert.strictEqual(
client[CONNECTION_ATTRIBUTES][SemanticAttributes.MESSAGING_PROTOCOL],
AedesAttributes.MESSAGING_PROTOCOL
)
assert.notStrictEqual(
span?.events.find((event) => event.name === 'preConnect'),
undefined
)
assert.notStrictEqual(
span?.events.find((event) => event.name === 'authenticate'),
undefined
)
assert.strictEqual(span?.attributes[AedesAttributes.CLIENT_ID], client.id)
})
it('should allow usage with broker instance as a client', async () => {
const onDeliver = mock.fn((packet, cb) => cb())
const topic = 'test'
await using brokerWrapper = await getBroker()
const { broker } = brokerWrapper
await new Promise((resolve) => {
broker.subscribe(
topic,
(packet, cb) => onDeliver(packet, cb),
() => resolve(null)
)
})
const packet = {
topic,
payload: Buffer.from('test'),
qos: 0,
retain: false,
}
assert.strictEqual(onDeliver.mock.calls.length, 0)
await promisify(broker.publish.bind(broker))(packet)
assert.strictEqual(onDeliver.mock.calls.length, 1)
const call = onDeliver.mock.calls[0]
assert.strictEqual(call.error, undefined)
mock.reset()
})
it('should create a span when a client is publishing a message (JSON payload)', async () => {
await using brokerWrapper = await getBroker()
await using clientWrapper = await getMqttClient(true)
const topic = 'test'
await clientWrapper.client.publishAsync(
topic,
JSON.stringify({ message: 'test' })
)
await waitForEvent(
brokerWrapper.broker,
'publish',
(packet: AedesPublishPacket) => {
if (packet.topic.startsWith('$SYS')) {
return NO_RESOLVE
}
return packet
}
)
const span = memorySpanExporter
.getFinishedSpans()
.find((span) => span.name.includes(`${topic} publish`))
assert.notStrictEqual(span, undefined)
assert.notStrictEqual(
span?.events.find((event) => event.name === 'authorizePublish'),
undefined
)
})
it('should propagate from the publisher to the subscriber (JSON payload)', async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await using brokerWrapper = await getBroker()
await using clientWrapper1 = await getMqttClient(true)
await using clientWrapper2 = await getMqttClient(true)
const publisher = clientWrapper1.client
const subscriber = clientWrapper2.client
const topic = 'test'
await subscriber.subscribeAsync(topic)
await publisher.publishAsync(topic, JSON.stringify({ message: 'test' }))
const promises = [
waitForEvent(
brokerWrapper.broker,
'publish',
(packet: AedesPublishPacket) => {
if (packet.topic.startsWith('$SYS')) {
return NO_RESOLVE
}
return packet
}
),
waitForEvent(
subscriber,
'message',
(topic, message, packet: IPublishPacket) => packet
),
]
await Promise.all(promises)
await memorySpanExporter.forceFlush()
const subscriberSpan = memorySpanExporter
.getFinishedSpans()
.find((span) => span.name.includes(`${topic} receive`))
const publisherSpan = memorySpanExporter
.getFinishedSpans()
.find((span) => span.name.includes(`${topic} publish`))
assert.notStrictEqual(subscriberSpan, undefined)
assert.notStrictEqual(publisherSpan, undefined)
assert.strictEqual(
publisherSpan?.spanContext().spanId,
subscriberSpan?.parentSpanId
)
})
it.todo('should capture connection events')
it.todo('should capture connection errors')
})