All files / lib/resources main.ts

100% Statements 398/398
94.73% Branches 54/57
100% Functions 22/22
100% Lines 398/398

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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 3981x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1515x 1x 1x 1514x 1514x 1514x 1514x 1514x 1514x 1514x 1514x 1514x 1514x 20x 20x 20x 20x 20x 20x 242832x 1x 1x 242831x 242831x 242831x 20x 20x 20x 20x 20x 20x 237579x 237579x 1x 1x 237578x 237578x 237578x 20x 20x 20x 20x 20x 20x 618x 618x 1x 1x 617x 617x 617x 20x 20x 20x 20x 20x 20x 3745x 3745x 1x 1x 3744x 3744x 3744x 20x 20x 20x 20x 20x 20x 502x 502x 1x 1x 501x 501x 501x 20x 20x 20x 20x 20x 20x 386x 386x 1x 1x 385x 385x 385x 20x 20x 20x 20x 20x 20x 20x 20x 98070x 98070x 98070x 98070x 98070x 98070x 1x 98070x 98070x 97451x 98070x 98070x 539x 98070x 98070x 70x 98070x 98070x 9x 98070x 98070x 98070x 20x 20x 20x 20x 20x 20x 20x 20x 108438x 108438x 91188x 91188x 108438x 108438x 1931x 1931x 108438x 108438x 1609x 1609x 108438x 108438x 108438x 20x 20x 20x 20x 20x 20x 20x 20x 706x 706x 20x 20x 20x 20x 20x 20x 20x 2x 2x 2x 2x 1x 1x 2x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 100x 100x 100x 100x 100x 1x 1x 90x 90x 100x 9x 9x 90x 90x 90x 90x 90x 90x 90x 90x 20x 20x 20x 20x 20x 20x 20x 90x 3x 3x 87x 87x 87x 87x 90x 90x 90x 90x 90x 1x 1x 90x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x
import PackageData from '../../../package.json' with { type: 'json' };
import {RESOURCES_ERR} from "../../app/error/error-codes.js";
import {iCPSError} from "../../app/error/error.js";
import {iCPSAppOptions} from "../../app/factory.js";
import {EventManager, ListenerFunction} from "./event-manager.js";
import {iCPSEvent, iCPSEventLog} from "./events-types.js";
import {NetworkManager} from "./network-manager.js";
import {ResourceManager} from "./resource-manager.js";
import {StateManager} from './state-manager.js';
import {Validator} from "./validator.js";
import {readFileSync, statSync} from 'fs'
import {jsonc} from "jsonc";
import {FILE_ENCODING, LibraryLockOwner} from "./resource-types.js";
 
/* eslint-disable @typescript-eslint/no-namespace */
 
/**
 * This namespace handles the static access to the singleton functions of the ResourceManager, NetworkManager, Validator and EventManager
 */
export namespace Resources {
    /**
     * The singleton instances of the shared resources
     */
    export let _instances: Resources.Types.Instances;
 
    /**
     * Static package info
     */
    export const PackageInfo: Resources.Types.PackageInfo = {
        name: PackageData.name,
        version: PackageData.version,
        description: PackageData.description,
    };
 
    /**
     * Prepares the global singleton instances. This includes the ResourceManager, NetworkManager, Validator and EventManager.
     * This function should only be called once.
     * @param appOptions - The parsed app options
     * @returns The singleton instances
     * @throws If the function is called with an already initiated singleton
     */
    export function setup(appOptions: iCPSAppOptions): Resources.Types.Instances {
        if (_instances) {
            throw new iCPSError(RESOURCES_ERR.ALREADY_INITIATED);
        }
 
        _instances = {} as Resources.Types.Instances; // Creating one-by one, so they are available as soon as possible
        _instances.event = new EventManager();
        _instances.state = new StateManager();
        _instances.validator = new Validator();
        _instances.manager = new ResourceManager(appOptions);
        _instances.network = new NetworkManager(appOptions);
 
        return _instances;
    }
 
    /**
     * @returns The singleton instances of the shared resources
     * @throws If the function is called before the singleton is initiated
     */
    export function instances(): Resources.Types.Instances {
        if (!_instances) {
            throw new iCPSError(RESOURCES_ERR.NOT_INITIATED);
        }
 
        return _instances;
    }
 
