All files / src/adapters/mqtt index.ts

5.37% Statements 5/93
1.5% Branches 2/133
3.22% Functions 1/31
5.68% Lines 5/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                              1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import mqtt, { IPublishPacket, MqttClient, QoS } from 'mqtt'
import Adapter from '../../lib/adapter.js'
import GleeQuoreMessage from '../../lib/message.js'
import { MqttAuthConfig, MqttAdapterConfig } from '../../index.d.js'
import { SecuritySchemesInterface as SecurityScheme } from '@asyncapi/parser'
 
interface IMQTTHeaders {
  cmd?: string
  retain?: boolean
  qos: QoS
  dup: boolean
  length: number
}
 
interface ClientData {
  url?: URL
  auth?: MqttAuthConfig
  serverBinding?: any
  protocolVersion?: number
  userAndPasswordSecurityReq?: SecurityScheme
  X509SecurityReq?: SecurityScheme
}
 
const MQTT_UNSPECIFIED_ERROR_REASON = 0x80
const MQTT_SUCCESS_REASON = 0
enum SecurityTypes {
  USER_PASSWORD = 'userpassword',
  X509 = 'x509',
}
class MqttAdapter extends Adapter {
  private client: MqttClient
  private firstConnect: boolean
 
  name(): string {
    return 'MQTT adapter'
  }
 
  async connect(): Promise<this> {
    return this._connect()
  }
 
  async send(message: GleeQuoreMessage) {
    return this._send(message)
  }
 
  private getSecurityReqs() {
    let userAndPasswordSecurityReq
    let X509SecurityReq
 
    const securityRequirements = this.AsyncAPIServer.security().map((e) =>
      e.all().map((e) => e.scheme())
    )
 
    securityRequirements.forEach((security) => {
      for (const sec of security) {
        const securityType = sec.type().toLocaleLowerCase()
        switch (securityType) {
          case SecurityTypes.USER_PASSWORD:
            userAndPasswordSecurityReq = sec
            break
          case SecurityTypes.X509:
            X509SecurityReq = sec
            break
          default:
            this.emit(
              'error',
              new Error(
                `Invalid security type '${securityType}' specified for server '${this.serverName
                }'. Please double-check your configuration to ensure you're using a supported security type. Here is a list of supported types: ${Object.values(
                  SecurityTypes
                )}`
              )
            )
        }
      }
    })
 
    return {
      userAndPasswordSecurityReq,
      X509SecurityReq,
    }
  }
 
  private async initializeClient(data: ClientData) {
    const {
      url,
      auth,
      serverBinding,
      protocolVersion,
      userAndPasswordSecurityReq,
      X509SecurityReq,
    } = data
 
    return mqtt.connect({
      host: url.hostname,
      port: url.port || (url.protocol === 'mqtt:' ? 1883 : 8883),
      protocol: url.protocol.slice(0, url.protocol.length - 1),
      clientId: serverBinding?.clientId ?? auth?.clientId,
      clean: serverBinding?.cleanSession,
      will: serverBinding?.will && {
        topic: serverBinding?.lastWill?.topic,
        qos: serverBinding?.lastWill?.qos,
        payload: serverBinding?.lastWill?.message,
        retain: serverBinding?.lastWill?.retain,
      },
      keepalive: serverBinding?.keepAlive,
      username: userAndPasswordSecurityReq ? auth?.username : undefined,
      password: userAndPasswordSecurityReq ? auth?.password : undefined,
      ca: X509SecurityReq ? auth?.cert : undefined,
      protocolVersion,
      customHandleAcks: this._customAckHandler.bind(this),
    } as any)
  }
 
  private async listenToEvents(data: ClientData) {
    const { protocolVersion } = data
 
    this.client.on('close', () => {
      this.emit('close', {
        connection: this.client,
        channels: this.channelNames.map((channelName) =>
          this.parsedAsyncAPI.channels().get(channelName).address()
        ),
      })
    })
 
    this.client.on('error', (error) => {
      this.emit('error', error)
    })
 
    this.client.on('message', (channel, message, mqttPacket) => {
      const qos = mqttPacket.qos
      Iif (protocolVersion === 5 && qos > 0) return // ignore higher qos messages. already processed
 
      const msg = this._createMessage(mqttPacket as IPublishPacket)
      this.emit('message', msg, this.client)
    })
  }
 
