import { Repository, Entity } from 'redis-om'; import { ConnectionOptions } from './connection'; import { StorageSchema as OldStorageSchema, SchemaConfig } from './schema'; import { StorageSchema as NewStorageSchema, ValidationResult } from './storage-schema'; import { UpdateOptions } from './optimistic-lock'; import { BatchOptions } from './batch-operations'; import { SchemaVersionManager } from './schema-versioning'; import { StorageVersionManager, StorageVersionBatch } from './storage-version-manager'; import { ExportOptions, ImportOptions, ExportMetadata, ImportResult } from './export-import-manager'; export interface StorageOptions extends ConnectionOptions { prefix?: string; idGenerator?: () => string; useJSON?: boolean; enableOptimisticLocking?: boolean; undefinedBehavior?: 'delete' | 'ignore'; enableChangeTracking?: boolean; } export interface QueryOptions { limit?: number; offset?: number; sortBy?: string; sortOrder?: 'ASC' | 'DESC'; stream?: boolean; pageSize?: number; } export interface SearchQuery { [key: string]: any; } export type StorageEntity = Entity & T & { entityId: string; }; export declare class StorageObject = Record> { private connection; private repository; private schema; private newSchema; private options; private isInitialized; private entityName; private versionField; private createdAtField; private updatedAtField; private keyManager; private storageVersionManager?; private schemaVersionManager?; private changeTrackingEnabled; constructor(entityName: string, schemaConfig: SchemaConfig, options?: StorageOptions); initialize(): Promise; private ensureInitialized; private prepareDataForJSON; private prepareDataForRedisJSON; private parseDataFromJSON; create(data: Partial): Promise>; createMany(items: Partial[], options?: BatchOptions): Promise[]>; /** * Truly atomic batch creation using Redis transactions */ private createManyAtomic; /** * Batch creation with rollback on failure */ private createManyWithRollback; findById(id: string): Promise | null>; findAll(options?: QueryOptions): Promise[]>; findOne(query: SearchQuery): Promise | null>; find(query: SearchQuery, options?: QueryOptions): Promise[]>; update(id: string, data: Partial, options?: UpdateOptions): Promise | null>; updateMany(query: SearchQuery, data: Partial, options?: BatchOptions): Promise; /** * Truly atomic batch update using Redis transactions */ private updateManyAtomic; /** * Batch update with rollback on failure */ private updateManyWithRollback; /** * Non-atomic batch update (original implementation) */ private updateManyNonAtomic; delete(id: string): Promise; deleteMany(query: SearchQuery, options?: BatchOptions): Promise; /** * Truly atomic batch deletion using Redis transactions */ private deleteManyAtomic; /** * Batch deletion with rollback capability */ private deleteManyWithRollback; /** * Non-atomic batch deletion (original implementation) */ private deleteManyNonAtomic; count(query?: SearchQuery): Promise; exists(id: string): Promise; clear(): Promise; private executeSearch; disconnect(): Promise; getRepository(): Repository; getEntityName(): string; /** * Get the schema name (alias for entityName) */ get schemaName(): string; /** * Get the Redis client for this storage */ getRedis(): any; /** * Get multiple entities by their IDs * * @param ids - Array of entity IDs to retrieve * @returns Array of entities (null for not found) */ getMany(ids: string[]): Promise<(StorageEntity | null)[]>; /** * Enable change tracking for version management */ enableChangeTracking(storageVersionManager: StorageVersionManager): void; /** * Set the schema version manager for entity tracking */ setSchemaVersionManager(schemaVersionManager: SchemaVersionManager): void; /** * Get current storage and schema versions */ getCurrentStorageVersions(): Promise<{ currentStorageVersion: number; currentSchemaVersion: number; versionTimestamp: number; }>; /** * Sync iterator for progressive sync operations */ syncIterator(nodeId: string, options: { syncBatchSize?: number; fromStorageVersion?: number; toStorageVersion?: number; includeEntityData?: boolean; }): AsyncIterableIterator; /** * Atomically increment a numeric field * This operation is guaranteed to be atomic with no race conditions */ atomicIncrement(id: string, field: keyof T, delta?: number): Promise; /** * Update with version check using Redis transactions * Provides stronger consistency guarantees than regular update */ updateWithLock(id: string, data: Partial, expectedVersion?: number): Promise | null>; /** * Perform multiple updates atomically * Either all succeed or all fail */ batchUpdateAtomic(updates: Array<{ id: string; data: Partial; expectedVersion?: number; }>): Promise<(StorageEntity | null)[]>; /** * Get the StorageSchema instance for this storage * * @returns The StorageSchema instance * * @example * ```typescript * const schema = storage.getSchema(); * const fields = schema.getFields(); * ``` */ getSchema(): NewStorageSchema | OldStorageSchema; /** * Update the schema definition and recreate indexes * Used during import to apply the imported schema * * @param schemaDefinition - The new schema definition to apply * @returns Promise that resolves when schema is updated and indexes are recreated * * @internal */ updateSchema(schemaDefinition: any): Promise; /** * Optimized schema update that only recreates index if needed * Detects if indexed fields changed and skips index recreation for safe changes * @internal */ updateSchemaOptimized(schemaDefinition: any): Promise; /** * Get metadata about this storage instance * * @returns Storage metadata including entity name, options, and initialization status * * @example * ```typescript * const metadata = storage.getMetadata(); * console.log(metadata.entityName, metadata.isInitialized); * ``` */ getMetadata(): { entityName: string; prefix: string; isInitialized: boolean; options: StorageOptions; dataStructure: 'JSON' | 'HASH'; fields: SchemaConfig; }; /** * Validate data against the schema * * @param data - Data to validate * @returns Validation result with errors and warnings * * @example * ```typescript * const result = await storage.validate({ name: 'John', age: 30 }); * if (!result.valid) { * console.error('Validation errors:', result.errors); * } * ``` */ validate(data: Partial): Promise; /** * Create multiple entities in a batch operation * * @param items - Array of items to create * @param options - Batch operation options * @returns Array of created entities * * @example * ```typescript * const users = await storage.bulkCreate([ * { name: 'John', age: 30 }, * { name: 'Jane', age: 25 } * ]); * ``` */ bulkCreate(items: Partial[], options?: BatchOptions): Promise[]>; /** * Update multiple entities in a batch operation * * @param updates - Array of update operations with id and data * @param options - Batch operation options * @returns Array of updated entities or null for not found * * @example * ```typescript * const updated = await storage.bulkUpdate([ * { id: 'user1', data: { age: 31 } }, * { id: 'user2', data: { age: 26 } } * ]); * ``` */ bulkUpdate(updates: Array<{ id: string; data: Partial; expectedVersion?: number; }>, options?: BatchOptions): Promise<(StorageEntity | null)[]>; /** * Delete multiple entities in a batch operation * * @param ids - Array of entity IDs to delete * @param options - Batch operation options * @returns Object with success status and deleted count * * @example * ```typescript * const result = await storage.bulkDelete(['user1', 'user2', 'user3']); * console.log(`Deleted ${result.deletedCount} entities`); * ``` */ bulkDelete(ids: string[], options?: BatchOptions): Promise<{ success: boolean; deletedCount: number; errors?: string[]; }>; /** * Get the current storage version if change tracking is enabled */ getCurrentStorageVersion(): Promise; /** * Get changes since a specific version */ getChangesSinceVersion(fromVersion: number, limit?: number): Promise; /** * Export storage data and/or schema to a file * * @param filePath - Path to export to * @param options - Export options * @returns Export metadata * * @example * ```typescript * // Export everything * const metadata = await storage.export('./backup/users.json'); * * // Export with options * const metadata = await storage.export('./users.ndjson', { * exportFormat: 'ndjson', * compressOutput: true, * includeSchema: true, * includeData: true * }); * * // Export incremental changes * const metadata = await storage.export('./changes.json', { * incrementalExport: true, * fromStorageVersion: 100, * toStorageVersion: 200 * }); * ``` */ export(filePath: string, options?: ExportOptions): Promise; /** * Import storage data and/or schema from a file * * @param filePath - Path to import from * @param options - Import options * @returns Import result * * @example * ```typescript * // Import from backup * const result = await storage.import('./backup/users.json'); * console.log(`Imported ${result.importedEntityCount} entities`); * * // Import with validation * const result = await storage.import('./users.ndjson', { * validateSchemaVersion: true, * entityMergeStrategy: 'merge', * continueOnError: true * }); * * // Dry run to test import * const result = await storage.import('./data.json', { * dryRun: true * }); * ``` */ import(filePath: string, options?: ImportOptions): Promise; /** * Create a backup of this storage * * @param backupName - Optional backup name (defaults to timestamp) * @returns Path to backup file * * @example * ```typescript * // Quick backup with auto-generated name * const backupPath = await storage.backup(); * * // Named backup * const backupPath = await storage.backup('users-before-migration'); * ``` */ backup(backupName?: string): Promise; /** * Restore from a backup file * * @param backupPath - Path to backup file * @returns Import result * * @example * ```typescript * // Restore from backup * const result = await storage.restore('./backups/users-backup.json.gz'); * console.log(`Restored ${result.importedEntityCount} entities`); * ``` */ restore(backupPath: string): Promise; /** * Export incremental changes since a specific version * * @param filePath - Path to export to * @param fromVersion - Starting version (exclusive) * @param toVersion - Ending version (inclusive, defaults to current) * @param options - Additional export options * @returns Export metadata * * @example * ```typescript * // Export changes since version 100 * const metadata = await storage.exportIncremental( * './changes-100-200.json', * 100, * 200 * ); * * // Export all changes since version 50 * const metadata = await storage.exportIncremental( * './recent-changes.json', * 50 * ); * * // Export with compression * const metadata = await storage.exportIncremental( * './changes.json.gz', * lastSyncVersion, * undefined, * { compressOutput: true } * ); * ``` */ exportIncremental(filePath: string, fromVersion: number, toVersion?: number, options?: Partial): Promise; /** * Import and apply incremental changes * * @param filePath - Path to incremental export file * @param options - Import options * @returns Import result with version information * * @example * ```typescript * // Apply incremental changes * const result = await storage.importIncremental('./changes-100-200.json'); * console.log(`Applied ${result.importedEntityCount} changes`); * console.log(`Now at version ${result.endStorageVersion}`); * * // Apply with validation * const result = await storage.importIncremental('./changes.json', { * validateSchemaVersion: true, * continueOnError: true * }); * ``` */ importIncremental(filePath: string, options?: Partial): Promise; /** * Synchronize with another storage instance * * @param targetStorage - Target storage to sync with * @param options - Sync options * @returns Sync result * * @example * ```typescript * // Sync two storage instances * const sourceStorage = await StorageSystem.get('users'); * const targetStorage = await StorageSystem.get('users-replica'); * * const result = await sourceStorage.sync(targetStorage, { * fromVersion: lastSyncVersion, * strategy: 'merge' * }); * * console.log(`Synced ${result.syncedCount} entities`); * console.log(`Target now at version ${result.targetVersion}`); * ``` */ sync(targetStorage: StorageObject, options?: { fromVersion?: number; toVersion?: number; strategy?: 'replace' | 'merge' | 'skip'; batchSize?: number; }): Promise<{ syncedCount: number; failedCount: number; sourceVersion: number; targetVersion: number; errors?: Array<{ entityId: string; error: string; }>; }>; /** * Get version history for this storage * * @param limit - Maximum number of versions to retrieve * @returns Array of version entries with timestamps * * @example * ```typescript * const history = await storage.getVersionHistory(10); * history.forEach(entry => { * console.log(`Version ${entry.version} at ${new Date(entry.timestamp)}`); * }); * ``` */ getVersionHistory(limit?: number): Promise>; /** * Enable change tracking for this storage instance (async version) * * @returns Current storage version after enabling * * @example * ```typescript * // Enable change tracking on existing storage * const version = await storage.enableChangeTrackingAsync(); * console.log(`Change tracking enabled at version ${version}`); * ``` */ enableChangeTrackingAsync(): Promise; /** * Get a summary of changes between versions * * @param fromVersion - Starting version * @param toVersion - Ending version (defaults to current) * @returns Summary of changes * * @example * ```typescript * const summary = await storage.getChangeSummary(100, 200); * console.log(`${summary.created} created, ${summary.updated} updated, ${summary.deleted} deleted`); * ``` */ getChangeSummary(fromVersion: number, toVersion?: number): Promise<{ created: number; updated: number; deleted: number; totalChanges: number; affectedEntityIds: string[]; }>; } //# sourceMappingURL=storage.d.ts.map