    /**
     * @returns The singleton instances of the shared event manager
     * @throws If the function is called before the singleton is initiated
     */
    export function event(): EventManager {
        const {event} = instances();
        if (!event) {
            throw new iCPSError(RESOURCES_ERR.EVENT_NOT_INITIATED);
        }
 
        return event;
    }
 
    /**
     * @returns The singleton instances of the shared network manager
     * @throws If the function is called before the singleton is initiated
     */
    export function network(): NetworkManager {
        const {network} = instances();
        if (!network) {
            throw new iCPSError(RESOURCES_ERR.NETWORK_NOT_INITIATED);
        }
 
        return network;
    }
 
    /**
     * @returns The singleton instances of the shared resource manager
     * @throws If the function is called before the singleton is initiated
     */
    export function manager(): ResourceManager {
        const {manager} = instances();
        if (!manager) {
            throw new iCPSError(RESOURCES_ERR.RESOURCE_NOT_INITIATED);
        }
 
        return manager;
    }
 
    /**
     * @returns The singleton instances of the shared validator
     * @throws If the function is called before the singleton is initiated
     */
    export function validator(): Validator {
        const {validator} = instances();
        if (!validator) {
            throw new iCPSError(RESOURCES_ERR.VALIDATOR_NOT_INITIATED);
        }
 
        return validator;
    }
 
    /**
     * @returns THe Singleton instance of the shared state
     * @throws If the function is called before the singleton is initiated
     */
    export function state(): StateManager {
        const {state} = instances()
        if(!state) {
            throw new iCPSError(RESOURCES_ERR.STATE_NOT_INITIATED);
        }
 
        return state;
    }
 
    /**
     * Returns a logger interface, that allows emitting log events to the event bus by providing a source object
     * Used to log messages associated to the source object
     * @param source - The source of the log message - either an object or a string
     * @returns The logger interface
     */
    export function logger(source: any | string): Resources.Types.Logger {
        const format = function (...args: unknown[]): string {
            return args.map(arg => String(arg)).join(` `);
        };
 
        return {
            log(...args: any[]) {
                Resources.event().emit(iCPSEventLog.INFO, source, format(args));
            },
            debug(...args: any[]) {
                Resources.event().emit(iCPSEventLog.DEBUG, source, format(args));
            },
            info(...args: any[]) {
                Resources.event().emit(iCPSEventLog.INFO, source, format(args));
            },
            warn(...args: any[]) {
                Resources.event().emit(iCPSEventLog.WARN, source, format(args));
            },
            error(...args: any[]) {
                Resources.event().emit(iCPSEventLog.ERROR, source, format(args));
            },
        };
    }
 
    /**
     * Returns an event interface, that allows listening to events emitted on the event bus, while binding the listener to the registry
     * Used to manage listeners for the listener object
     * @param listenerObject - The source of the registration request, used to track the listeners and enable cleanup
     * @returns The events interface
     */
    export function events(listenerObject: any): Resources.Types.Events {
        return {
            on(event: iCPSEvent, listener: ListenerFunction) {
                Resources.event().on(listenerObject, event, listener);
                return Resources.events(listenerObject); // Returning for chaining
            },
            once(event: iCPSEvent, listener: ListenerFunction) {
                Resources.event().once(listenerObject, event, listener);
                return Resources.events(listenerObject); // Returning for chaining
            },
            removeListeners(event?: iCPSEvent) {
                Resources.event().removeListenersFromRegistry(listenerObject, event);
                return Resources.events(listenerObject); // Returning for chaining
            },
        };
    }
 
    /**
     * Emits an event on the central event bus
     * @param event - The event to emit
     * @param args - Optional arguments to pass to the event
     * @returns True if the event had listeners
     */
    export function emit(event: iCPSEvent, ...args: any[]): boolean {
        return Resources.event().emit(event, ...args);
    }
 
    /**
     * Can be used to check if a process is running
     * @param pid - The process id to check
     * @returns True if the process is running or the user does not have the necessary permissions to check this, false otherwise
     */
    export function pidIsRunning(pid: number): boolean {
        try {
            process.kill(pid, 0);
            return true;
        } catch (e) {
            return (e as NodeJS.ErrnoException).code === `EPERM`;
        }
    }
 
    /**
     * Information about the library's locking status
     */
    export type LockStat = {
        /**
         * The path to the lock file
         */
        lockFilePath: string,
        /**
         * True, if the lock file exists
         */
        lockFileExists: boolean,
        /**
         * The process holding the lock - undefined, if the lock file does not exist. If the content of the lock file cannot be parsed, the pid is NaN.
         */
        owner?: LibraryLockOwner,
        /**
         * The time of the last heartbeat (modification time of the lock file) in ms since epoch - NaN, if the lock file does not exist
         */
        lastHeartbeat: number,
    }
 
