UNPKG

@travetto/runtime

Version:

Runtime for travetto applications.

360 lines (313 loc) 16.9 kB
<!-- This file was generated by @travetto/doc and should not be modified directly --> <!-- Please modify https://github.com/travetto/travetto/tree/main/module/runtime/DOC.tsx and execute "npx trv doc" to rebuild --> # Runtime ## Runtime for travetto applications. **Install: @travetto/runtime** ```bash npm install @travetto/runtime # or yarn add @travetto/runtime ``` Runtime is the foundation of all [Travetto](https://travetto.dev) applications. It is intended to be a minimal application set, as well as support for commonly shared functionality. It has support for the following key areas: * Runtime Context * Environment Support * Standard Error Support * Console Management * Resource Access * JSON Utilities * Common Utilities * Time Utilities * Process Execution * Shutdown Management * Path behavior ## Runtime Context While running any code within the framework, there are common patterns/goals for interacting with the underlying code repository. These include: * Determining attributes of the running environment (e.g., name, debug information, production flags) * Resolving paths within the workspace (e.g. standard, tooling, resourcing, modules) **Code: Runtime Shape** ```typescript class $Runtime { constructor(idx: ManifestIndex, resourceOverrides?: Record<string, string>); /** The role we are running as */ get role(): Role; /** Are we in production mode */ get production(): boolean; /** Are we in development mode */ get localDevelopment(): boolean; /** Get debug value */ get debug(): false | string; /** Manifest main */ get main(): ManifestContext['main']; /** Manifest workspace */ get workspace(): ManifestContext['workspace']; /** Are we running from a mono-root? */ get monoRoot(): boolean; /** Main source path */ get mainSourcePath(): string; /** Produce a workspace relative path */ workspaceRelative(...parts: string[]): string; /** Strip off the workspace path from a file */ stripWorkspacePath(full: string): string; /** Produce a workspace path for tooling, with '@' being replaced by node_module/name folder */ toolPath(...parts: string[]): string; /** Resolve single module path */ modulePath(modulePath: string, overrides?: Record<string, string>): string; /** Resolve resource paths */ resourcePaths(paths: string[] = []): string[]; /** Get source for function */ getSourceFile(handle: Function): string; /** Get import for function */ getImport(handle: Function): string; /** Import from a given path */ async importFrom<T = unknown>(location?: string): Promise<T>; /** Get an install command for a given npm module */ getInstallCommand(pkg: string, production = false): string; } ``` ### Class and Function Metadata For the framework to work properly, metadata needs to be collected about files, classes and functions to uniquely identify them, with support for detecting changes during live reloads. To achieve this, every `class` is decorated with metadata, including methods, line numbers, and ultimately a unique id stored at `Ⲑid`. ## Environment Support The functionality we support for testing and retrieving environment information for known environment variables. They can be accessed directly on the [Env](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L114) object, and will return a scoped [EnvProp](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L8), that is compatible with the property definition. E.g. only showing boolean related fields when the underlying flag supports `true` or `false` **Code: Base Known Environment Flags** ```typescript interface EnvData { /** * The node environment we are running in * @default development */ NODE_ENV: 'development' | 'production'; /** * Outputs all console.debug messages, defaults to off */ DEBUG: boolean | string; /** * The role we are running as, allows access to additional files from the manifest during runtime. */ TRV_ROLE: Role; /** * The folders to use for resource lookup */ TRV_RESOURCES: string[]; /** * Resource path overrides * @private */ TRV_RESOURCE_OVERRIDES: Record<string, string>; /** * The max time to wait for shutdown to finish after initial SIGINT, * @default 2s */ TRV_SHUTDOWN_WAIT: TimeSpan | number; /** * The desired runtime module */ TRV_MODULE: string; /** * The location of the manifest file * @default undefined */ TRV_MANIFEST: string; /** * trvc log level */ TRV_BUILD: 'none' | 'info' | 'debug' | 'error' | 'warn'; /** * Should break on first line of a method when using the @DebugBreak decorator * @default false */ TRV_DEBUG_BREAK: boolean; } ``` ### Environment Property For a given [EnvProp](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L8), we support the ability to access different properties as a means to better facilitate environment variable usage. **Code: EnvProp Shape** ```typescript export class EnvProp<T> { readonly key: string; constructor(key: string) { this.key = key; } /** Remove value */ clear(): void; /** Export value */ export(value?: T | undefined | null): Record<string, string>; /** Read value as string */ get value(): string | undefined; /** Read value as list */ get list(): string[] | undefined; /** Read value as object */ get object(): Record<string, string> | undefined; /** Add values to list */ add(...items: string[]): void; /** Read value as int */ get int(): number | undefined; /** Read value as boolean */ get bool(): boolean | undefined; /** Determine if the underlying value is truthy */ get isTrue(): boolean; /** Determine if the underlying value is falsy */ get isFalse(): boolean; /** Determine if the underlying value is set */ get isSet(): boolean; } ``` ## Standard Error Support While the framework is 100 % compatible with standard `Error` instances, there are cases in which additional functionality is desired. Within the framework we use [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L26) (or its derivatives) to represent framework errors. This class is available for use in your own projects. Some of the additional benefits of using this class is enhanced error reporting, as well as better integration with other modules (e.g. the [Web API](https://github.com/travetto/travetto/tree/main/module/web#readme "Declarative support for creating Web Applications") module and HTTP status codes). The [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L26) takes in a message, and an optional payload and / or error classification. The currently supported error classifications are: * `general` - General purpose errors * `system` - Synonym for `general` * `data` - Data format, content, etc are incorrect. Generally correlated to bad input. * `permission` - Operation failed due to lack of permissions * `auth` - Operation failed due to lack of authentication * `missing` - Resource was not found when requested * `timeout` - Operation did not finish in a timely manner * `unavailable` - Resource was unresponsive ## Console Management This module provides logging functionality, built upon [console](https://nodejs.org/api/console.html) operations. The supported operations are: * `console.error` which logs at the `ERROR` level * `console.warn` which logs at the `WARN` level * `console.info` which logs at the `INFO` level * `console.debug` which logs at the `DEBUG` level * `console.log` which logs at the `INFO` level **Note**: All other console methods are excluded, specifically `trace`, `inspect`, `dir`, `time`/`timeEnd` ### How Logging is Instrumented All of the logging instrumentation occurs at transpilation time. All `console.*` methods are replaced with a call to a globally defined variable that delegates to the [ConsoleManager](https://github.com/travetto/travetto/tree/main/module/runtime/src/console.ts#L43). This module, hooks into the [ConsoleManager](https://github.com/travetto/travetto/tree/main/module/runtime/src/console.ts#L43) and receives all logging events from all files compiled by the [Travetto](https://travetto.dev). A sample of the instrumentation would be: **Code: Sample logging at various levels** ```typescript export function work() { console.debug('Start Work'); try { 1 / 0; } catch (error) { console.error('Divide by zero', { error }); } console.debug('End Work'); } ``` **Code: Sample After Transpilation** ```javascript import * as Δfunction from "@travetto/runtime/src/function.js"; import * as Δconsole from "@travetto/runtime/src/console.js"; const Δm_1 = ["@travetto/runtime", "doc/transpile.ts"]; export function work() { Δconsole.log({ level: "debug", import: Δm_1, line: 2, scope: "work", args: ['Start Work'] }); try { 1 / 0; } catch (error) { Δconsole.log({ level: "error", import: Δm_1, line: 7, scope: "work", args: ['Divide by zero', { error }] }); } Δconsole.log({ level: "debug", import: Δm_1, line: 9, scope: "work", args: ['End Work'] }); } Δfunction.registerFunction(work, Δm_1, { hash: 159357293, lines: [1, 10, 2] }); ``` #### Filtering Debug The `debug` messages can be filtered using the patterns from the [debug](https://www.npmjs.com/package/debug). You can specify wild cards to only `DEBUG` specific modules, folders or files. You can specify multiple, and you can also add negations to exclude specific packages. **Terminal: Sample environment flags** ```bash # Debug $ DEBUG=-@travetto/model npx trv run app $ DEBUG=-@travetto/registry npx trv run app $ DEBUG=@travetto/web npx trv run app $ DEBUG=@travetto/*,-@travetto/model npx trv run app ``` Additionally, the logging framework will merge [debug](https://www.npmjs.com/package/debug) into the output stream, and supports the standard usage **Terminal: Sample environment flags for standard usage** ```bash # Debug $ DEBUG=express:*,@travetto/web npx trv run web ``` ## Resource Access The primary access patterns for resources, is to directly request a file, and to resolve that file either via file-system look up or leveraging the [Manifest](https://github.com/travetto/travetto/tree/main/module/manifest#readme "Support for project indexing, manifesting, along with file watching")'s data for what resources were found at manifesting time. The [FileLoader](https://github.com/travetto/travetto/tree/main/module/runtime/src/file-loader.ts#L12) allows for accessing information about the resources, and subsequently reading the file as text/binary or to access the resource as a `Readable` stream. If a file is not found, it will throw an [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L26) with a category of 'notfound'. The [FileLoader](https://github.com/travetto/travetto/tree/main/module/runtime/src/file-loader.ts#L12) also supports tying itself to [Env](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L114)'s `TRV_RESOURCES` information on where to attempt to find a requested resource. ## JSON Utilities The framework provides utilities for working with JSON data. This module provides methods for reading and writing JSON files, as well as serializing and deserializing JSON data. It also provides support for working with Base64 encoded data for web safe transfer. The primary goal is ease of use, but also a centralized location for performance and security improvements over time. * `parseSafe(input: string | Buffer)` parses JSON safely from a string or Buffer. * `stringifyBase64(value: any)` encodes a JSON value as a base64 encoded string. * `parseBase64(input: string)` decodes a JSON value from a base64 encoded string. * `readFile(file: string)` reads a JSON file asynchronously. * `readFileSync(file: string, onMissing?: any)` reads a JSON file synchronously. ## Common Utilities Common utilities used throughout the framework. Currently [Util](https://github.com/travetto/travetto/tree/main/module/runtime/src/util.ts#L11) includes: * `uuid(len: number)` generates a simple uuid for use within the application. * `allowDenyMatcher(rules[])` builds a matching function that leverages the rules as an allow/deny list, where order of the rules matters. Negative rules are prefixed by '!'. * `hash(text: string, size?: number)` produces a full sha512 hash. * `resolvablePromise()` produces a `Promise` instance with the `resolve` and `reject` methods attached to the instance. This is extremely useful for integrating promises into async iterations, or any other situation in which the promise creation and the execution flow don't always match up. **Code: Sample makeTemplate Usage** ```typescript const tpl = makeTemplate((name: 'age'|'name', value) => `**${name}: ${value}**`); tpl`{{age:20}} {{name: 'bob'}}</>; // produces '**age: 20** **name: bob**' ``` ## Time Utilities [TimeUtil](https://github.com/travetto/travetto/tree/main/module/runtime/src/time.ts#L20) contains general helper methods, created to assist with time-based inputs via environment variables, command line interfaces, and other string-heavy based input. **Code: Time Utilities** ```typescript export class TimeUtil { /** * Test to see if a string is valid for relative time * @param val */ static isTimeSpan(value: string): value is TimeSpan; /** * Returns time units convert to ms * @param amount Number of units to extend * @param unit Time unit to extend ('ms', 's', 'm', 'h', 'd', 'w', 'y') */ static asMillis(amount: Date | number | TimeSpan, unit?: TimeUnit): number; /** * Returns the time converted to seconds * @param date The date to convert */ static asSeconds(date: Date | number | TimeSpan, unit?: TimeUnit): number; /** * Returns the time converted to a Date * @param date The date to convert */ static asDate(date: Date | number | TimeSpan, unit?: TimeUnit): Date; /** * Resolve time or span to possible time */ static fromValue(value: Date | number | string | undefined): number | undefined; /** * Returns a new date with `amount` units into the future * @param amount Number of units to extend * @param unit Time unit to extend ('ms', 's', 'm', 'h', 'd', 'w', 'y') */ static fromNow(amount: number | TimeSpan, unit: TimeUnit = 'ms'): Date; /** * Returns a pretty timestamp * @param time Time in milliseconds */ static asClock(time: number): string; } ``` ## Process Execution [ExecUtil](https://github.com/travetto/travetto/tree/main/module/runtime/src/exec.ts#L41) exposes `getResult` as a means to wrap [child_process](https://nodejs.org/api/child_process.html)'s process object. This wrapper allows for a promise-based resolution of the subprocess with the ability to capture the stderr/stdout. A simple example would be: **Code: Running a directory listing via ls** ```typescript import { spawn } from 'node:child_process'; import { ExecUtil } from '@travetto/runtime'; export async function executeListing() { const final = await ExecUtil.getResult(spawn('ls')); console.log('Listing', { lines: final.stdout.split('\n') }); } ``` ## Shutdown Management Another key lifecycle is the process of shutting down. The framework provides centralized functionality for running operations on graceful shutdown. Primarily used by the framework for cleanup operations, this provides a clean interface for registering shutdown handlers. The code intercepts `SIGTERM` and `SIGUSR2`, with a default threshold of 2 seconds. These events will start the shutdown process, but also clear out the pending queue. If a kill signal is sent again, it will complete immediately. As a registered shutdown handler, you can do. **Code: Registering a shutdown handler** ```typescript import { ShutdownManager } from '@travetto/runtime'; export function registerShutdownHandler() { ShutdownManager.signal.addEventListener('abort', () => { // Do important work, the framework will wait until all async // operations are completed before finishing shutdown }); } ``` ## Path Behavior To ensure consistency in path usage throughout the framework, imports pointing at `node:path` and `path` are rewritten at compile time. These imports are pointing towards [Manifest](https://github.com/travetto/travetto/tree/main/module/manifest#readme "Support for project indexing, manifesting, along with file watching")'s `path` implementation. This allows for seamless import/usage patterns with the reliability needed for cross platform support.