All files mqtt-plus-error.ts

91.28% Statements 335/367
75.58% Branches 65/86
100% Functions 17/17
91.28% Lines 335/367

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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 3681x 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 290x 290x 290x 290x 2x     290x 290x 290x 290x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 83x 83x 83x 83x 83x 83x 83x 290x 290x 290x 290x 66x 66x 66x 66x 66x 224x 224x 224x 224x 223x 223x 224x 224x 224x 290x 83x 83x 22x 22x 83x 2x 2x 2x 1x 1x 83x 1x 1x 1x 1x 19x 19x 19x 3x   19x 19x 19x 19x 19x 3x 3x 3x 3x     19x 1x 1x 1x 1x 113x 113x 113x 113x 3x 3x 113x 113x                     113x   113x   113x 1x 1x 1x 1x 2x 2x 2x 1x 2x 2x   2x   2x   2x 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 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 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x               114x 108x 108x 94x 94x 94x 94x 94x 94x 14x 14x 14x 14x 14x 14x 108x 6x 6x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 6x 114x 114x 114x 114x 114x 114x 114x 113x 113x 113x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x       114x 110x 110x 108x 108x 108x 108x 110x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x     110x 110x 1x 1x 1x 1x 1x 1x 1x 114x  
/*
**  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.
*/
 
/*  type of a single resource cleanup handler  */
type SpoolCleanup<T = unknown> =
    (resource: T) => void | Promise<void>
 
/*  type of a single resource  */
type SpoolResource<T = unknown> = {
    resource: T,
    cleanup:  SpoolCleanup<T>
}
 
/*  resource spooling class  */
export class Spool {
    /*  internal state  */
    private resources: SpoolResource<unknown>[] = []
 
    /*  roll cleanup procedure onto spool  */
    roll (cleanup: SpoolCleanup): void
    roll <T>(resource: T, cleanup: SpoolCleanup<T>): void
    roll (...args: any[]): void {
        /*  determine parameters  */
        let resource: unknown
        let cleanup:  SpoolCleanup<unknown>
        if      (args.length === 1) { resource = undefined; cleanup  = args[0] }
        else if (args.length === 2) { resource = args[0];   cleanup  = args[1] }
        else
            throw new Error("invalid number of arguments")
 
        /*  store information  */
        this.resources.push({ resource, cleanup })
    }
 
    /*  roll a sub-spool onto spool  */
    sub (): Spool {
        /*  create new spool  */
        const spool = new Spool()
 
        /*  roll sub-spool onto spool  */
        this.roll(spool, () => {})
 
        /*  return new spool  */
        return spool
    }
 
    /*  unroll all cleanup procedures from spool  */
    unroll (suppress = true): Promise<void> | void {
        /*  NOTICE: we operate synchronously until the first
            cleanup procedure returns a Promise. Then we continue
            asynchronously, regardless of whether the following
            cleanup procedures return a Promise or not!  */
        try {
            let promise: Promise<void> | undefined
            while (this.resources.length > 0) {
                const entry    = this.resources.pop()!
                const resource = entry.resource
                const cleanup  = entry.cleanup
                if (promise) {
                    if (resource instanceof Spool)
                        promise = promise.then(() => resource.unroll() /* RECURSION */)
                    else
                        promise = promise.then(() => cleanup(resource))
                }
                else {
                    let result: Promise<void> | void
                    if (resource instanceof Spool)
                        result = resource.unroll() /* RECURSION */
                    else
                        result = cleanup(resource)
                    if (result instanceof Promise)
                        promise = result
                }
            }
            if (promise)
                return suppress ? promise.catch(() => {}) : promise
            else
                return
        }
        catch (error: unknown) {
            if (suppress)
                return
            throw error
        }
    }
}
 
/*  helper function for retrieving an Error object  */
export function ensureError (error: unknown, prefix?: string, debug = false): Error {
    if (error instanceof Error && prefix === undefined && debug === false)
        return error
    let msg = error instanceof Error
        ? error.message
        : String(error)
    if (prefix)
        msg = `${prefix}: ${msg}`
    if (debug && error instanceof Error)
        msg = `${msg}\n${error.stack}`
    if (error instanceof Error) {
        const err = new Error(msg, { cause: error })
        err.stack = error.stack
        return err
    }
    else
        return new Error(msg)
}
 
/*  helper function for running the finally code of "run"  */
function runFinally (isAsync: false,   onfinally?: () => void): void
function runFinally (isAsync: true,    onfinally?: () => Promise<void> | void): Promise<void>
function runFinally (isAsync: boolean, onfinally?: () => Promise<void> | void): Promise<void> | void {
    if (!onfinally) {
        if (isAsync)
            return Promise.resolve()
        else
            return
    }
    let result: Promise<void> | void
    try {
        result = onfinally()
    }
    catch (error: unknown) {
        if (isAsync)
            return Promise.reject(error)
        else
            throw error
    }
    if (!isAsync && result instanceof Promise)
        throw new Error("onfinally callback returned Promise in non-async context")
    if (isAsync && !(result instanceof Promise))
        result = Promise.resolve(result)
    return result
}
 
/*  helper function for unrolling a spool  */
function runUnroll (isAsync: false,   spool?: Spool): void
function runUnroll (isAsync: true,    spool?: Spool): Promise<void>
function runUnroll (isAsync: boolean, spool?: Spool): Promise<void> | void {
    if (!spool) {
        if (isAsync) return Promise.resolve()
        else         return
    }
    let result = spool.unroll()
    if (!isAsync && result instanceof Promise)
        throw new Error("spool unroll returned Promise in non-async context")
    if (isAsync && !(result instanceof Promise))
        result = Promise.resolve(result)
    return result
}
 