  private checkFirstConnect() {
    this.firstConnect = true
    this.emit('connect', {
      name: this.name(),
      adapter: this,
      connection: this.client,
      channels: this.channelNames,
    })
  }
 
  private subscribe(channels: string[]) {
    channels.forEach((channel) => {
      const asyncAPIChannel = this.parsedAsyncAPI.channels().get(channel)
      const receiveOperations = asyncAPIChannel.operations().filterByReceive()
      Iif (receiveOperations.length > 1) {
        this.emit('error', new Error(`Channel ${channel} has more than one receive operation. Please make sure you have only one.`))
        return
      }
      const binding = asyncAPIChannel.operations().filterByReceive()[0].bindings().get('mqtt')?.value()
      const topic = asyncAPIChannel.address()
      this.client.subscribe(
        topic,
        {
          qos: binding?.qos ? binding.qos : 0,
        },
        (err, granted) => {
          Iif (err) {
            console.error(`Error while trying to subscribe to \`${topic}\` topic.`)
            console.error(err.message)
            return
          }
          granted.forEach(({ topic, qos }) => {
            console.log(`Subscribed to \`${topic}\` topic with QoS ${qos}`)
          })
        }
      )
    })
  }
 
  async _connect(): Promise<this> {
    const mqttOptions: MqttAdapterConfig = await this.resolveProtocolConfig(
      'mqtt'
    )
    const auth: MqttAuthConfig = await this.getAuthConfig(mqttOptions?.auth)
    const subscribedChannels = this.getSubscribedChannels()
    const mqttServerBinding = this.AsyncAPIServer.bindings().get('mqtt')
    const mqtt5ServerBinding = this.AsyncAPIServer.bindings().get('mqtt5')
 
    const { userAndPasswordSecurityReq, X509SecurityReq } =
      this.getSecurityReqs()
 
    const url = new URL(this.AsyncAPIServer.url())
 
    const protocolVersion = parseInt(
      this.AsyncAPIServer.protocolVersion() || '4'
    )
    const serverBinding =
      protocolVersion === 5 ? mqtt5ServerBinding : mqttServerBinding
 
    this.client = await this.initializeClient({
      url,
      auth,
      serverBinding,
      protocolVersion,
      userAndPasswordSecurityReq,
      X509SecurityReq,
    })
 
    await this.listenToEvents({ protocolVersion })
 
    const connectClient = (): Promise<this> => {
      return new Promise((resolve) => {
        this.client.on('connect', (connAckPacket) => {
          const isSessionResume = connAckPacket.sessionPresent
 
          Iif (!this.firstConnect) {
            this.checkFirstConnect()
          }
 
          const shouldSubscribe =
            !isSessionResume && Array.isArray(subscribedChannels)
 
          Iif (shouldSubscribe) {
            this.subscribe(subscribedChannels)
          }
 
          resolve(this)
        })
      })
    }
 
    return connectClient()
 
  }
 
  _send(message: GleeQuoreMessage): Promise<void> {
    return new Promise((resolve, reject) => {
      const channel = this.parsedAsyncAPI.channels().get(message.channel)
      const address = channel.address()
      const binding = channel.bindings().get('mqtt')?.value()
      this.client.publish(
        address,
        message.payload,
        {
          qos: binding?.qos ? binding.qos : 2,
          retain: binding?.retain ? binding.retain : false,
        },
        (err) => {
          Iif (err) {
            reject(err)
            return
          }
 
          resolve()
        }
      )
    })
  }
 
  _createMessage(packet: IPublishPacket): GleeQuoreMessage {
    const headers: IMQTTHeaders = {
      cmd: packet.cmd,
      retain: packet.retain,
      qos: packet.qos,
      dup: packet.dup,
      length: packet.length,
    }
    const id = this.parsedAsyncAPI.channels().all().filter(channel => channel.address() === packet.topic)[0]?.id()
    return new GleeQuoreMessage({
      payload: packet.payload,
      headers,
      channel: id,
    })
  }
 
  _customAckHandler(channel, message, mqttPacket, done) {
    const msg = this._createMessage(mqttPacket as IPublishPacket)
 
    msg.on('processing:successful', () => done(MQTT_SUCCESS_REASON))
    msg.on('processing:failed', () => done(MQTT_UNSPECIFIED_ERROR_REASON))
 
    this.emit('message', msg, this.client)
  }
}
 
export default MqttAdapter