    /**
     * Returns information on the library's locking status
     * @returns Information about the lock file path, its existence, the locking process and its last heartbeat
     */
    export function getLockStat(): LockStat {
        const {lockFilePath} = Resources.manager();
        let lastHeartbeat: number;
        try {
            const stat = statSync(lockFilePath);
            if (!stat.isFile()) {
                return {lockFilePath, lockFileExists: false, lastHeartbeat: NaN};
            }
 
            lastHeartbeat = stat.mtimeMs;
        } catch {
            return {lockFilePath, lockFileExists: false, lastHeartbeat: NaN};
        }
 
        return {
            lockFilePath,
            lockFileExists: true,
            owner: parseLockOwner(readFileSync(lockFilePath, FILE_ENCODING)),
            lastHeartbeat,
        };
    }
 
    /**
     * Parses the content of the lock file
     * @param content - The content of the lock file - either the serialized lock owner or only the process id (as written by previous versions)
     * @returns The lock owner - with a pid of NaN, if the content cannot be parsed
     */
    function parseLockOwner(content: string): LibraryLockOwner {
        if (/^\s*\d+\s*$/.test(content)) {
            return {pid: parseInt(content, 10)};
        }
 
        try {
            const owner = jsonc.parse(content) as Partial<LibraryLockOwner>;
            return {
                instance: typeof owner?.instance === `string` ? owner.instance : undefined,
                pid: typeof owner?.pid === `number` ? owner.pid : NaN,
                hostname: typeof owner?.hostname === `string` ? owner.hostname : undefined,
            };
        } catch {
            return {pid: NaN};
        }
    }
 
    /**
     * Typing namespace
     */
    export namespace Types {
        /**
         * Type holding all the singleton instances
         */
        export type Instances = {
            /**
             * The resource manager instance
             */
            manager: ResourceManager,
            /**
             * The network manager instance
             */
            network: NetworkManager,
            /**
             * The validator instance
             */
            validator: Validator,
            /**
             * The event manager instance
             */
            event: EventManager,
            /**
             * THe state manager instance
             */
            state: StateManager
        }
 
        /**
         * Package Metadata
         */
        export type PackageInfo = {
            /**
             * The name of this package
             */
            name: string,
            /**
             * The version of this package
             */
            version: string,
            /**
             * A short description of this package
             */
            description: string,
        }
        /**
        * Interface to logger event bus, with a source bound to it
        */
        export type Logger = {
            /**
            * Logs a message to the event bus
            * @param args - The arguments to log
            */
            log: (...args: any[]) => void,
            /**
            * Logs a debug message to the event bus
            * @param args - The arguments to log
            */
            debug: (...args: any[]) => void,
            /**
            * Logs an info message to the event bus
            * @param args - The arguments to log
            */
            info: (...args: any[]) => void,
            /**
            * Logs a warn message to the event bus
            * @param args - The arguments to log
            */
            warn: (...args: any[]) => void,
            /**
            * Logs an error message to the event bus
            * @param args - The arguments to log
            */
            error: (...args: any[]) => void,
        }
 
        /**
        * Interface to listener functions of the event bus, with a listener bound to it
        */
        export type Events = {
            /**
            * Registers an event listener to the event bus
            * @param event - The event to listen to
            * @param listener - The listener function to call upon the event
            * @returns This instance for chaining
            */
            on: (event: iCPSEvent, listener: ListenerFunction) => Resources.Types.Events,
            /**
            * Registers an one-time event listener to the event bus
            * @param event - The event to listen to
            * @param listener - The listener function to call upon the event
            * @returns This instance for chaining
            */
            once: (event: iCPSEvent, listener: ListenerFunction) => Resources.Types.Events,
            /**
            * Removes all listeners from the source from the event bus
            * @param event - Optional event to remove listeners for - otherwise all will be removed
            */
            removeListeners: (event?: iCPSEvent) => Resources.Types.Events,
        }
 
        /**
        * Possible regions for this tool to operate in
        */
        export enum Region {
        /**
         * Will use icloud.com
         */
            WORLD = `world`,
            /**
         * Will use icloud.com.cn
         */
            CHINA = `china`,
        }
    }
}