All files mqtt-plus-base.ts

88.7% Statements 220/248
79.31% Branches 46/58
100% Functions 17/17
88.7% Lines 220/248

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 2491x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 2x 2x 2x 4x 4x 4x 4x             4x 2x 2x 9x 9x 9x 9x 9x 9x 9x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1098x 1098x 1098x       1099x 1099x 9x 9x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 28x 28x 28x 28x 28x       28x 28x 28x 28x 1x 1x 1x 19x 19x 19x 19x       19x 19x 19x 19x 19x 1x 1x 1x 19x 19x 19x 19x 7x 7x 7x 12x 12x 19x 19x 19x 1x 1x 1x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1098x 1098x 1099x 1099x 1099x 1096x 1096x 1096x 1096x 1096x       1096x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1x 1098x 1099x 1099x       1099x 1099x 1099x 1099x 1099x 1x 1x 1x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1098x 1098x 1099x 1099x 1099x 1099x 1x 1x 1x 1x 1099x 1099x 1099x 1098x 1098x 1098x         1099x 1098x 1098x 1099x 33x 33x 33x 32x   32x 32x 33x 1065x 1065x 1065x 1065x 1061x   1061x 1061x 1065x 1099x    
/*
**  MQTT+ -- MQTT Communication Patterns
**  Copyright (c) 2018-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
/*  external requirements  */
import { type MqttClient,
    type OnMessageCallback,
    type IClientSubscribeOptions,
    type IClientPublishOptions,
    type IPublishPacket }               from "mqtt"
 
/*  internal requirements  */
import type { APISchema, Registration } from "./mqtt-plus-api"
import type { Message }                 from "./mqtt-plus-msg"
import type { APIOptions }              from "./mqtt-plus-options"
import { TraceTrait }                   from "./mqtt-plus-trace"
import { Spool, ensureError }           from "./mqtt-plus-error"
import { PLazy }                        from "./mqtt-plus-util"
 
/*  MQTTp Base class with shared infrastructure  */
export class BaseTrait<T extends APISchema = APISchema> extends TraceTrait<T> {
    private mqtt: MqttClient
    private messageHandler: OnMessageCallback
 
    /*  central message callback registries  */
    protected onRequest  = new Map<string, (message: any, topicName: string) => void | Promise<void>>()
    protected onResponse = new Map<string, (message: any, topicName: string) => void | Promise<void>>()
 
    /*  construct API class  */
    constructor (
        mqtt: MqttClient | null,
        options: Partial<APIOptions> = {}
    ) {
        super(options)
 
        /*  optionally provide a fake proxy for the MQTT client
            (mainly for using emit({ ..., dry: true }) to just make MQTT "last will")  */
        if (mqtt === null) {
            this.log("info", "establishing proxy MQTT client")
            mqtt = new Proxy<MqttClient>({} as MqttClient, {
                get (_target, prop, _receiver): any {
                    if (prop === "isFakeProxy")
                        return true
                    else if (typeof prop === "string" && [ "on", "off", "once" ].includes(prop))
                        return () => {}
                    else
                        return () => {
                            throw new Error(`Underlying MQTT operation "${String(prop)}" called ` +
                                "on a null MQTT client -- only MQTT+ \"emit({ ..., dry: true })\" " +
                                "is supported in this special operation mode")
                        }
                }
            })
        }
 
        /*  store MQTT client  */
        this.mqtt = mqtt
 
        /*  hook into the MQTT message processing  */
        this.log("info", "hooking into MQTT client")
        this.messageHandler = (topic, message, packet) => {
            /*  convert message to codec-specific input format
                (NOTICE: MQTT.js uses Buffer in its handler signature only,
                but internally supports string or Buffer, while we are
                dealing with string or Uint8Array only)  */
            let input: Uint8Array | string
            if (this.options.codec === "json")
                input = message.toString()
            else if (this.options.codec === "cbor")
                input = Buffer.isBuffer(message)
                    ? new Uint8Array(message.buffer, message.byteOffset, message.byteLength)
                    : message
            else
                throw new Error("invalid codec configured")
            this._onMessage(topic, input, packet)
        }
        this.mqtt.on("message", this.messageHandler)
    }
 
    /*  destroy API class  */
    async destroy () {
        this.log("info", "un-hooking from MQTT client")
        this.mqtt.off("message", this.messageHandler)
        this.onRequest.clear()
        this.onResponse.clear()
    }
 
    /*  create a registration for subsequent destruction  */
    protected makeRegistration (spool: Spool, kind: string, name: string, key: string): Registration {
        return {
            destroy: async (): Promise<void> => {
                if (!this.onRequest.has(key))
                    throw new Error(`destroy: ${kind} "${name}" not registered`)
                await spool.unroll(false)?.catch((err: unknown) => {
                    const error = ensureError(err, `destroy: ${kind} "${name}" failed to cleanup`)
                    this.error(error)
                    throw error
                })
            }
        }
    }
 