/*  helper type for ensuring T contains no Promise  */
type RunNoPromise<T> =
    [ T ] extends [ Promise<any> ] ? never : T
 
/*  run a synchronous or asynchronous action  */
export function run<T, X extends RunNoPromise<T> | never> (
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => void,
    oncleanup?:  (value: T)     => void
): X
export function run<T, X extends RunNoPromise<T> | never> (
    description: string,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => void,
    oncleanup?:  (value: T)     => void
): X
export function run<T, X extends Promise<T> | never> (
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => Promise<void>,
    oncleanup?:  (value: T)     => Promise<void>
): X
export function run<T, X extends Promise<T> | never> (
    description: string,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => Promise<void> | void,
    oncleanup?:  (value: T)     => Promise<void> | void
): X
export function run<T, X extends RunNoPromise<T> | never> (
    spool:       Spool | undefined,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => void,
    oncleanup?:  (value: T)     => void
): X
export function run<T, X extends RunNoPromise<T> | never> (
    description: string,
    spool:       Spool | undefined,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => void,
    oncleanup?:  (value: T)     => void
): X
export function run<T, X extends Promise<T> | never> (
    spool:       Spool | undefined,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => Promise<void>,
    oncleanup?:  (value: T)     => Promise<void>
): X
export function run<T, X extends Promise<T> | never> (
    description: string,
    spool:       Spool | undefined,
    action:      ()             => X,
    oncatch?:    (error: Error) => X,
    onfinally?:  ()             => Promise<void>,
    oncleanup?:  (value: T)     => Promise<void>
): X
export function run<T, X extends RunNoPromise<T> | never> (
    config: {
        description?: string,
        spool?:       Spool | undefined,
        action:       ()             => X,
        oncatch?:     (error: Error) => X,
        onfinally?:   ()             => void,
        oncleanup?:   (value: T)     => void
    }
): X
export function run<T, X extends Promise<T>> (
    config: {
        description?: string,
        spool?:       Spool | undefined,
        action:       ()             => X,
        oncatch?:     (error: Error) => X,
        onfinally?:   ()             => Promise<void>,
        oncleanup?:   (value: T)     => Promise<void>
    }
): X
export function run<T> (
    ...args: any[]
): T | Promise<T> | never {
    /*  support overloaded signatures  */
    let description: string | undefined
    let spool:       Spool | undefined
    let action:      () => T | Promise<T> | never
    let oncatch:     ((error: Error) => T | Promise<T> | never) | undefined
    let onfinally:   (() => void) | undefined
    let oncleanup:   ((value: T) => void) | undefined
    if (args.length === 1 && typeof args[0] === "object" && args[0] !== null) {
        description = args[0].description
        spool       = args[0].spool
        action      = args[0].action
        oncatch     = args[0].oncatch
        onfinally   = args[0].onfinally
        oncleanup   = args[0].oncleanup
    }
    else if (typeof args[0] === "string") {
        description = args[0]
        if (args[1] instanceof Spool || (args[1] === undefined && typeof args[2] === "function")) {
            spool       = args[1]
            action      = args[2]
            oncatch     = args[3]
            onfinally   = args[4]
            oncleanup   = args[5]
        }
        else {
            action      = args[1]
            oncatch     = args[2]
            onfinally   = args[3]
            oncleanup   = args[4]
        }
    }
    else {
        if (args[0] instanceof Spool || (args[0] === undefined && typeof args[1] === "function")) {
            spool       = args[0]
            action      = args[1]
            oncatch     = args[2]
            onfinally   = args[3]
            oncleanup   = args[4]
        }
        else {
            action      = args[0]
            oncatch     = args[1]
            onfinally   = args[2]
            oncleanup   = args[3]
        }
    }
 
    /*  sanity check spool/oncleanup scenario  */
    if (oncleanup && !spool)
        throw new Error("oncleanup requires a spool")
 
    /*  perform the action  */
    let result: T | Promise<T>
    try {
        result = action()
    }
    catch (arg: unknown) {
        /*  synchronous case (error branch)  */
        let error = ensureError(arg, description)
        if (oncatch) {
            try {
                result = oncatch(error)
            }
            catch (arg: unknown) {
                error = ensureError(arg, description)
                runFinally(false, onfinally)
                runUnroll(false, spool)
                throw error
            }
            runFinally(false, onfinally)
            return result
        }
        runFinally(false, onfinally)
        runUnroll(false, spool)
        throw error
    }
    if (result instanceof Promise) {
        /*  asynchronous case (result or error branch)  */
        return result.then(async (result) => {
            await runFinally(true, onfinally)
            if (spool && oncleanup)
                spool.roll(result, oncleanup as SpoolCleanup<unknown>)
            return result
        }, async (arg: unknown) => {
            /*  asynchronous case (error branch)  */
            let error = ensureError(arg, description)
            if (oncatch) {
                try {
                    const result = oncatch(error)
                    await runFinally(true, onfinally)
                    return result
                }
                catch (arg: unknown) {
                    error = ensureError(arg, description)
                    await runFinally(true, onfinally)
                    await runUnroll(true, spool)
                    throw error
                }
            }
            await runFinally(true, onfinally)
            await runUnroll(true, spool)
            throw error
        })
    }
    else {
        /*  synchronous case (result branch)  */
        runFinally(false, onfinally)
        if (spool && oncleanup)
            spool.roll(result, oncleanup as SpoolCleanup<unknown>)
        return result
    }
}