/** * Transaction types for distributed ACID-like operations * * Note: Elasticsearch doesn't natively support ACID transactions across multiple * documents. This implementation provides transaction-like semantics using: * - Optimistic concurrency control (seq_no/primary_term) * - Two-phase operations (prepare/commit) * - Compensation-based rollback * - Transaction state tracking */ /** * Transaction isolation level */ export type TransactionIsolationLevel = | 'read_uncommitted' | 'read_committed' | 'repeatable_read' | 'serializable'; /** * Transaction state */ export type TransactionState = | 'active' | 'preparing' | 'prepared' | 'committing' | 'committed' | 'rolling_back' | 'rolled_back' | 'failed'; /** * Transaction locking strategy */ export type LockingStrategy = 'optimistic' | 'pessimistic'; /** * Transaction operation type */ export type TransactionOperationType = 'read' | 'create' | 'update' | 'delete'; /** * Transaction operation */ export interface TransactionOperation { /** Operation type */ type: TransactionOperationType; /** Target index */ index: string; /** Document ID */ id: string; /** Document data (for create/update) */ document?: T; /** Original document (for rollback) */ originalDocument?: T; /** Version info for optimistic locking */ version?: { seqNo: number; primaryTerm: number; }; /** Timestamp when operation was added */ timestamp: Date; /** Whether operation has been executed */ executed: boolean; /** Whether operation has been committed */ committed: boolean; /** Compensation operation for rollback */ compensation?: TransactionOperation; } /** * Transaction configuration */ export interface TransactionConfig { /** Transaction ID (auto-generated if not provided) */ id?: string; /** Isolation level */ isolationLevel?: TransactionIsolationLevel; /** Locking strategy */ lockingStrategy?: LockingStrategy; /** Transaction timeout in milliseconds */ timeout?: number; /** Enable automatic rollback on error */ autoRollback?: boolean; /** Maximum retry attempts for conflicts */ maxRetries?: number; /** Retry delay in milliseconds */ retryDelay?: number; /** Enable strict ordering of operations */ strictOrdering?: boolean; /** Metadata for tracking */ metadata?: Record; } /** * Transaction context */ export interface TransactionContext { /** Transaction ID */ id: string; /** Current state */ state: TransactionState; /** Configuration */ config: Required; /** Operations in this transaction */ operations: TransactionOperation[]; /** Read set (for repeatable read isolation) */ readSet: Map; /** Write set (for conflict detection) */ writeSet: Set; /** Transaction start time */ startTime: Date; /** Transaction end time */ endTime?: Date; /** Error if transaction failed */ error?: Error; /** Number of retry attempts */ retryAttempts: number; } /** * Transaction result */ export interface TransactionResult { /** Whether transaction succeeded */ success: boolean; /** Transaction ID */ transactionId: string; /** Final state */ state: TransactionState; /** Number of operations executed */ operationsExecuted: number; /** Number of operations committed */ operationsCommitted: number; /** Number of operations rolled back */ operationsRolledBack: number; /** Transaction duration in milliseconds */ duration: number; /** Error if transaction failed */ error?: { message: string; type: string; operation?: TransactionOperation; }; /** Metadata */ metadata?: Record; } /** * Transaction statistics */ export interface TransactionStats { /** Total transactions started */ totalStarted: number; /** Total transactions committed */ totalCommitted: number; /** Total transactions rolled back */ totalRolledBack: number; /** Total transactions failed */ totalFailed: number; /** Total operations executed */ totalOperations: number; /** Total conflicts encountered */ totalConflicts: number; /** Total retries */ totalRetries: number; /** Average transaction duration */ avgDuration: number; /** Average operations per transaction */ avgOperationsPerTransaction: number; /** Success rate */ successRate: number; /** Active transactions count */ activeTransactions: number; } /** * Lock information */ export interface LockInfo { /** Document key (index:id) */ key: string; /** Transaction ID holding the lock */ transactionId: string; /** Lock type */ type: 'read' | 'write'; /** Lock acquired at */ acquiredAt: Date; /** Lock expires at */ expiresAt: Date; /** Lock metadata */ metadata?: Record; } /** * Conflict resolution strategy */ export type ConflictResolutionStrategy = | 'abort' // Abort transaction | 'retry' // Retry operation | 'skip' // Skip conflicting operation | 'force' // Force operation (last write wins) | 'merge'; // Attempt to merge changes /** * Conflict information */ export interface ConflictInfo { /** Operation that conflicted */ operation: TransactionOperation; /** Conflicting transaction ID */ conflictingTransactionId?: string; /** Expected version */ expectedVersion?: { seqNo: number; primaryTerm: number; }; /** Actual version */ actualVersion?: { seqNo: number; primaryTerm: number; }; /** Conflict detected at */ detectedAt: Date; } /** * Transaction manager configuration */ export interface TransactionManagerConfig { /** Default isolation level */ defaultIsolationLevel?: TransactionIsolationLevel; /** Default locking strategy */ defaultLockingStrategy?: LockingStrategy; /** Default transaction timeout */ defaultTimeout?: number; /** Enable automatic cleanup of expired transactions */ enableCleanup?: boolean; /** Cleanup interval in milliseconds */ cleanupInterval?: number; /** Maximum concurrent transactions */ maxConcurrentTransactions?: number; /** Conflict resolution strategy */ conflictResolution?: ConflictResolutionStrategy; /** Enable transaction logging */ enableLogging?: boolean; /** Enable transaction metrics */ enableMetrics?: boolean; } /** * Savepoint for nested transactions */ export interface Savepoint { /** Savepoint name */ name: string; /** Operations count at savepoint */ operationsCount: number; /** Created at */ createdAt: Date; /** Metadata */ metadata?: Record; } /** * Transaction callback functions */ export interface TransactionCallbacks { /** Called before transaction begins */ onBegin?: (context: TransactionContext) => Promise | void; /** Called before operation executes */ onBeforeOperation?: (operation: TransactionOperation) => Promise | void; /** Called after operation executes */ onAfterOperation?: (operation: TransactionOperation) => Promise | void; /** Called on conflict */ onConflict?: (conflict: ConflictInfo) => Promise | ConflictResolutionStrategy; /** Called before commit */ onBeforeCommit?: (context: TransactionContext) => Promise | void; /** Called after commit */ onAfterCommit?: (result: TransactionResult) => Promise | void; /** Called before rollback */ onBeforeRollback?: (context: TransactionContext) => Promise | void; /** Called after rollback */ onAfterRollback?: (result: TransactionResult) => Promise | void; /** Called on transaction error */ onError?: (error: Error, context: TransactionContext) => Promise | void; }