    /*  subscribe to an MQTT topic (Promise-based)  */
    protected async subscribeTopic (topic: string, options: Partial<IClientSubscribeOptions> = {}): Promise<void> {
        this.log("info", `subscribing to MQTT topic "${topic}"`)
        return new Promise<void>((resolve, reject) => {
            this.mqtt.subscribe(topic, { qos: 2, ...options }, (err: Error | null, _granted: any) => {
                if (err) {
                    this.error(err, `subscribing to MQTT topic "${topic}" failed`)
                    reject(err)
                }
                else
                    resolve()
            })
        })
    }
 
    /*  unsubscribe from an MQTT topic (Promise-based)  */
    protected async unsubscribeTopic (topic: string): Promise<void> {
        this.log("info", `unsubscribing from MQTT topic "${topic}"`)
        return new Promise<void>((resolve, reject) => {
            this.mqtt.unsubscribe(topic, (err?: Error, _packet?: any) => {
                if (err) {
                    this.error(err, `unsubscribing from MQTT topic "${topic}" failed`)
                    reject(err)
                }
                else
                    resolve()
            })
        })
    }
 
    /*  publish to an MQTT topic (Promise-based)  */
    protected async publishToTopic (
        topic:   string,
        message: string | Uint8Array,
        options: IClientPublishOptions = {}
    ) {
        /*  determine buffer  */
        if (typeof message === "string")
            this.log("info", `publishing to MQTT topic "${topic}" (type: string, length: ${message.length} chars)`)
        else
            this.log("info", `publishing to MQTT topic "${topic}" (type: buffer, length: ${message.byteLength} bytes)`)
 
        /*  provide decoded message on demand  */
        const messageOnDemand = new PLazy<Message>((resolve, reject) => {
            let parsed: Message
            try {
                const payload = this.codec.decode(message)
                parsed = this.msg.parse(payload)
            }
            catch (err: unknown) {
                return reject(err)
            }
            resolve(parsed)
        })
        this.log("debug", `publishing to MQTT topic "${topic}"`, { message: messageOnDemand })
 
        /*  forward operation to underlying MQTT facility  */
        return new Promise<void>((resolve, reject) => {
            /*  NOTICE: MQTT.js is dealing with string or Buffer only  */
            const messageData = typeof message === "string"
                ? message
                : Buffer.from(message.buffer, message.byteOffset, message.byteLength)
            this.mqtt.publish(topic, messageData, options, (err?: Error) => {
                if (err) {
                    this.error(err, `publishing to MQTT topic "${topic}" failed`)
                    reject(err)
                }
                else
                    resolve()
            })
        })
    }
 
    /*  handle incoming MQTT message  */
    private _onMessage (topic: string, data: string | Uint8Array, _packet: IPublishPacket): void {
        /*  parse MQTT topic  */
        const topicMatch = this.options.topicMatch(topic)
        if (topicMatch === null)
            return
 
        /*  parse MQTT data into payload object  */
        if (typeof data === "string")
            this.log("info", `received from MQTT topic "${topic}" (type: string, length: ${data.length} chars)`)
        else
            this.log("info", `received from MQTT topic "${topic}" (type: buffer, length: ${data.byteLength} bytes)`)
        let payload: any
        try {
            payload = this.codec.decode(data)
        }
        catch (err: unknown) {
            this.error(ensureError(err, "failed to parse message into object"))
            return
        }
 
        /*  parse payload object into typed MQTT+ message  */
        let message: Message
        try {
            message = this.msg.parse(payload)
        }
        catch (err: unknown) {
            this.error(ensureError(err, "failed to parse object into typed message object"))
            return
        }
        this.log("debug", `received from MQTT topic "${topic}"`, { message })
 
        /*  dispatch MQTT+ message  */
        if (this.msg.isRequest(message)) {
            /*  dispatch request message  */
            const handler = this.onRequest.get(`${message.type}:${message.name}`)
            if (handler !== undefined) {
                Promise.resolve().then(() => handler(message, topicMatch.name)).catch((err: unknown) => {
                    this.error(ensureError(err, `dispatching request message from MQTT topic "${topic}" failed`))
                })
            }
        }
        else if (this.msg.isResponse(message)) {
            /*  dispatch response message  */
            const handler = this.onResponse.get(`${message.type}:${message.id}`)
            if (handler !== undefined) {
                Promise.resolve().then(() => handler(message, topicMatch.name)).catch((err: unknown) => {
                    this.error(ensureError(err, `dispatching response message from MQTT topic "${topic}" failed`))
                })
            }
        }
    }
}