syncstates companion library for Backstage
- JavaScript 71.4%
- TypeScript 28.6%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .vscode | ||
| build | ||
| src | ||
| tests | ||
| .gitignore | ||
| .gitlab-ci.yml | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
@simtopy/syncstates
A TypeScript library for state synchronization, featuring data structures, conflict resolution, and configurable retry logic.
Features
- Type-Safe Data Structures: Fully typed stores and indexes with configurable ID and timestamp keys
- Efficient Synchronization: Smart batching and query optimization
- Automatic Conflict Resolution: Built-in timestamp-based conflict detection
- Configurable Retry Logic: Exponential backoff with customizable retry policies
- Transaction Safety: Rollback mechanism for failed synchronizations
- Flexible Logging: Pluggable logger interface for debugging and monitoring
- Memory Efficient: Uses Maps and Sets for optimal performance
Installation
npm install @simtopy/syncstates
Quick start
import { TypeStore, IdStore, Synchronizer } from '@simtopy/syncstates'
// Create stores with type-specific keys
const store = new TypeStore([
['users', new IdStore([], 'userId', 'createdAt')],
['products', new IdStore([], 'productId', 'lastModified')]
])
// Create synchronizer with fetch function
const sync = new Synchronizer(async (query) => {
// Your API call to fetch data
const response = await fetch('/api/sync', {
method: 'POST',
body: JSON.stringify(query)
})
return response.json()
})
// Define queries for synchronization
const queries = [
[['users', ['user1', 'user2']], ['products', ['prod1']]]
]
// Synchronize data
await sync.synchronize(queries, store)
Core Concepts
Main Classes
- TypeStore: Main data container managing multiple IdStores
- IdStore<IdKey, TsKey>: Typed store for specific data types
- Synchronizer: Handles data synchronization with retry logic
- TypeIndex: Index for tracking state across multiple types
- IdIndex: Index for tracking state of individual items
Mutation Tracking
- TypeIndexMutation: Tracks changes across multiple types
- IdIndexMutation: Tracks changes for individual items
Error Types
- ValidationError: Data format validation failed
- MissingTypeError: Unknown data type encountered
- NetworkError: Network-related issues (retryable)
- MaxAttemtpsError: Maximum retry attempts exceeded
TypeStore and IdStore
TypeStore manages multiple IdStore instances, each representing a different data type with its own ID and timestamp keys:
const userStore = new IdStore([], 'userId', 'createdAt')
const productStore = new IdStore([], 'productId', 'lastModified')
const typeStore = new TypeStore([
['users', userStore],
['products', productStore]
])
Indexes for State Management
import { TypeIndex, IdIndex } from '@simtopy/syncstates'
// Create indexes to track state
const idIndex = new IdIndex([['item1', 1000], ['item2', 2000]])
const typeIndex = new TypeIndex([['users', idIndex]])
// Compare states to detect changes
const mutation = IdIndexMutation.fromIdIndexs(previousIndex, currentIndex)
Synchronization with Retry Logic
const synchronizer = new Synchronizer(fetchFunction, {
maxRetry: 5,
retryDelay: 1000,
retryBackoff: 2.0
})
try {
await synchronizer.synchronize(queries, store)
} catch (error) {
if (error instanceof MaxAttemtpsError) {
console.log('Max retry attempts reached')
}
}
Advanced Usage
Custom Logger
const customLogger = {
trace: (...args) => console.trace('[TRACE]', ...args),
debug: (...args) => console.debug('[DEBUG]', ...args),
verbose: (...args) => console.log('[VERBOSE]', ...args),
info: (...args) => console.info('[INFO]', ...args),
warn: (...args) => console.warn('[WARN]', ...args),
error: (...args) => console.error('[ERROR]', ...args)
}
const sync = new Synchronizer(fetchFunction, customLogger)
Query Building Strategies
// Type-focused queries (one type per batch)
const typedQueries = Synchronizer.buildTypedQueries(mutations, 1000)
// Balanced queries (multiple types per batch)
const balancedQueries = Synchronizer.buildBalancedQueries(mutations, 1000)
Changelog
0.2.4
- added a copy getter in idStore and typeStore
- added a test for the copy getter