chrono-forge
Version:
A comprehensive framework for building resilient Temporal workflows, advanced state management, and real-time streaming activities in TypeScript. Designed for a seamless developer experience with powerful abstractions, dynamic orchestration, and full cont
178 lines (177 loc) • 7.33 kB
TypeScript
import EventEmitter from 'eventemitter3';
import { EntitiesState } from './entities';
import { EntityAction } from './actions';
import { LRUCacheWithDelete } from 'mnemonist';
import { Queue } from 'typescript-algos';
/**
* Represents the detailed diff structure for EntitiesState
* Contains added, updated, and deleted entity collections
*/
export type EntitiesStateDetailedDiff = {
added: EntitiesState;
updated: EntitiesState;
deleted: EntitiesState;
};
/**
* Represents a queue item containing an entity action and optional origin
* Used for tracking actions in the processing queue
*/
export type QueueItem = {
action: EntityAction;
origin?: string;
};
/**
* StateManager class manages application state and entity relationships
* using a singleton pattern with instance management.
* Extends EventEmitter to provide state change notifications.
* Handles state updates, entity queries, and relationship management.
*/
export declare class StateManager extends EventEmitter {
private readonly _instanceId;
/**
* Gets the instance ID of this StateManager
* @returns The unique identifier for this StateManager instance
*/
get instanceId(): string;
/**
* Private constructor for singleton pattern
* @param _instanceId - Unique identifier for this StateManager instance
*/
private constructor();
/**
* Gets or creates a StateManager instance for the given ID
* Implements the singleton pattern with multiple named instances
* @param instanceId - Unique identifier for the StateManager instance
* @returns StateManager instance for the given ID
* @throws Error if instanceId is not provided
*/
static getInstance(instanceId: string): StateManager;
private static instances;
/**
* Indicates whether the StateManager is currently processing changes
* @returns Boolean indicating if state changes are being processed
*/
private _processing;
get processing(): boolean;
/**
* Gets the current entity state
* @returns The current EntitiesState object or empty object if not initialized
*/
private _state;
get state(): EntitiesState;
/**
* Sets the current entity state
* @param state - The new EntitiesState to set
*/
set state(state: EntitiesState);
/**
* Updates the state and emits change events if necessary
* Performs diff calculation and triggers event emission for changed entities
* @param newState - The new state to set
* @param previousState - Previous state before changes
* @param origins - Set of origin identifiers for the changes
*/
private handleStateChange;
/**
* Sets a new state by dispatching a setState action
* Avoids unnecessary updates if the state hasn't changed
* @param newState - The new state to set
*/
setState(newState: EntitiesState): Promise<void>;
/**
* LRU cache for storing entity data with delete capability
* Used to improve performance by caching frequently accessed entities
*/
readonly cache: LRUCacheWithDelete<string, Record<string, any>>;
/**
* Queue of pending entity actions to be processed
*/
private readonly _queue;
/**
* Gets the current action queue
* @returns Array of pending QueueItems
*/
get queue(): Queue<QueueItem>;
/**
* Dispatches entity actions either synchronously or asynchronously
* Processes actions immediately if sync is true, otherwise queues them
* @param actions - The entity action(s) to dispatch (can be single action or array)
* @param sync - Whether to process the action(s) immediately (default: true)
* @param origin - Optional origin identifier for the action(s)
* @returns Promise that resolves when processing is complete
*/
dispatch(actions: EntityAction | EntityAction[], sync?: boolean, origin?: string): Promise<void>;
/**
* Processes queued changes or provided items
* Applies actions to the state and handles state changes
* Includes safeguards against excessive processing time
* @param items - Optional array of QueueItems to process instead of the queue
* @returns Promise that resolves when processing is complete
*/
processChanges(items?: QueueItem[]): Promise<void>;
/**
* Emits state change events for all affected entities
* Supports wildcard event patterns and handles event propagation
* @param differences - Detailed diff of state changes
* @param previousState - Previous state before changes
* @param newState - New state after changes
* @param origins - Array of origin identifiers for the changes
* @returns Promise that resolves when all events have been emitted
*/
private emitStateChangeEvents;
/**
* Queries an entity by name and ID, optionally denormalizing the data
* Resolves entity references and creates proxies for denormalized entities
* @param entityName - Name of the entity type
* @param id - ID of the entity
* @param denormalizeData - Whether to denormalize the entity data (default: true)
* @returns The requested entity (denormalized if specified) or null if not found
*/
query(entityName: string, id: string, denormalizeData?: boolean): any;
/**
* Clears all entities from the state
* Dispatches a clearEntities action with this instance as the origin
*/
clear(): void;
/**
* Emits events asynchronously to all registered listeners
* Handles errors in event listeners to prevent propagation
* @param event - The event name to emit
* @param args - Arguments to pass to the listeners
* @returns Promise that resolves to true if there were listeners, false otherwise
*/
protected emitAsync(event: string, ...args: any[]): Promise<boolean>;
/**
* Checks if an entity is referenced by any other entities in the state
* Traverses the relationship map to find references
* @param entityName - Name of the entity type to check
* @param entityId - ID of the entity to check
* @param ignoreReference - Optional reference to ignore during the check
* @param checkedEntities - Set of already checked entities to prevent circular references
* @returns Boolean indicating if the entity is referenced
*/
isEntityReferenced(entityName: string, entityId: string, ignoreReference?: {
entityName: string;
fieldName: string;
}, checkedEntities?: Set<string>): boolean;
/**
* Cleans up this StateManager instance by clearing cache, state, and removing event listeners.
*
* This method should be called when a workflow completes or during continueAsNew
* to ensure that state data doesn't persist between workflow executions in the
* shared VM environment.
*
* ## Cleanup actions:
* - Clears the LRU cache
* - Resets the state to an empty object
* - Removes all event listeners from this instance
* - Clears the action queue
*/
cleanup(): void;
/**
* Clears the StateManager singleton instances map.
* This is useful for full system resets or testing.
*/
static clearInstances(): void;
}
export default StateManager;