All files mqtt-plus-event.ts

99.1% Statements 222/224
69.23% Branches 27/39
100% Functions 9/9
99.1% Lines 222/224

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 2251x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 8x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 9x 9x 9x 10x 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 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 8x 8x   8x 9x    
/*
**  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 { IClientPublishOptions,
    IClientSubscribeOptions }         from "mqtt"
import { nanoid }                     from "nanoid"
 
/*  internal requirements  */
import type { EventEmission }         from "./mqtt-plus-msg"
import type { APISchema, EventKeys,
    Registration }                    from "./mqtt-plus-api"
import type { WithInfo, InfoEvent }   from "./mqtt-plus-info"
import { AuthTrait, type AuthOption } from "./mqtt-plus-auth"
import { Spool, ensureError }         from "./mqtt-plus-error"
 
/*  Event Emission Trait  */
export class EventTrait<T extends APISchema = APISchema> extends AuthTrait<T> {
    /*  register an event handler  */
    async event<K extends EventKeys<T> & string> (
        name:     K,
        callback: WithInfo<T[K], InfoEvent>
    ): Promise<Registration>
    async event<K extends EventKeys<T> & string> (
        config: {
            name:      K,
            callback:  WithInfo<T[K], InfoEvent>,
            options?:  Partial<IClientSubscribeOptions>,
            share?:    string,
            auth?:     AuthOption
        }
    ): Promise<Registration>
    async event<K extends EventKeys<T> & string> (
        nameOrConfig: K | {
            name:      K,
            callback:  WithInfo<T[K], InfoEvent>,
            options?:  Partial<IClientSubscribeOptions>,
            share?:    string,
            auth?:     AuthOption
        },
        ...args:       any[]
    ): Promise<Registration> {
        /*  determine actual parameters  */
        let name:     K
        let callback: WithInfo<T[K], InfoEvent>
        let options:  Partial<IClientSubscribeOptions> = {}
        let share     = this.options.share
        let auth:     AuthOption | undefined
        if (typeof nameOrConfig === "object" && nameOrConfig !== null && "name" in nameOrConfig) {
            /*  object-based API  */
            name     = nameOrConfig.name
            callback = nameOrConfig.callback
            options  = nameOrConfig.options ?? {}
            share    = nameOrConfig.share   ?? this.options.share
            auth     = nameOrConfig.auth
        }
        else {
            /*  positional API  */
            name     = nameOrConfig
            callback = args[0]
        }
 
        /*  sanity check callback  */
        if (typeof callback !== "function")
            throw new Error("event: callback argument is required and must be a function")
 
        /*  create resource spool  */
        const spool = new Spool()
 
        /*  sanity check situation  */
        if (this.onRequest.has(`event-emission:${name}`))
            throw new Error(`event: event "${name}" already registered`)
 
        /*  generate the corresponding MQTT topics for broadcast and direct use  */
        const topicS = share !== "" ? `$share/${share}/${name}` : name
        const topicB = this.options.topicMake(topicS, "event-emission")
        const topicD = this.options.topicMake(name,   "event-emission", this.options.id)
 
        /*  remember the registration  */
        this.onRequest.set(`event-emission:${name}`, async (request: EventEmission, topicName: string) => {
            /*  check receiver  */
            if (request.receiver && request.receiver !== this.options.id)
                return
 
            /*  determine event information  */
            const senderId = request.sender
            if (senderId === undefined || senderId === "")
                throw new Error("invalid request: missing sender")
            const params   = request.params ?? []
 
            /*  create information object  */
            const info: InfoEvent = { sender: senderId }
            if (request.receiver)
                info.receiver = request.receiver
            if (request.meta)
                info.meta = request.meta
 
            /*  asynchronously execute handler  */
            try {
                if (topicName !== request.name)
                    throw new Error(`event name mismatch (topic: "${topicName}", payload: "${request.name}")`)
                if (auth)
                    info.authenticated = await this.authenticated(senderId, request.auth, auth)
                if (info.authenticated !== undefined && !info.authenticated)
                    throw new Error(`event "${name}" failed authentication`)
                await callback(...params, info)
            }
            catch (result: unknown) {
                const error = ensureError(result)
                this.error(error, `handler for event "${name}" failed`)
            }
        })
        spool.roll(() => { this.onRequest.delete(`event-emission:${name}`) })
 
        /*  subscribe to MQTT topics  */
        await this.subscribeTopicAndSpool(spool, topicB, options)
        await this.subscribeTopicAndSpool(spool, topicD, options)
 
        /*  provide a registration for subsequent destruction  */
        return this.makeRegistration(spool, "event", name, `event-emission:${name}`)
    }
 
    /*  emit event ("fire and forget")  */
    emit<K extends EventKeys<T> & string> (
        name:          K,
        ...params:     Parameters<T[K]>
    ): void
    emit<K extends EventKeys<T> & string> (
        config: {
            name:      K,
            params:    Parameters<T[K]>,
            receiver?: string,
            options?:  IClientPublishOptions,
            meta?:     Record<string, any>
        }
    ): void
    emit<K extends EventKeys<T> & string> (
        config: {
            name:      K,
            params:    Parameters<T[K]>,
            receiver?: string,
            options?:  IClientPublishOptions,
            meta?:     Record<string, any>,
            dry:       true
        }
    ): { topic: string, payload: string | Uint8Array, options: IClientPublishOptions }
    emit<K extends EventKeys<T> & string> (
        nameOrConfig: K | {
            name:      K,
            params:    Parameters<T[K]>,
            receiver?: string,
            options?:  IClientPublishOptions,
            meta?:     Record<string, any>,
            dry?:      true
        },
        ...args:       any[]
    ): void | { topic: string, payload: string | Uint8Array, options: IClientPublishOptions } {
        /*  determine actual parameters  */
        let name:      K
        let params:    Parameters<T[K]>
        let receiver:  string | undefined
        let options:   IClientPublishOptions = {}
        let meta:      Record<string, any> | undefined
        let dry:       boolean | undefined
        if (typeof nameOrConfig === "object" && nameOrConfig !== null && "name" in nameOrConfig) {
            /*  object-based API  */
            name     = nameOrConfig.name
            params   = nameOrConfig.params
            receiver = nameOrConfig.receiver
            options  = nameOrConfig.options ?? {}
            meta     = nameOrConfig.meta
            dry      = nameOrConfig.dry
        }
        else {
            /*  positional API  */
            name     = nameOrConfig
            params   = args as Parameters<T[K]>
        }
 
        /*  generate unique request id  */
        const requestId = nanoid()
 
        /*  generate encoded message  */
        const auth      = this.authenticate()
        const metaStore = this.metaStore(meta)
        const request   = this.msg.makeEventEmission(requestId, name, params,
            this.options.id, receiver, auth, metaStore)
        const message   = this.codec.encode(request)
 
        /*  generate corresponding MQTT topic  */
        const topic = this.options.topicMake(name, "event-emission", receiver)
 
        /*  produce result  */
        if (dry)
            /*  return publish information  */
            return { topic, payload: message, options: { qos: 2, ...options } }
        else
            /*  publish message to MQTT topic  */
            this.publishToTopic(topic, message, { qos: 2, ...options }).catch((err: Error) => {
                this.error(err, `emitting event "${name}" failed`)
            })
    }
}