From 150e3e7ef4642cbbb88208c13196a299c40a70c0 Mon Sep 17 00:00:00 2001 From: helloscoopa <26799723+helloscoopa@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:18:28 +0000 Subject: [PATCH] docs: freeze v1.7.0 docs --- gitbook-docs.yaml | 11 +- gitbook-versions/v1.7/.gitbook.yaml | 5 + gitbook-versions/v1.7/README.md | 64 ++ gitbook-versions/v1.7/SUMMARY.md | 44 + .../v1.7/advanced/dependency-tracking.md | 408 +++++++++ .../v1.7/advanced/event-system.md | 460 ++++++++++ gitbook-versions/v1.7/advanced/middleware.md | 192 ++++ .../v1.7/advanced/persistent-storage.md | 303 +++++++ .../v1.7/advanced/resource-management.md | 476 ++++++++++ .../v1.7/advanced/serialization-adapters.md | 80 ++ .../v1.7/advanced/tag-invalidation.md | 620 +++++++++++++ .../v1.7/advanced/type-validation.md | 79 ++ gitbook-versions/v1.7/api/events.md | 647 ++++++++++++++ gitbook-versions/v1.7/api/run-cache.md | 774 ++++++++++++++++ gitbook-versions/v1.7/api/storage-adapters.md | 358 ++++++++ .../v1.7/api/typed-cache-interface.md | 459 ++++++++++ gitbook-versions/v1.7/api/types.md | 263 ++++++ .../v1.7/features/auto-refetch.md | 294 ++++++ .../v1.7/features/cache-management.md | 224 +++++ .../v1.7/features/eviction-policies.md | 133 +++ .../v1.7/features/pattern-matching.md | 322 +++++++ .../v1.7/features/source-functions.md | 391 ++++++++ .../v1.7/features/ttl-expiration.md | 255 ++++++ .../v1.7/getting-started/basic-usage.md | 305 +++++++ .../v1.7/getting-started/installation.md | 99 +++ .../v1.7/getting-started/typed-caching.md | 434 +++++++++ .../v1.7/guides/best-practices.md | 838 ++++++++++++++++++ gitbook-versions/v1.7/guides/debugging.md | 697 +++++++++++++++ .../v1.7/guides/migration-guide.md | 476 ++++++++++ gitbook-versions/v1.7/guides/performance.md | 625 +++++++++++++ .../v1.7/resources/contributing.md | 9 + gitbook-versions/v1.7/resources/faq.md | 433 +++++++++ gitbook-versions/v1.7/resources/license.md | 80 ++ 33 files changed, 10856 insertions(+), 2 deletions(-) create mode 100644 gitbook-versions/v1.7/.gitbook.yaml create mode 100644 gitbook-versions/v1.7/README.md create mode 100644 gitbook-versions/v1.7/SUMMARY.md create mode 100644 gitbook-versions/v1.7/advanced/dependency-tracking.md create mode 100644 gitbook-versions/v1.7/advanced/event-system.md create mode 100644 gitbook-versions/v1.7/advanced/middleware.md create mode 100644 gitbook-versions/v1.7/advanced/persistent-storage.md create mode 100644 gitbook-versions/v1.7/advanced/resource-management.md create mode 100644 gitbook-versions/v1.7/advanced/serialization-adapters.md create mode 100644 gitbook-versions/v1.7/advanced/tag-invalidation.md create mode 100644 gitbook-versions/v1.7/advanced/type-validation.md create mode 100644 gitbook-versions/v1.7/api/events.md create mode 100644 gitbook-versions/v1.7/api/run-cache.md create mode 100644 gitbook-versions/v1.7/api/storage-adapters.md create mode 100644 gitbook-versions/v1.7/api/typed-cache-interface.md create mode 100644 gitbook-versions/v1.7/api/types.md create mode 100644 gitbook-versions/v1.7/features/auto-refetch.md create mode 100644 gitbook-versions/v1.7/features/cache-management.md create mode 100644 gitbook-versions/v1.7/features/eviction-policies.md create mode 100644 gitbook-versions/v1.7/features/pattern-matching.md create mode 100644 gitbook-versions/v1.7/features/source-functions.md create mode 100644 gitbook-versions/v1.7/features/ttl-expiration.md create mode 100644 gitbook-versions/v1.7/getting-started/basic-usage.md create mode 100644 gitbook-versions/v1.7/getting-started/installation.md create mode 100644 gitbook-versions/v1.7/getting-started/typed-caching.md create mode 100644 gitbook-versions/v1.7/guides/best-practices.md create mode 100644 gitbook-versions/v1.7/guides/debugging.md create mode 100644 gitbook-versions/v1.7/guides/migration-guide.md create mode 100644 gitbook-versions/v1.7/guides/performance.md create mode 100644 gitbook-versions/v1.7/resources/contributing.md create mode 100644 gitbook-versions/v1.7/resources/faq.md create mode 100644 gitbook-versions/v1.7/resources/license.md diff --git a/gitbook-docs.yaml b/gitbook-docs.yaml index a43ba7a..9afef17 100644 --- a/gitbook-docs.yaml +++ b/gitbook-docs.yaml @@ -7,11 +7,18 @@ $schema: https://api.gitbook.com/gitbook-docs.yaml site: title: RunCache structure: + - type: space + key: space-v1-7 + title: "v1.7 (latest)" + path: v1-7 + default: true + content: + directory: ./gitbook-versions/v1.7 + language: en - type: space key: space-v1-6 - title: "v1.6 (latest)" + title: "v1.6" path: v1-6 - default: true content: directory: ./gitbook-versions/v1.6 language: en diff --git a/gitbook-versions/v1.7/.gitbook.yaml b/gitbook-versions/v1.7/.gitbook.yaml new file mode 100644 index 0000000..6acdd6a --- /dev/null +++ b/gitbook-versions/v1.7/.gitbook.yaml @@ -0,0 +1,5 @@ +root: ./ + +structure: + readme: README.md + summary: SUMMARY.md diff --git a/gitbook-versions/v1.7/README.md b/gitbook-versions/v1.7/README.md new file mode 100644 index 0000000..b3a713a --- /dev/null +++ b/gitbook-versions/v1.7/README.md @@ -0,0 +1,64 @@ +# RunCache + +{% hint style="info" %} +These docs are for **RunCache v1.7.x** (last updated at release v1.7.0). Install this version with `npm install run-cache@1.7`, or pick another version from the menu above the sidebar. +{% endhint %} + +> A dependency-free, lightweight runtime caching library for JavaScript and TypeScript applications. + + +RunCache allows you to cache strings and other JSON-serializable values with configurable time-to-live (TTL) settings and supports automatic value regeneration through source functions. It's designed to be easy to use while providing powerful features for advanced caching scenarios. + +## Key Features + +- **Zero Dependencies:** Lightweight implementation with no external dependencies +- **In-Memory Performance:** Fast, efficient runtime cache for optimal application performance +- **Source Function Support:** Cache values generated from synchronous or asynchronous functions +- **Automatic Refetching:** Configure cache entries to automatically refresh on expiration +- **Comprehensive Event System:** Subscribe to cache events including expiry, refetch, and refetch failures +- **Pattern Matching:** Use wildcard patterns to operate on groups of related cache keys +- **Eviction Policies:** Configure size limits with LRU (Least Recently Used) or LFU (Least Frequently Used) eviction strategies +- **Middleware Support:** Add custom processing for intercepting and transforming cache operations +- **Tag-based Invalidation:** Group related cache entries with tags for efficient batch invalidation +- **Dependency Tracking:** Establish relationships between cache entries with automatic cascading invalidation +- **Persistent Storage:** Store cache data across application restarts using various storage adapters +- **TypeScript Support:** Full type definitions included + +## Quick Example + +```typescript +import { RunCache } from "run-cache"; + +// Basic caching +await RunCache.set({ key: "user-profile", value: { name: "John Doe" } }); +const profile = await RunCache.get("user-profile"); + +// Cache with expiration (TTL in milliseconds) +await RunCache.set({ + key: "api-data", + value: { data: [1, 2, 3] }, + ttl: 60000 // 1 minute +}); + +// Cache with automatic refresh +await RunCache.set({ + key: "weather-data", + sourceFn: async () => await fetchWeatherData(), + ttl: 300000, // 5 minutes + autoRefetch: true +}); +``` + +## When to Use RunCache + +RunCache is ideal for: + +- Caching API responses to reduce network requests +- Storing computed values to improve application performance +- Managing temporary data with automatic expiration +- Creating relationships between cached data with dependencies +- Implementing complex caching strategies with middleware + +## Getting Started + +To get started with RunCache, check out the [Installation](getting-started/installation.md) guide. \ No newline at end of file diff --git a/gitbook-versions/v1.7/SUMMARY.md b/gitbook-versions/v1.7/SUMMARY.md new file mode 100644 index 0000000..3e6a650 --- /dev/null +++ b/gitbook-versions/v1.7/SUMMARY.md @@ -0,0 +1,44 @@ +# Table of contents + +* [Introduction](README.md) + +## Getting Started +* [Installation](getting-started/installation.md) +* [Basic Usage](getting-started/basic-usage.md) +* [Typed Caching](getting-started/typed-caching.md) + +## Core Features +* [Cache Management](features/cache-management.md) +* [TTL and Expiration](features/ttl-expiration.md) +* [Automatic Refetching](features/auto-refetch.md) +* [Source Functions](features/source-functions.md) +* [Eviction Policies](features/eviction-policies.md) +* [Pattern Matching](features/pattern-matching.md) + +## Advanced Features +* [Tag-based Invalidation](advanced/tag-invalidation.md) +* [Dependency Tracking](advanced/dependency-tracking.md) +* [Event System](advanced/event-system.md) +* [Middleware](advanced/middleware.md) +* [Persistent Storage](advanced/persistent-storage.md) +* [Resource Management](advanced/resource-management.md) +* [Value Serialization](advanced/serialization-adapters.md) +* [Type Safety](advanced/type-validation.md) + +## API Reference +* [RunCache](api/run-cache.md) +* [Storage Adapters](api/storage-adapters.md) +* [Events](api/events.md) +* [Types](api/types.md) +* [Typed Cache Interface](api/typed-cache-interface.md) + +## Guides +* [Best Practices](guides/best-practices.md) +* [Performance Optimization](guides/performance.md) +* [Debugging and Logging](guides/debugging.md) +* [Migration Guide](guides/migration-guide.md) + +## Resources +* [FAQ](resources/faq.md) +* [Contributing](resources/contributing.md) +* [License](resources/license.md) \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/dependency-tracking.md b/gitbook-versions/v1.7/advanced/dependency-tracking.md new file mode 100644 index 0000000..135f2f8 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/dependency-tracking.md @@ -0,0 +1,408 @@ +# Dependency Tracking + +Dependency tracking is an advanced feature in RunCache that allows you to establish relationships between cache entries. When a cache entry changes or is invalidated, all dependent entries are automatically invalidated as well. This guide explains how to use dependency tracking effectively in your applications. + +## Understanding Dependency Tracking + +Dependency tracking allows you to: +- Define relationships between cache entries +- Automatically invalidate dependent entries when a parent entry changes +- Create complex dependency chains with multi-level relationships +- Maintain data consistency across related cache entries + +This is particularly useful for: +- Derived data that depends on base data +- Composite views that depend on multiple data sources +- Hierarchical data structures +- Ensuring consistency in complex caching scenarios + +## Setting Up Dependencies + +To establish a dependency relationship, use the `dependencies` parameter when setting a cache entry: + +```typescript +// Primary data +await RunCache.set({ + key: 'user:1:profile', + value: { name: 'John Doe', email: 'john@example.com' } +}); + +// Dependent data +await RunCache.set({ + key: 'user:1:dashboard', + value: { widgets: [...] }, + dependencies: ['user:1:profile'] // This entry depends on the profile +}); +``` + +In this example: +- `user:1:dashboard` depends on `user:1:profile` +- If `user:1:profile` is updated or invalidated, `user:1:dashboard` will be automatically invalidated + +Dependents (including indirect ones) are invalidated when the entry they depend on is: +- updated with `set()` (setting a key for the first time does not invalidate anything), +- refetched, manually with `refetch()` or automatically with `autoRefetch`, +- deleted, evicted, invalidated by tag, or expired (entries with `autoRefetch` invalidate their dependents when the refetch completes instead). + +Two consequences are worth planning for: +- Any `set()` on an existing parent counts as a change, even if the value is the same, and so does every automatic refetch of a parent with `autoRefetch`. Each one invalidates the parent's dependents. +- Invalidated dependents are removed, including ones that have their own `sourceFn` and `autoRefetch`. They are not re-created automatically; call `set()` for them again (for example from a `dependency_invalidation` listener) if they should come back. + +When an entry is both tagged and a dependent of another tagged entry, `invalidateByTag()` reports it with a `tag_invalidation` event. Only entries removed because of a dependency, and not because of the tag, get `dependency_invalidation` events. + +`invalidateByDependency(key)` invalidates the dependents of `key` while leaving `key` itself in the cache. Each invalidated entry emits a `dependency_invalidation` event whose `dependencyKey` is the entry that changed. + +## Multi-Level Dependencies + +RunCache supports multi-level dependency chains: + +```typescript +// Primary data +await RunCache.set({ + key: 'user:1:profile', + value: { name: 'John Doe' } +}); + +// First-level dependent data +await RunCache.set({ + key: 'user:1:recommendations', + value: [...], + dependencies: ['user:1:profile'] +}); + +// Second-level dependent data +await RunCache.set({ + key: 'home:feed', + value: [...], + dependencies: ['user:1:recommendations'] +}); +``` + +In this example: +- When `user:1:profile` changes, `user:1:recommendations` is invalidated +- When `user:1:recommendations` is invalidated (directly or via dependency), `home:feed` is also invalidated +- This creates a cascading invalidation effect + +## Multiple Dependencies + +A cache entry can depend on multiple other entries: + +```typescript +// Primary data sources +await RunCache.set({ key: 'products', value: [...] }); +await RunCache.set({ key: 'categories', value: [...] }); +await RunCache.set({ key: 'user:1:preferences', value: {...} }); + +// Dependent data that relies on multiple sources +await RunCache.set({ + key: 'user:1:product-recommendations', + value: [...], + dependencies: ['products', 'categories', 'user:1:preferences'] +}); +``` + +In this example: +- `user:1:product-recommendations` depends on three different cache entries +- If any of those entries change, the recommendations will be invalidated + +## Checking Dependencies + +You can check if one cache entry depends on another (directly or indirectly) using the `isDependencyOf` method: + +```typescript +// Check if one entry depends on another +const isDependency = await RunCache.isDependencyOf('home:feed', 'user:1:profile'); +console.log(isDependency); // true (because of the multi-level dependency) + +// Check a non-dependent relationship +const isNotDependency = await RunCache.isDependencyOf('products', 'categories'); +console.log(isNotDependency); // false (no dependency relationship) +``` + +## Manual Dependency Invalidation + +You can invalidate an entry's dependents without changing the entry itself using the `invalidateByDependency` method: + +```typescript +// Invalidate everything that depends on the profile +await RunCache.invalidateByDependency('user:1:profile'); +``` + +This will: +1. Invalidate all entries that directly depend on it (`user:1:recommendations`) +2. Invalidate all entries that depend on those entries (`home:feed`) +3. And so on, following the dependency chain + +The specified entry (`user:1:profile`) itself is kept. + +## Monitoring Dependency Invalidations + +RunCache provides events to monitor dependency invalidations: + +```typescript +// Global dependency invalidation event +await RunCache.onDependencyInvalidation((event) => { + console.log(`Cache entry ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); + +// Specific key dependency invalidation +await RunCache.onKeyDependencyInvalidation("user:1:dashboard", (event) => { + console.log(`Dashboard cache was invalidated due to dependency on: ${event.dependencyKey}`); +}); + +// Pattern-based dependency invalidation events +await RunCache.onKeyDependencyInvalidation("home:*", (event) => { + console.log(`Home page component ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +These events can be useful for: +- Logging and monitoring +- Triggering additional actions when dependencies are invalidated +- Debugging complex dependency chains + +## Combining Dependencies with Source Functions + +Dependencies work particularly well with source functions and automatic refetching: + +```typescript +// Primary data with source function +await RunCache.set({ + key: 'user:1:profile', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1'); + const data = await response.json(); + return data; + }, + ttl: 300000, // 5 minutes + autoRefetch: true +}); + +// Dependent data with source function +async function fetchRecommendations() { + // Get the user profile from cache + const profile = (await RunCache.get('user:1:profile')) as { preferences: string[] }; + + // Use profile data to fetch recommendations + const response = await fetch(`https://api.example.com/recommendations?preferences=${profile.preferences.join(',')}`); + const recommendations = await response.json(); + return recommendations; +} + +await RunCache.set({ + key: 'user:1:recommendations', + sourceFn: fetchRecommendations, + dependencies: ['user:1:profile'], + ttl: 600000, // 10 minutes + autoRefetch: true +}); +``` + +In this example: +1. When `user:1:profile` is refreshed (automatically or manually), `user:1:recommendations` is invalidated and removed from the cache +2. It is not re-created on its own: the next `get('user:1:recommendations')` returns `undefined` +3. Set it again with its source function when it is next needed (or from a `dependency_invalidation` listener), and it is computed from the fresh profile + +```typescript +await RunCache.onKeyDependencyInvalidation('user:1:recommendations', async () => { + await RunCache.set({ + key: 'user:1:recommendations', + sourceFn: fetchRecommendations, + dependencies: ['user:1:profile'], + ttl: 600000, + autoRefetch: true + }); +}); +``` + +## Dependency Best Practices + +### 1. Design Dependency Hierarchies Carefully + +Plan your dependency relationships to reflect logical data dependencies: + +```typescript +// Good - logical dependency hierarchy +await RunCache.set({ key: 'products', value: '...' }); +await RunCache.set({ key: 'product:1:details', value: '...', dependencies: ['products'] }); +await RunCache.set({ key: 'product:1:reviews', value: '...', dependencies: ['product:1:details'] }); + +// Avoid - circular dependencies +await RunCache.set({ key: 'user:1:friends', value: '...', dependencies: ['user:1:profile'] }); +await RunCache.set({ key: 'user:1:profile', value: '...', dependencies: ['user:1:friends'] }); // Circular! +``` + +RunCache rejects circular dependencies: the second `set()` above throws `Circular dependency detected`, and the entry is not written. + +### 2. Avoid Deep Dependency Chains + +Deep dependency chains can lead to widespread invalidations: + +```typescript +// Potentially problematic - deep dependency chain +A → B → C → D → E → F → G + +// Better - flatter dependency structure +A → B, C, D +E → F, G +``` + +Consider using tags for broader grouping when appropriate. + +### 3. Be Specific with Dependencies + +Define dependencies as specifically as possible: + +```typescript +// Too broad - invalidates too much +await RunCache.set({ + key: 'user:1:dashboard', + value: '...', + dependencies: ['global:data'] // Very broad dependency +}); + +// Better - more specific dependencies +await RunCache.set({ + key: 'user:1:dashboard', + value: '...', + dependencies: ['user:1:profile', 'user:1:preferences'] // Only what's needed +}); +``` + +### 4. Combine with Tags for Complex Scenarios + +For complex invalidation needs, combine dependencies with tags: + +```typescript +// Set up with both dependencies and tags +await RunCache.set({ + key: 'user:1:feed', + value: '...', + dependencies: ['user:1:profile', 'user:1:friends'], + tags: ['user:1', 'feed'] +}); + +// Different invalidation options: +// 1. Invalidate when profile changes (automatic via dependency) +// 2. Invalidate all user:1 data (via tag) +await RunCache.invalidateByTag('user:1'); +// 3. Invalidate all feeds (via tag) +await RunCache.invalidateByTag('feed'); +``` + +### 5. Monitor Invalidation Patterns + +Use events to monitor and understand how your dependencies behave: + +```typescript +// Track dependency invalidations +await RunCache.onDependencyInvalidation((event) => { + console.log(`${event.key} invalidated due to ${event.dependencyKey}`); + // Track metrics about invalidation frequency + trackMetric('cache.dependency.invalidation', { + key: event.key, + dependency: event.dependencyKey + }); +}); +``` + +## Advanced Dependency Patterns + +### 1. Dynamic Dependencies + +Create dependencies dynamically based on content: + +```typescript +async function cacheArticleWithRelatedContent(articleId) { + // Fetch and cache the article + const article = await fetchArticle(articleId); + await RunCache.set({ + key: `article:${articleId}`, + value: article + }); + + // Determine related content IDs from the article + const relatedIds = article.relatedArticles; + + // Cache related content with dependencies + for (const relatedId of relatedIds) { + const relatedArticle = await fetchArticle(relatedId); + await RunCache.set({ + key: `article:${relatedId}`, + value: relatedArticle, + dependencies: [`article:${articleId}`] // Dynamic dependency + }); + } +} +``` + +### 2. Dependency-Aware Refresh + +Refreshing a parent removes every entry that depends on it, so a dependent cannot be brought back with `refetch()` afterwards: it is no longer in the cache. To refresh a key together with its parents, refresh the parents first and then set the key again from its source function. RunCache cannot list keys or hand back an entry's source function, so keep the definitions of the entries you refresh this way: + +```typescript +interface EntryDefinition { + sourceFn: () => Promise; + dependencies?: string[]; + ttl?: number; +} + +// Your own record of how each entry is built +const definitions = new Map([ + ['user:1:profile', { sourceFn: fetchProfile, ttl: 300000 }], + ['user:1:recommendations', { + sourceFn: fetchRecommendations, + dependencies: ['user:1:profile'], + ttl: 600000 + }] +]); + +async function smartRefresh(key: string, refreshed = new Set()) { + if (refreshed.has(key)) return; + const definition = definitions.get(key); + + if (!definition) { + // Not defined here: refresh it in place (it needs a source function) + await RunCache.refetch(key); + refreshed.add(key); + return; + } + + // Refresh the parents first. Each one removes `key` and its other dependents. + for (const parent of definition.dependencies ?? []) { + await smartRefresh(parent, refreshed); + } + + // Then recreate `key`, so its source function runs against the fresh parents + await RunCache.set({ key, ...definition }); + refreshed.add(key); +} + +await smartRefresh('user:1:recommendations'); +``` + +`refreshed` makes sure a parent shared by several keys is refreshed once: refreshing it again later would remove the dependents that were just recreated. + +### 3. Conditional Dependencies + +Implement conditional dependency relationships: + +```typescript +// Check if we should establish a dependency +const shouldDependOn = await checkCondition(); + +await RunCache.set({ + key: 'conditional-data', + value: '...', + dependencies: shouldDependOn ? ['base-data'] : [] // Conditional dependency +}); +``` + +## Next Steps + +Now that you understand dependency tracking, explore these related topics: + +- [Tag-based Invalidation](./tag-invalidation.md) - Another way to group and invalidate related cache entries +- [Event System](./event-system.md) - Learn more about monitoring cache events +- [Source Functions](../features/source-functions.md) - Understand how to generate cache values dynamically +- [Resource Management](./resource-management.md) - Learn about memory management and cleanup \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/event-system.md b/gitbook-versions/v1.7/advanced/event-system.md new file mode 100644 index 0000000..1315ca7 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/event-system.md @@ -0,0 +1,460 @@ +# Event System + +RunCache provides a comprehensive event system that allows you to monitor and respond to various cache lifecycle events. This guide explains how to use the event system effectively in your applications. + +## Understanding the Event System + +The event system allows you to: +- Monitor cache operations like expiration, refetching, and invalidation +- Execute custom logic when specific events occur +- Implement logging, analytics, and debugging +- Build reactive systems that respond to cache changes + +RunCache supports both global event listeners (for all keys) and key-specific listeners (for specific keys or patterns). + +Listeners run synchronously, in the order they were registered. Errors thrown by a listener are reported to `console.error` and do not affect other listeners or the cache operation (see [Handle Errors in Event Handlers](#2-handle-errors-in-event-handlers)). + +## Available Event Types + +RunCache provides several event types you can subscribe to: + +| Event Type | Description | Event Object Properties | +|------------|-------------|------------------------| +| `EXPIRE` | Triggered when a cache entry expires | `key`, `value`, `ttl`, `createdAt`, `updatedAt` | +| `REFETCH` | Triggered when a cache entry is refreshed | `key`, `value`, `ttl`, `createdAt`, `updatedAt` | +| `REFETCH_FAILURE` | Triggered when a cache refresh fails | `key`, `value`, `ttl`, `createdAt`, `updatedAt`, `error` | +| `TAG_INVALIDATION` | Triggered when a cache entry is invalidated by tag | the above, plus `tag` | +| `DEPENDENCY_INVALIDATION` | Triggered when a cache entry is invalidated by dependency | the above, plus `dependencyKey` | + +`value` is the stored form of the entry: non-string values arrive as their JSON string. `error` is set only on `REFETCH_FAILURE` events, to the error the source function threw. No event carries custom metadata. + +## Global Event Listeners + +Global event listeners are triggered for all cache entries that match the specified event type: + +### Expiry Events + +```typescript +// Listen for all expiry events +await RunCache.onExpiry((event) => { + console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); +}); +``` + +### Refetch Events + +```typescript +// Listen for all successful refetch events +await RunCache.onRefetch((event) => { + console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); +}); + +// Listen for all refetch failure events +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}:`, event.error); +}); +``` + +### Tag Invalidation Events + +```typescript +// Listen for all tag invalidation events +await RunCache.onTagInvalidation((event) => { + console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### Dependency Invalidation Events + +```typescript +// Listen for all dependency invalidation events +await RunCache.onDependencyInvalidation((event) => { + console.log(`Cache key ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +## Key-Specific Event Listeners + +Key-specific event listeners are triggered only for cache entries with keys that match the specified key or pattern: + +### Key-Specific Expiry Events + +```typescript +// Listen for expiry of a specific key +await RunCache.onKeyExpiry("api-data", (event) => { + console.log(`API data cache expired`); +}); + +// Listen for expiry of keys matching a pattern +await RunCache.onKeyExpiry("user:*:profile", (event) => { + console.log(`User profile ${event.key} expired`); +}); +``` + +### Key-Specific Refetch Events + +```typescript +// Listen for refetch of a specific key +await RunCache.onKeyRefetch("weather-data", (event) => { + console.log(`Weather data was refreshed`); +}); + +// Listen for refetch failures of keys matching a pattern +await RunCache.onKeyRefetchFailure("api:*", (event) => { + console.error(`API data ${event.key} refresh failed:`, event.error); +}); +``` + +### Key-Specific Tag Invalidation Events + +```typescript +// Listen for tag invalidation of keys matching a pattern +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { + console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### Key-Specific Dependency Invalidation Events + +```typescript +// Listen for dependency invalidation of a specific key +await RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { + console.log(`Main dashboard was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +## Managing Event Listeners + +### Removing All Event Listeners + +To remove all event listeners: + +```typescript +// Remove all event listeners +await RunCache.clearEventListeners(); +``` + +### Removing Specific Event Listeners + +To remove listeners for a specific event type: + +```typescript +// Remove all expiry event listeners +await RunCache.clearEventListeners({ + event: EVENT.EXPIRE +}); +``` + +### Removing Key-Specific Listeners + +To remove listeners for a specific key or pattern: + +```typescript +// Remove refetch listeners for a specific key +await RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: "api-data" +}); + +// Remove refetch failure listeners for keys matching a pattern +await RunCache.clearEventListeners({ + event: EVENT.REFETCH_FAILURE, + key: "api:*" +}); +``` + +## Practical Event System Use Cases + +### 1. Logging and Monitoring + +Use events to implement comprehensive logging: + +```typescript +// Set up logging for all major events +await RunCache.onExpiry((event) => { + logger.info(`Cache expired: ${event.key}`); +}); + +await RunCache.onRefetch((event) => { + logger.info(`Cache refreshed: ${event.key}`); +}); + +await RunCache.onRefetchFailure((event) => { + logger.error(`Cache refresh failed: ${event.key}`, event.error); +}); + +await RunCache.onTagInvalidation((event) => { + logger.info(`Cache invalidated by tag: ${event.key} (tag: ${event.tag})`); +}); + +await RunCache.onDependencyInvalidation((event) => { + logger.info(`Cache invalidated by dependency: ${event.key} (depends on: ${event.dependencyKey})`); +}); +``` + +### 2. Implementing Retry Logic + +Use events to implement retry logic for failed refetches: + +```typescript +// Set up retry logic with exponential backoff +// Attempts per key; RunCache events carry no custom metadata +const retryCounts = new Map(); + +await RunCache.onRefetchFailure((event) => { + const retryCount = (retryCounts.get(event.key) ?? 0) + 1; + retryCounts.set(event.key, retryCount); + + if (retryCount <= 3) { + const delay = Math.pow(2, retryCount) * 1000; // Exponential backoff + console.log(`Retrying ${event.key} in ${delay}ms (attempt ${retryCount})`); + + setTimeout(() => { + RunCache.refetch(event.key) + .catch(() => { /* reported again through onRefetchFailure */ }); + }, delay); + } else { + console.error(`Failed to refresh ${event.key} after ${retryCount} attempts`); + } +}); + +// Any successful refresh (a retry, a manual refetch or an automatic one) resets the +// count, so a key that recovers gets a full retry sequence the next time it fails. +await RunCache.onRefetch((event) => { + retryCounts.delete(event.key); +}); +``` + +### 3. UI Updates + +Use events to trigger UI updates when cache data changes: + +```typescript +// One RunCache listener per key, shared by every component that shows that key. +// clearEventListeners() removes *all* listeners for an event and key, so a component +// that clears on unmount would also remove the listener of another component, or of +// a newer effect run, watching the same key. Components subscribe here instead and +// remove only their own callback. +const refetchSubscribers = new Map void>>(); + +function subscribeToRefetch(key: string, callback: () => void): () => void { + let callbacks = refetchSubscribers.get(key); + if (!callbacks) { + const created = new Set<() => void>(); + callbacks = created; + refetchSubscribers.set(key, created); + // Registered once per key and kept; it does nothing while no callback is subscribed. + RunCache.onKeyRefetch(key, () => created.forEach((cb) => cb())) + .catch((error) => console.error(`Could not watch ${key}`, error)); + } + const own = callbacks; + own.add(callback); + return () => { own.delete(callback); }; +} + +// React component example +function UserProfile({ userId }) { + const [profile, setProfile] = useState(null); + + useEffect(() => { + const key = `user:${userId}:profile`; + + let active = true; + + // get() returns the stored object, no parsing needed + const load = async () => { + const data = await RunCache.get(key); + if (active && data !== undefined) setProfile(data); + }; + + // This effect run owns only its own callback; the cleanup removes just that one, + // so a newer run (or another component) watching the same key keeps its updates. + const unsubscribe = subscribeToRefetch(key, () => { load().catch(console.error); }); + load().catch(console.error); + + return () => { + active = false; // ignore a load that finishes after cleanup + unsubscribe(); + }; + }, [userId]); + + // Render profile... +} +``` + +### 4. Cache Analytics + +Use events to collect analytics about cache usage: + +```typescript +// Set up analytics tracking +let metrics = { + expiryCount: 0, + refetchCount: 0, + refetchFailureCount: 0, + tagInvalidationCount: 0, + dependencyInvalidationCount: 0 +}; + +await RunCache.onExpiry(() => metrics.expiryCount++); +await RunCache.onRefetch(() => metrics.refetchCount++); +await RunCache.onRefetchFailure(() => metrics.refetchFailureCount++); +await RunCache.onTagInvalidation(() => metrics.tagInvalidationCount++); +await RunCache.onDependencyInvalidation(() => metrics.dependencyInvalidationCount++); + +// Report metrics periodically +setInterval(() => { + console.log('Cache metrics:', metrics); + // Send metrics to monitoring system + sendMetricsToMonitoring(metrics); + + // Reset counters + metrics = { + expiryCount: 0, + refetchCount: 0, + refetchFailureCount: 0, + tagInvalidationCount: 0, + dependencyInvalidationCount: 0 + }; +}, 60000); // Every minute +``` + +### 5. Cascading Updates + +Use events to implement custom cascading update logic: + +```typescript +// When user data is refreshed, also refresh related data +await RunCache.onKeyRefetch('user:*:profile', async (event) => { + const userId = event.key.split(':')[1]; + + // Refresh related data + await RunCache.refetch(`user:${userId}:recommendations`); + await RunCache.refetch(`user:${userId}:activity`); +}); +``` + +## Event Metadata + +Cache entries cannot carry custom metadata, and event objects only contain the fields listed in the [Events API](../api/events.md). To associate extra information with a key, keep it in your own map: + +```typescript +const entryInfo = new Map(); + +await RunCache.set({ key: 'api-data', value: { results: [] } }); +entryInfo.set('api-data', { source: 'external-api', version: '1.0' }); + +await RunCache.onKeyExpiry('api-data', (event) => { + const info = entryInfo.get(event.key); + console.log(`API data expired. Source: ${info?.source}, Version: ${info?.version}`); +}); +``` + +## Best Practices for Event Handling + +### 1. Keep Event Handlers Lightweight + +Event handlers should be fast and non-blocking: + +```typescript +// Good - lightweight handler +await RunCache.onExpiry((event) => { + console.log(`Cache expired: ${event.key}`); +}); + +// Avoid - heavy processing in handler +await RunCache.onExpiry(async (event) => { + // DON'T do this - blocks the event loop + await heavyProcessing(); + await networkRequest(); +}); +``` + +If you need to perform heavy work, delegate it to a separate process or queue. + +### 2. Handle Errors in Event Handlers + +RunCache isolates listeners from cache operations. If a listener throws, or an `async` listener rejects, the error is written to `console.error` (naming the event and key), the remaining listeners still run, and the cache operation that emitted the event completes normally. A failing listener can therefore never abort an invalidation, crash the process from an expiry timer, or cause an unhandled promise rejection. The error is not passed back to the code that triggered the event. To route listener errors to your own logging instead of the console, set `onListenerError`: + +```typescript +await RunCache.configure({ + onListenerError: (error, { event, key }) => logger.error({ err: error, event, key }, 'RunCache listener failed'), +}); +``` + +To react to errors inside a specific listener, handle them there: + +```typescript +// Good - error handling +await RunCache.onRefetch((event) => { + try { + processRefetchEvent(event); + } catch (error) { + console.error('Error in refetch handler:', error); + } +}); +``` + +### 3. Use Specific Key Patterns + +Use specific key patterns to minimize unnecessary event processing: + +```typescript +// Too broad - triggers for all keys +await RunCache.onKeyExpiry('*', (event) => { + // This will run for EVERY expiry +}); + +// Better - more specific pattern +await RunCache.onKeyExpiry('api:*', (event) => { + // This will only run for API-related expirations +}); +``` + +### 4. Clean Up Event Listeners + +Remove event listeners when they're no longer needed: + +```typescript +// In a component or module initialization +async function initializeModule() { + // Set up event listeners + await RunCache.onKeyRefetch('module-data', handleRefetch); + + // Return cleanup function + return () => + RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: 'module-data' + }); +} + +// Later, when shutting down +const cleanup = await initializeModule(); +// When module is unloaded +await cleanup(); +``` + +### 5. Avoid Circular Event Handling + +Be careful not to create circular event handling patterns: + +```typescript +// Dangerous - potential circular handling +await RunCache.onKeyRefetch('data-a', async () => { + await RunCache.refetch('data-b'); +}); + +await RunCache.onKeyRefetch('data-b', async () => { + await RunCache.refetch('data-a'); // Creates a loop! +}); +``` + +## Next Steps + +Now that you understand the event system, explore these related topics: + +- [Tag-based Invalidation](./tag-invalidation.md) - Learn about invalidating groups of related cache entries +- [Dependency Tracking](./dependency-tracking.md) - Understand how to establish relationships between cache entries +- [Middleware](./middleware.md) - Explore how to intercept and transform cache operations +- [Resource Management](./resource-management.md) - Learn about memory management and cleanup \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/middleware.md b/gitbook-versions/v1.7/advanced/middleware.md new file mode 100644 index 0000000..9f7d4b8 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/middleware.md @@ -0,0 +1,192 @@ +# Middleware + +The middleware system in RunCache allows you to intercept and transform cache operations. This enables powerful customization options such as: + +- Value validation +- Value normalization/transformation +- Encryption/decryption of cached values +- Logging or monitoring specific cache operations +- Custom business logic based on cache operations + +## Basic Usage + +Middleware functions are added to the RunCache using the `use()` method: + +```javascript +import { RunCache } from 'run-cache'; + +// Add a simple middleware that logs all cache operations +await RunCache.use(async (value, context, next) => { + console.log(`Cache operation: ${context.operation} for key: ${context.key}`); + return next(value); +}); +``` + +## Middleware Function Signature + +Middleware functions have the following signature: + +```typescript +(value: string | undefined, context: MiddlewareContext, next: (value: string | undefined) => Promise) => Promise +``` + +Where: + +- `value`: The stored (string) form of the value being processed +- `context`: Object containing metadata about the operation +- `next`: Function to call the next middleware in the chain + +The context object contains: + +```typescript +interface MiddlewareContext { + key: string; // The cache key being operated on + operation: 'get' | 'set' | 'delete' | 'has' | 'refetch'; // The operation being performed + value?: string; // The original value (if applicable) + ttl?: number; // Time-to-live in milliseconds (if applicable) + autoRefetch?: boolean; // Whether auto-refetch is enabled (if applicable) + timestamp: number; // Timestamp when the operation was initiated +} +``` + +### When middleware runs + +| Operation | Runs when | `value` is | The result is | +| --- | --- | --- | --- | +| `set` | A value is set, directly or from a `sourceFn` | The new value | Stored | +| `refetch` | A `sourceFn` runs again (`refetch()` or auto-refetch) | The fresh value | Stored | +| `get` | A key is read **and found** | The stored value | Returned to the caller | + +Although the type also lists `delete` and `has`, middleware is not called for them, nor for a `get()` that misses, for events, or when the cache is saved to or loaded from a storage adapter. + +A middleware that transforms values (encryption, compression) must therefore apply the transform on both `set` and `refetch`, and reverse it on `get`. If it only handles `set`, refetched values are stored untransformed and `get` then fails to reverse them. + +## Examples + +### Encryption Middleware + +```javascript +import { RunCache } from 'run-cache'; +import { encrypt, decrypt } from './your-crypto-lib'; + +// Add encryption middleware +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + // Encrypt the value before storing + return next(encrypt(value)); + } else if (context.operation === 'get') { + // Decrypt the value after retrieval + const encrypted = await next(value); + return encrypted ? decrypt(encrypted) : undefined; + } + return next(value); +}); + +// Use the cache normally - values will be automatically encrypted/decrypted +await RunCache.set({ key: 'sensitive-data', value: 'secret-value' }); +const value = await RunCache.get('sensitive-data'); // Returns decrypted 'secret-value' +``` + +### Data Validation Middleware + +```javascript +import { RunCache } from 'run-cache'; + +// Add validation middleware +await RunCache.use(async (value, context, next) => { + if (context.operation === 'set') { + if (!value || value.length < 3) { + // Reject invalid values + throw new Error(`Invalid value for key ${context.key}: minimum length is 3 characters`); + } + } + return next(value); +}); + +// Valid value - passes through middleware +await RunCache.set({ key: 'valid-key', value: 'valid-value' }); + +// Invalid value - throws error. Nothing is written: if 'invalid-key' already +// existed, it keeps its previous value and TTL. +try { + await RunCache.set({ key: 'invalid-key', value: 'a' }); +} catch (error) { + // error is a MiddlewareError; the error thrown by the middleware is error.cause + console.error(error.message); // "Middleware execution failed for key: 'invalid-key'" + console.error(error.cause.message); // "Invalid value for key invalid-key: minimum length is 3 characters" +} +``` + +### Objects and Middleware + +You do not need middleware to store objects: RunCache converts non-string values to JSON before the middleware chain runs on `set`, and parses them after it runs on `get` (see [Value Serialization](serialization-adapters.md)). Middleware therefore always receives a string, so any string transform such as the encryption above works for objects too: + +```javascript +await RunCache.set({ + key: 'user', + value: { id: 123, name: 'John Doe', email: 'john@example.com' } +}); + +const user = await RunCache.get('user'); // { id: 123, name: 'John Doe', ... } +``` + +## Chaining Multiple Middleware + +Middleware functions are executed in the order they are added. Each middleware can transform the value before passing it to the next middleware: + +```javascript +// First middleware compresses the data +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + return next(compress(value)); + } else if (context.operation === 'get') { + const compressed = await next(value); + return compressed ? decompress(compressed) : undefined; + } + return next(value); +}); + +// Second middleware encrypts the data +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + return next(encrypt(value)); + } else if (context.operation === 'get') { + const encrypted = await next(value); + return encrypted ? decrypt(encrypted) : undefined; + } + return next(value); +}); +``` + +In this example, when setting a value: +1. The value is first compressed by the first middleware +2. The compressed value is then encrypted by the second middleware +3. The encrypted and compressed value is stored in the cache + +When getting a value: +1. The encrypted and compressed value is retrieved from the cache +2. The second middleware decrypts it +3. The first middleware decompresses it +4. The original value is returned to the caller + +## Clearing Middleware + +To remove all middleware functions: + +```javascript +await RunCache.clearMiddleware(); +``` + +## Best Practices + +1. **Keep middleware functions focused**: Each middleware should have a single responsibility. +2. **Handle all operations**: Treat `refetch` like `set` (values going into the cache) and `get` as the way out. +3. **Always call next()**: Ensure you call `next(value)` to continue the middleware chain, unless you explicitly want to short-circuit it. +4. **Error handling**: Properly handle errors in your middleware to avoid breaking the cache functionality. +5. **Performance**: Be mindful of performance implications, especially for computationally expensive operations like encryption. + +## Next Steps + +- Learn about [Event System](event-system.md) for responding to cache events +- Explore [Persistent Storage](persistent-storage.md) for saving cache data across application restarts +- Check out [Resource Management](resource-management.md) for optimizing memory usage \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/persistent-storage.md b/gitbook-versions/v1.7/advanced/persistent-storage.md new file mode 100644 index 0000000..c2f0fb3 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/persistent-storage.md @@ -0,0 +1,303 @@ +# Persistent Storage + +RunCache keeps entries in memory, so they are lost when a Node.js process restarts or a browser page reloads. A storage adapter lets you save the cache to a durable medium and load it back later. + +## Storage Adapters + +Three adapters are built in: + +| Adapter | Environment | Where data goes | +| --- | --- | --- | +| `FilesystemAdapter` | Node.js | A JSON file, `./.json` by default | +| `LocalStorageAdapter` | Browser | `window.localStorage`, under `storageKey` | +| `IndexedDBAdapter` | Browser | The `cache-store` object store of the `run-cache-db` database, under `storageKey` | + +Each adapter throws from its constructor when used in the wrong environment. + +### Options + +All three accept these options. `FilesystemAdapter` also accepts `filePath`, which overrides the file location. + +| Option | Default | Effect | +| --- | --- | --- | +| `storageKey` | `"run-cache-data"` | Key (or file name) the data is stored under | +| `autoSaveInterval` | `0` (off) | Save every this many milliseconds while the adapter is attached | +| `autoLoadOnInit` | `true` | Load the saved data when the adapter is attached | + +```typescript +import { FilesystemAdapter, LocalStorageAdapter, IndexedDBAdapter } from 'run-cache'; + +new FilesystemAdapter({ storageKey: 'my-app-cache' }); // ./my-app-cache.json +new FilesystemAdapter({ filePath: '/var/cache/my-app/cache.json' }); +new LocalStorageAdapter({ storageKey: 'my-app-cache', autoSaveInterval: 60000 }); +new IndexedDBAdapter({ storageKey: 'my-app-cache', autoLoadOnInit: false }); +``` + +## Attaching an Adapter + +```typescript +import { RunCache, FilesystemAdapter } from 'run-cache'; + +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }) +}); + +// Entries saved by a previous run are available now +const user = await RunCache.get('user:1'); +``` + +Configuring an adapter immediately loads the data it holds (unless it was created with `autoLoadOnInit: false`) and merges it into the cache, as described in [Restoring Data](#restoring-data). `configure()` returns a promise, so `await` it before reading from the cache. Configuring the adapter that is already attached does nothing. + +When you switch to a different adapter, RunCache first saves the current entries to the previous adapter and then loads from the new one. If saving to the previous adapter fails, `configure()` rejects and the previous adapter stays attached, so no entries are lost and you can retry. Loading never changes your configuration: the `maxEntries` and `evictionPolicy` stored with the data are ignored. Pass `storageAdapter: undefined` to detach persistence. + +## Saving + +Nothing is saved unless you ask for it, in one of these ways. + +### Manually + +```typescript +const saved = await RunCache.saveToStorage(); // false if the adapter failed or none is attached +const loaded = await RunCache.loadFromStorage(); // false if nothing was saved or the data could not be read +``` + +Neither method throws on adapter errors: failures are reported as `false`, and logged when `debug: true` is set (see [Debugging](../guides/debugging.md)). Loading merges into the cache; to return to exactly the saved state, call `RunCache.flush()` first. + +### Auto-save + +Either give the adapter an `autoSaveInterval`, which applies while that adapter is attached, or start an interval yourself: + +```typescript +// Save every 5 minutes +await RunCache.setupAutoSave(300000); + +// Stop auto-saving +await RunCache.setupAutoSave(0); +``` + +Call `setupAutoSave()` after attaching the adapter: it does nothing while no adapter is attached. An interval started with `setupAutoSave()` keeps running when you switch to an adapter without a positive `autoSaveInterval`. Attaching an adapter that sets one replaces it: the explicit interval is cleared and the adapter's interval runs instead, and that one ends when the adapter is detached, leaving no auto-save until you call `setupAutoSave()` again. In Node.js the timer does not keep the process alive. + +### On shutdown + +`RunCache.shutdown()` saves to the attached adapter, then clears all entries, timers and listeners and detaches the adapter. To have that happen on `SIGINT`/`SIGTERM` (Node.js) or page unload (browser), opt in when configuring: + +```typescript +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }), + handleProcessSignals: true +}); +``` + +Without `handleProcessSignals`, call `await RunCache.shutdown()` from your own shutdown code. In a browser, an IndexedDB save started during page unload may not finish; save at a quieter moment as well if the data matters. + +## Restoring Data + +When data is loaded, whether automatically on attaching an adapter or with `loadFromStorage()`: + +- **Stored entries are merged into the cache.** Keys that already exist in memory keep their current value; the stored copy is ignored. Nothing in memory is cleared. To return to exactly the saved state, call `RunCache.flush()` before `RunCache.loadFromStorage()`. +- **Expired entries are skipped.** Entries that had already expired when the cache was saved are not written at all. +- **TTLs continue where they left off.** Each restored entry expires after the time remaining on its original TTL, not a fresh TTL, and emits its `expire` event as usual. +- **Your configuration wins.** `maxEntries`, `evictionPolicy` and other options are whatever you configured, not what was stored. If the restored entries exceed `maxEntries`, the eviction policy is applied. +- **Source functions must be set again.** Functions are never written to storage, so restored entries hold their last value but cannot be refetched or auto-refetched until you call `set()` with a `sourceFn` for them. + +Values keep their type (see [Value Serialization](serialization-adapters.md)), and tags, dependencies, `autoRefetch` flags and access statistics are restored too. + +```typescript +await RunCache.configure({ storageAdapter: new FilesystemAdapter() }); + +// Re-register source functions for entries that need refetching +await RunCache.set({ + key: 'exchange-rates', + sourceFn: fetchExchangeRates, + ttl: 60000, + autoRefetch: true +}); +``` + +## Storage Format + +Every adapter stores the same JSON string: + +```json +{ + "version": 1, + "timestamp": 1735689600000, + "entries": { + "user:1": { + "value": "{\"name\":\"Ada\"}", + "serialized": true, + "createdAt": 1735689500000, + "updatedAt": 1735689500000, + "ttl": 3600000, + "accessCount": 3, + "lastAccessed": 1735689590000, + "tags": ["user"], + "dependencies": ["session:1"] + } + }, + "config": { "maxEntries": 1000, "evictionPolicy": "LRU" } +} +``` + +`serialized: true` marks a value that was set as a non-string and is parsed again when read. Source functions are never written. The `config` block is informational only and is not applied when the data is loaded. + +The FilesystemAdapter writes to a temporary file in the same directory and renames it over the target, so a crash during a save never leaves a truncated cache file behind. + +## Custom Storage Adapters + +Implement the `StorageAdapter` interface to store the cache anywhere: + +```typescript +interface StorageAdapter { + save(data: string): Promise; + load(): Promise; // null when nothing has been saved + clear(): Promise; + + // Optional: read when the adapter is attached with configure() + readonly autoSaveInterval?: number; // save at this interval (ms) when > 0 + readonly autoLoadOnInit?: boolean; // load existing data on attach (default: true) +} +``` + +### Example: Redis + +```typescript +import { RunCache, type StorageAdapter } from 'run-cache'; +import Redis from 'ioredis'; + +class RedisStorageAdapter implements StorageAdapter { + private redis: Redis; + private key: string; + + constructor(options: { redisUrl: string; key?: string }) { + this.redis = new Redis(options.redisUrl); + this.key = options.key ?? 'run-cache-data'; + } + + async save(data: string): Promise { + await this.redis.set(this.key, data); + } + + async load(): Promise { + return this.redis.get(this.key); + } + + async clear(): Promise { + await this.redis.del(this.key); + } +} + +await RunCache.configure({ + storageAdapter: new RedisStorageAdapter({ redisUrl: 'redis://localhost:6379', key: 'my-app-cache' }) +}); +``` + +### Wrapping an adapter + +Middleware does not run when the cache is saved or loaded. To transform the stored data, for example to encrypt or compress it, wrap another adapter: + +```typescript +import { type StorageAdapter, LocalStorageAdapter } from 'run-cache'; + +class TransformingAdapter implements StorageAdapter { + constructor( + private inner: StorageAdapter, + private encode: (data: string) => string | Promise, + private decode: (data: string) => string | Promise + ) {} + + async save(data: string): Promise { + await this.inner.save(await this.encode(data)); + } + + async load(): Promise { + const data = await this.inner.load(); + return data === null ? null : this.decode(data); + } + + clear(): Promise { + return this.inner.clear(); + } + + // Pass the wrapped adapter's options through + get autoSaveInterval() { return this.inner.autoSaveInterval; } + get autoLoadOnInit() { return this.inner.autoLoadOnInit; } +} + +// encryptString/decryptString are your own functions +await RunCache.configure({ + storageAdapter: new TransformingAdapter(new LocalStorageAdapter(), encryptString, decryptString) +}); +``` + +The same wrapper can drop entries you do not want persisted: parse the JSON in `encode`, delete keys from `entries`, and stringify it again. + +## Best Practices + +1. **Pick the adapter for the environment.** `FilesystemAdapter` for Node.js; `IndexedDBAdapter` for larger browser caches, since `localStorage` is usually limited to about 5 MB per origin and its writes block the main thread. +2. **Save explicitly.** Combine `autoSaveInterval` (or `setupAutoSave()`) with `handleProcessSignals: true` or your own `await RunCache.shutdown()`. +3. **Check the result of `saveToStorage()`.** It returns `false` instead of throwing, for example when `localStorage` is full. Turn on `debug` to see the reason. +4. **Separate data by `storageKey`.** Use one key per user, environment or data-format version; changing the key is the simplest way to discard data written by an older version of your app. Because loading merges, switch users in this order: detach the current adapter (`await RunCache.configure({ storageAdapter: undefined })`, which saves to it), then `await RunCache.flush()`, then attach the next user's adapter. Flushing while the old adapter is still attached would let the empty cache be saved over that user's data. +5. **Re-register source functions after loading** for entries that rely on `refetch()` or `autoRefetch`. + +## Common Scenarios + +### Browser application with per-user data + +```typescript +import { RunCache, LocalStorageAdapter } from 'run-cache'; + +async function onUserLogin(userId: string) { + // Save the previous user's entries to their key and detach their adapter + await RunCache.configure({ storageAdapter: undefined }); + // Loading merges, so clear memory before loading another user's data + await RunCache.flush(); + + await RunCache.configure({ + storageAdapter: new LocalStorageAdapter({ + storageKey: `user-${userId}-cache`, + autoSaveInterval: 60000 + }) + }); + + const profile = await RunCache.get('user:profile'); + if (profile === undefined) { + await RunCache.set({ key: 'user:profile', value: await fetchUserProfile(userId), ttl: 3600000 }); + } +} +``` + +### Node.js service + +```typescript +import { RunCache, FilesystemAdapter, EvictionPolicy } from 'run-cache'; + +await RunCache.configure({ + maxEntries: 10000, + evictionPolicy: EvictionPolicy.LRU, + storageAdapter: new FilesystemAdapter({ + filePath: './data/cache.json', + autoSaveInterval: 5 * 60 * 1000 + }), + handleProcessSignals: true // save on SIGINT/SIGTERM +}); +``` + +### Choosing an adapter by environment + +```typescript +import { RunCache, FilesystemAdapter, IndexedDBAdapter, type StorageAdapter } from 'run-cache'; + +const isNode = typeof process !== 'undefined' && !!process.versions?.node; +const storageAdapter: StorageAdapter = isNode + ? new FilesystemAdapter({ storageKey: 'app-cache' }) + : new IndexedDBAdapter({ storageKey: 'app-cache' }); + +await RunCache.configure({ storageAdapter }); +``` + +## Next Steps + +- [Storage Adapters API](../api/storage-adapters.md) - Adapter reference +- [Resource Management](resource-management.md) - Shutdown and cleanup +- [Value Serialization](serialization-adapters.md) - How values are stored diff --git a/gitbook-versions/v1.7/advanced/resource-management.md b/gitbook-versions/v1.7/advanced/resource-management.md new file mode 100644 index 0000000..db7ef1e --- /dev/null +++ b/gitbook-versions/v1.7/advanced/resource-management.md @@ -0,0 +1,476 @@ +# Resource Management + +RunCache provides several features to help you effectively manage memory usage and ensure proper cleanup of resources. This guide explains how to optimize resource usage and implement proper cleanup in your applications. + +## Understanding Resource Management + +Effective resource management in RunCache involves: +- Controlling memory usage through cache size limits +- Implementing appropriate eviction policies +- Ensuring proper cleanup of timers and event listeners +- Managing application lifecycle events +- Optimizing cache performance + +## Cache Size Management + +### Setting Maximum Cache Size + +You can limit the maximum number of entries in the cache using the `maxEntries` configuration option: + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +// Configure cache with a maximum size of 1000 entries +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU // Least Recently Used +}); +``` + +When the cache reaches the maximum size, the configured eviction policy determines which entries are removed to make space for new ones. + +### Available Eviction Policies + +RunCache supports three eviction policies: + +1. **NONE**: No automatic eviction (default). Cache entries are only removed via TTL or manual deletion. + +2. **LRU (Least Recently Used)**: Removes the least recently used entries when the cache exceeds its maximum size. Writes and reads both count as a use. This is ideal for most applications as it preserves recently written and recently read data. + +3. **LFU (Least Frequently Used)**: Removes the least frequently accessed entries when the cache exceeds its maximum size. When entries have the same access frequency, the oldest entry is removed first. This is useful for applications where access frequency is more important than recency. + +```typescript +// Configure with LRU policy +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU +}); + +// Configure with LFU policy +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LFU +}); +``` + +### Monitoring Evictions + +You can monitor evictions by setting up a custom middleware: + +```typescript +// Add middleware to track evictions +await RunCache.use(async (value, context, next) => { + if (context.operation === 'evict') { + console.log(`Cache entry ${context.key} was evicted due to size limits`); + // Track metrics about evictions + trackMetric('cache.eviction', { + key: context.key, + policy: RunCache.getConfig().evictionPolicy + }); + } + return next(value); +}); +``` + +## Memory Usage Optimization + +### Using TTL for Automatic Cleanup + +Set appropriate TTL (Time-to-Live) values to automatically remove entries that are no longer needed. Entries holding a plain value are removed from memory as soon as their TTL elapses, even if they are never read again: + +```typescript +// Set cache entry with TTL +await RunCache.set({ + key: 'temporary-data', + value: largeDataObject, + ttl: 3600000 // 1 hour +}); +``` + +### Manual Cleanup + +For immediate cleanup of specific entries or groups of entries: + +```typescript +// Delete specific entries +await RunCache.delete('large-data-key'); + +// Delete groups of entries using patterns +await RunCache.delete('temp:*'); + +// Clear the entire cache +await RunCache.flush(); +``` + +### Optimizing Value Size + +Minimize the size of cached values: + +```typescript +// Bad - storing unnecessary data +await RunCache.set({ + key: 'user-profile', + value: { + name: 'John Doe', + email: 'john@example.com', + avatar: largeBase64EncodedImage, // Unnecessarily large + fullHistory: completeUserHistory, // Rarely needed data + // ...more data + } +}); + +// Better - store only what's needed +await RunCache.set({ + key: 'user-profile', + value: { + name: 'John Doe', + email: 'john@example.com', + avatarUrl: '/avatars/john.jpg', // Just the URL, not the image + // ...essential data only + } +}); + +// Store rarely needed data separately +await RunCache.set({ + key: 'user-profile:full-history', + value: completeUserHistory, + ttl: 3600000 // With shorter TTL +}); +``` + +## Timer Management + +RunCache uses timers for TTL expiration and automatic refetching. These are managed automatically, but it's important to understand how they work. + +### How Timers Work in RunCache + +- **TTL Timers**: Each entry with a TTL has a timer. When it fires, the `expire` event is emitted and entries without a source function are removed from memory, so keys that are written once and never read again do not accumulate. Entries with a source function stay until they are read or refetched. + +- **Process lifetime**: In Node.js, TTL timers and the auto-save interval are `unref()`'d. They never keep the process alive on their own, so a script exits when its other work is done even if cache entries are still pending expiry. + +- **Refetch Timers**: For entries with `autoRefetch: true`, RunCache sets up timers to trigger background refreshes when the TTL expires. + +### Cleaning Up Timers + +When you delete a cache entry or flush the cache, RunCache automatically cleans up any associated timers: + +```typescript +// This automatically cleans up any timers for this entry +await RunCache.delete('api-data'); + +// This cleans up all timers for all entries +await RunCache.flush(); +``` + +## Event Listener Management + +As your application grows, you might accumulate many event listeners. It's important to clean them up when they're no longer needed. + +### Removing Event Listeners + +```typescript +// Remove all event listeners +await RunCache.clearEventListeners(); + +// Remove listeners for a specific event type +await RunCache.clearEventListeners({ + event: EVENT.EXPIRE +}); + +// Remove listeners for a specific key +await RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: 'api-data' +}); +``` + +### Best Practices for Event Listeners + +```typescript +// In a component or module +async function initializeComponent() { + // Set up event listeners + await RunCache.onKeyRefetch('component-data', handleRefetch); + + // Return cleanup function + return () => + RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: 'component-data' + }); +} + +// When component mounts +const cleanup = await initializeComponent(); + +// When component unmounts +await cleanup(); +``` + +## Middleware Management + +Middleware functions can accumulate over time and impact performance. Clean them up when they're no longer needed: + +```typescript +// Remove all middleware +await RunCache.clearMiddleware(); +``` + +## Application Lifecycle Management + +### Cleanup on Termination + +Importing RunCache does not install any process or window handlers. Opt in to have RunCache shut down cleanly when the process or page is terminating: + +```typescript +await RunCache.configure({ handleProcessSignals: true }); +``` + +With this option enabled: + +- **Node.js**: RunCache listens for `SIGTERM` and `SIGINT`, awaits `RunCache.shutdown()` (which saves to the configured storage adapter), and then re-raises the signal unless your application has its own listener for it. The process therefore exits the same way it would without RunCache. The handlers remove themselves first, so a second signal terminates immediately. +- **Browsers**: RunCache calls `RunCache.shutdown()` on `beforeunload`. This is best effort, because browsers do not wait for asynchronous work during unload. + +Pass `handleProcessSignals: false` to remove the handlers again. `RunCache.shutdown()` also removes them. + +If your application already handles termination signals, leave the option off and call RunCache from your own handler: + +```typescript +process.on('SIGTERM', async () => { + await RunCache.shutdown(); + process.exit(0); +}); +``` + +### Manual Shutdown + +You can also manually trigger a complete shutdown of RunCache: + +```typescript +// Manually shut down the cache +await RunCache.shutdown(); +``` + +The `shutdown` method: +1. Clears all cache entries +2. Cancels all timers +3. Removes all event listeners +4. Resets the cache configuration to default values + +This is particularly useful in long-running applications or when you need to release resources manually. + +## Persistent Storage Management + +When using persistent storage adapters, it's important to manage storage resources effectively: + +```typescript +import { RunCache, FilesystemAdapter } from 'run-cache'; + +// Configure with storage adapter +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }) +}); + +// Save every 5 minutes +await RunCache.setupAutoSave(300000); + +// Manual save +await RunCache.saveToStorage(); + +// Manual load +await RunCache.loadFromStorage(); + +// Disable auto-save +await RunCache.setupAutoSave(0); +``` + +### Storage Cleanup + +To clean up persistent storage: + +```typescript +// Clear cache and save empty state to storage +await RunCache.flush(); +await RunCache.saveToStorage(); +``` + +## Performance Optimization Strategies + +### 1. Use Appropriate TTL Values + +Match TTL values to data volatility: + +```typescript +// Frequently changing data +await RunCache.set({ + key: 'stock-prices', + value: prices, + ttl: 60000 // 1 minute +}); + +// Relatively stable data +await RunCache.set({ + key: 'product-catalog', + value: catalog, + ttl: 3600000 // 1 hour +}); + +// Very stable data +await RunCache.set({ + key: 'app-configuration', + value: config, + ttl: 86400000 // 1 day +}); +``` + +### 2. Implement Staggered Expiration + +Add small random variations to TTL to prevent mass expiration: + +```typescript +function setWithJitter(key, value, baseTTL) { + const jitter = Math.floor(Math.random() * (baseTTL * 0.1)); // 10% jitter + return RunCache.set({ + key, + value, + ttl: baseTTL + jitter + }); +} + +// Usage +await setWithJitter('api-data-1', jsonData1, 300000); +await setWithJitter('api-data-2', jsonData2, 300000); +await setWithJitter('api-data-3', jsonData3, 300000); +``` + +### 3. Batch Related Operations + +Group related cache operations to minimize overhead: + +```typescript +// Less efficient - multiple separate operations +for (const id of userIds) { + await RunCache.set({ key: `user:${id}:profile`, value: profiles[id] }); +} + +// More efficient - batch processing +async function batchSetProfiles(profiles) { + const operations = Object.entries(profiles).map(([id, profile]) => + RunCache.set({ key: `user:${id}:profile`, value: profile }) + ); + await Promise.all(operations); +} + +await batchSetProfiles(profiles); +``` + +### 4. Use Structured Key Naming + +Adopt a consistent key naming convention for efficient pattern matching: + +```typescript +// Good - structured naming +await RunCache.set({ key: 'user:1:profile', value: '...' }); +await RunCache.set({ key: 'user:1:preferences', value: '...' }); +await RunCache.set({ key: 'post:123:comments', value: '...' }); + +// Efficient operations on groups +await RunCache.delete('user:1:*'); // Delete all user 1 data +const allUserData = await RunCache.get('user:*:profile'); // Get all user profiles +``` + +### 5. Implement Cache Warming + +Pre-populate critical cache entries on application startup: + +```typescript +async function warmCache() { + console.log('Warming cache...'); + + // Check if entries already exist + const hasConfig = await RunCache.has('app:config'); + const hasGlobalData = await RunCache.has('app:global-data'); + + // Warm up only what's missing + if (!hasConfig) { + const config = await fetchAppConfig(); + await RunCache.set({ key: 'app:config', value: config }); + } + + if (!hasGlobalData) { + const globalData = await fetchGlobalData(); + await RunCache.set({ key: 'app:global-data', value: globalData }); + } + + console.log('Cache warming complete'); +} + +// Call on application startup +warmCache(); +``` + +## Memory Leak Prevention + +### 1. Clean Up Event Listeners + +```typescript +// Set up event listener +const handleRefetch = (event) => { + console.log(`Refreshed: ${event.key}`); +}; + +await RunCache.onRefetch(handleRefetch); + +// Later, when no longer needed +await RunCache.clearEventListeners({ + event: EVENT.REFETCH, + handler: handleRefetch // Remove specific handler +}); +``` + +### 2. Avoid Reference Cycles + +Be careful with metadata that might create reference cycles: + +```typescript +// Fails - non-string values are stored as JSON, which cannot represent cycles +const obj = {}; +obj.self = obj; + +await RunCache.set({ key: 'data', value: obj }); // throws: circular structure + +// Better - cache plain data without back-references +await RunCache.set({ + key: 'data', + value: { id: 123, type: 'example' } +}); +``` + +### 3. Monitor Memory Usage + +Implement memory usage monitoring: + +```typescript +// Periodically check memory usage +setInterval(async () => { + if (process.memoryUsage) { + const memUsage = process.memoryUsage(); + console.log(`Memory usage: ${Math.round(memUsage.heapUsed / 1024 / 1024)} MB`); + + // If memory usage is too high, clear some cache + if (memUsage.heapUsed > MEMORY_THRESHOLD) { + console.log('Memory usage too high, clearing temporary cache entries'); + await RunCache.delete('temp:*'); + } + } +}, 60000); // Check every minute +``` + +## Next Steps + +Now that you understand resource management, explore these related topics: + +- [Eviction Policies](../features/eviction-policies.md) - Learn more about cache eviction strategies +- [TTL and Expiration](../features/ttl-expiration.md) - Understand time-to-live functionality +- [Persistent Storage](./persistent-storage.md) - Learn about saving cache data across application restarts +- [Middleware](./middleware.md) - Explore how to intercept and transform cache operations \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/serialization-adapters.md b/gitbook-versions/v1.7/advanced/serialization-adapters.md new file mode 100644 index 0000000..d0905ae --- /dev/null +++ b/gitbook-versions/v1.7/advanced/serialization-adapters.md @@ -0,0 +1,80 @@ +# Value Serialization + +RunCache stores every entry as a string. Strings are stored exactly as given; any other value is converted with `JSON.stringify` when it is set and converted back with `JSON.parse` when it is read. You do not need to serialize values yourself. + +```typescript +import { RunCache } from 'run-cache'; + +await RunCache.set({ key: 'user:1', value: { name: 'Ada', roles: ['admin'] } }); + +const user = await RunCache.get<{ name: string; roles: string[] }>('user:1'); +console.log(user); // { name: 'Ada', roles: ['admin'] }, an object, not a string +``` + +The same applies to values returned by a `sourceFn`, on the first fetch and on every refetch, and to values restored from a [storage adapter](persistent-storage.md). + +## What round-trips + +Because the conversion is plain JSON, a value comes back exactly as it went in only if JSON can represent it: + +| Value you set | What `get()` returns | +| --- | --- | +| `'hello'`, `''`, `'{"a":1}'` (any string) | The same string. Strings are never parsed, even if they look like JSON | +| `42`, `0`, `true`, `false` | The same number or boolean | +| `null` | `null` | +| Plain objects and arrays of the above | An equal object or array | +| `undefined` inside an object | The property is dropped | +| `NaN`, `Infinity` | `null` | +| `Date` | Its ISO string, e.g. `"2026-01-01T00:00:00.000Z"` | +| `Map`, `Set`, `RegExp` | `{}` (their contents are lost) | +| A class instance | A plain object with its own enumerable properties; methods and prototype are lost | +| `BigInt` | `set()` throws, because JSON cannot represent it | + +Setting `value: undefined` is the same as not passing a value, so `set()` then needs a `sourceFn`. + +## Storing types JSON cannot represent + +RunCache does not have pluggable serializers. Convert such values to a JSON-friendly shape before you set them, and back after you read them: + +```typescript +// Date +await RunCache.set({ key: 'last-sync', value: new Date().toISOString() }); +const lastSync = new Date((await RunCache.get('last-sync')) as string); + +// Map and Set +const permissions = new Map([['read', true], ['write', false]]); +await RunCache.set({ key: 'permissions', value: [...permissions] }); +const restored = new Map((await RunCache.get<[string, boolean][]>('permissions')) as [string, boolean][]); + +// BigInt +await RunCache.set({ key: 'balance', value: (10n ** 20n).toString() }); +const balance = BigInt((await RunCache.get('balance')) as string); +``` + +A small helper keeps the conversion in one place: + +```typescript +interface Session { + userId: string; + expiresAt: Date; +} + +async function setSession(key: string, session: Session) { + await RunCache.set({ key, value: { ...session, expiresAt: session.expiresAt.toISOString() } }); +} + +async function getSession(key: string): Promise { + const raw = (await RunCache.get(key)) as { userId: string; expiresAt: string } | undefined; + return raw && { ...raw, expiresAt: new Date(raw.expiresAt) }; +} +``` + +## Serialization and middleware + +[Middleware](middleware.md) runs on the stored form of a value, so the `value` a middleware receives is always a string (or `undefined`). On `set`, objects have already been converted to JSON; on `get`, the value is parsed after the middleware chain has run. A middleware that transforms strings symmetrically, such as encryption or compression, therefore works for any value type. + +## Next Steps + +- [Type Safety](type-validation.md) - Typed reads and runtime checks +- [Middleware](middleware.md) - Transform values on their way in and out +- [Persistent Storage](persistent-storage.md) - How serialized entries are saved diff --git a/gitbook-versions/v1.7/advanced/tag-invalidation.md b/gitbook-versions/v1.7/advanced/tag-invalidation.md new file mode 100644 index 0000000..f7692d6 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/tag-invalidation.md @@ -0,0 +1,620 @@ +# Tag-based Invalidation + +Tag-based invalidation is a powerful feature in RunCache that allows you to group related cache entries and invalidate them together. This guide explains how to use tags effectively in your applications. + +## Understanding Tag-based Invalidation + +Tag-based invalidation allows you to: +- Group related cache entries under common tags +- Invalidate multiple cache entries at once using a single tag +- Create flexible grouping schemes independent of key naming +- Implement complex invalidation strategies + +## Basic Usage + +### Adding Tags to Cache Entries + +When setting a cache entry, you can assign one or more tags to it: + +```typescript +// Set a cache entry with tags +await RunCache.set({ + key: 'user:1:profile', + value: { name: 'John Doe', email: 'john@example.com' }, + tags: ['user:1', 'profile'] +}); + +// Another entry with some overlapping tags +await RunCache.set({ + key: 'user:1:settings', + value: { theme: 'dark', notifications: true }, + tags: ['user:1', 'settings'] +}); + +// Entry for a different user +await RunCache.set({ + key: 'user:2:profile', + value: { name: 'Jane Smith', email: 'jane@example.com' }, + tags: ['user:2', 'profile'] +}); +``` + +In this example: +- Both `user:1:profile` and `user:1:settings` are tagged with `user:1` +- Both `user:1:profile` and `user:2:profile` are tagged with `profile` +- `user:1:settings` is uniquely tagged with `settings` + +### Invalidating by Tag + +To invalidate all cache entries with a specific tag: + +```typescript +// Invalidate all entries tagged with 'user:1' +await RunCache.invalidateByTag('user:1'); +``` + +This would invalidate both `user:1:profile` and `user:1:settings`, but not `user:2:profile`. + +Similarly: + +```typescript +// Invalidate all profile entries +await RunCache.invalidateByTag('profile'); +``` + +This would invalidate both `user:1:profile` and `user:2:profile`, but not `user:1:settings`. + +## Tag Design Strategies + +### Hierarchical Tags + +You can create hierarchical relationships using tag naming conventions: + +```typescript +// Set cache entries with hierarchical tags +await RunCache.set({ + key: 'product:1:details', + value: { name: 'Product 1', price: 99.99 }, + tags: ['product', 'product:1', 'product:details'] +}); + +await RunCache.set({ + key: 'product:1:reviews', + value: [{ rating: 5, text: 'Great product!' }], + tags: ['product', 'product:1', 'product:reviews'] +}); + +await RunCache.set({ + key: 'product:2:details', + value: { name: 'Product 2', price: 149.99 }, + tags: ['product', 'product:2', 'product:details'] +}); +``` + +This allows for flexible invalidation: + +```typescript +// Invalidate all product data +await RunCache.invalidateByTag('product'); + +// Invalidate all data for product 1 +await RunCache.invalidateByTag('product:1'); + +// Invalidate details for all products +await RunCache.invalidateByTag('product:details'); +``` + +### Role-based Tags + +Tags can represent roles or categories: + +```typescript +// Set cache entries with role-based tags +await RunCache.set({ + key: 'user:1:dashboard', + value: { widgets: [...] }, + tags: ['user:1', 'dashboard', 'admin-view'] +}); + +await RunCache.set({ + key: 'user:2:dashboard', + value: { widgets: [...] }, + tags: ['user:2', 'dashboard', 'customer-view'] +}); + +await RunCache.set({ + key: 'global:admin-settings', + value: { settings: [...] }, + tags: ['global', 'admin-view'] +}); +``` + +This allows for role-based invalidation: + +```typescript +// Invalidate all admin views when admin settings change +await RunCache.invalidateByTag('admin-view'); + +// Invalidate all dashboards +await RunCache.invalidateByTag('dashboard'); +``` + +### Version Tags + +Tags can be used for version-based invalidation: + +```typescript +// Set cache entries with version tags +await RunCache.set({ + key: 'app:config', + value: { theme: 'light', features: [...] }, + tags: ['config', 'v1.2.3'] +}); + +await RunCache.set({ + key: 'app:translations', + value: { en: {...}, es: {...} }, + tags: ['translations', 'v1.2.3'] +}); +``` + +When a new version is deployed: + +```typescript +// Invalidate all cache entries from the previous version +await RunCache.invalidateByTag('v1.2.3'); + +// Set new cache entries with the new version tag +await RunCache.set({ + key: 'app:config', + value: { theme: 'dark', features: [...] }, + tags: ['config', 'v1.3.0'] +}); +``` + +## Monitoring Tag Invalidations + +RunCache provides events to monitor tag invalidations: + +```typescript +// Global tag invalidation event +await RunCache.onTagInvalidation((event) => { + console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); +}); + +// Specific key tag invalidation +await RunCache.onKeyTagInvalidation("user:1:profile", (event) => { + console.log(`User profile was invalidated by tag: ${event.tag}`); +}); + +// Pattern-based tag invalidation events +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { + console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +Each entry is removed before its event is emitted, so listeners see the cache in its invalidated state: `RunCache.has(event.key)` returns `false`, while `event.value` still holds the removed value. An error thrown by a listener does not stop the remaining entries from being invalidated. The same applies to dependency invalidation events. + +## Combining Tags with Other Features + +### Tags with TTL + +Combine tags with TTL for time-based invalidation: + +```typescript +// Set cache entry with tags and TTL +await RunCache.set({ + key: 'weather:nyc', + value: { temp: 72, conditions: 'sunny' }, + tags: ['weather', 'location:nyc'], + ttl: 3600000 // 1 hour +}); + +// Set cache entry with tags and TTL +await RunCache.set({ + key: 'weather:la', + value: { temp: 85, conditions: 'clear' }, + tags: ['weather', 'location:la'], + ttl: 3600000 // 1 hour +}); +``` + +This allows for both time-based expiration and manual invalidation: + +```typescript +// Invalidate all weather data regardless of TTL +await RunCache.invalidateByTag('weather'); + +// Invalidate just NYC weather data +await RunCache.invalidateByTag('location:nyc'); +``` + +### Tags with Source Functions + +Combine tags with source functions for automatic refreshing: + +```typescript +// Set cache entry with tags and source function +await RunCache.set({ + key: 'stock:AAPL', + sourceFn: async () => { + const response = await fetch('https://api.example.com/stocks/AAPL'); + const data = await response.json(); + return data; + }, + tags: ['stock', 'tech-stock'], + ttl: 60000, // 1 minute + autoRefetch: true +}); + +await RunCache.set({ + key: 'stock:MSFT', + sourceFn: async () => { + const response = await fetch('https://api.example.com/stocks/MSFT'); + const data = await response.json(); + return data; + }, + tags: ['stock', 'tech-stock'], + ttl: 60000, // 1 minute + autoRefetch: true +}); +``` + +This allows for both automatic refreshing and manual invalidation: + +```typescript +// Force refresh all tech stock data immediately +await RunCache.invalidateByTag('tech-stock'); +``` + +### Tags with Dependencies + +Combine tags with dependencies for complex invalidation strategies: + +```typescript +// Primary data with tags +await RunCache.set({ + key: 'products', + value: [...], + tags: ['product-data', 'catalog'] +}); + +// Dependent data with tags +await RunCache.set({ + key: 'featured-products', + value: [...], + dependencies: ['products'], + tags: ['product-data', 'featured'] +}); + +await RunCache.set({ + key: 'product-recommendations', + value: [...], + dependencies: ['products', 'user-preferences'], + tags: ['product-data', 'personalized'] +}); +``` + +This provides multiple ways to invalidate: + +```typescript +// Option 1: Invalidate by dependency (cascades to dependents) +await RunCache.invalidateByDependency('products'); + +// Option 2: Invalidate by tag (direct invalidation) +await RunCache.invalidateByTag('product-data'); + +// Option 3: Invalidate just personalized content +await RunCache.invalidateByTag('personalized'); +``` + +## Advanced Tag Patterns + +### Dynamic Tag Generation + +Generate tags dynamically based on data or context: + +```typescript +function generateUserTags(user) { + const tags = [`user:${user.id}`]; + + if (user.role) { + tags.push(`role:${user.role}`); + } + + if (user.subscriptionLevel) { + tags.push(`subscription:${user.subscriptionLevel}`); + } + + if (user.region) { + tags.push(`region:${user.region}`); + } + + return tags; +} + +// Usage +const user = await fetchUser(1); +await RunCache.set({ + key: `user:${user.id}:profile`, + value: user, + tags: generateUserTags(user) +}); +``` + +### Tag-based Prefetching + +Use tags to implement prefetching strategies: + +```typescript +// Listen for tag invalidations +await RunCache.onTagInvalidation((event) => { + if (event.tag === 'product-data') { + // Prefetch related data that might be needed soon + prefetchRelatedData(); + } +}); + +async function prefetchRelatedData() { + // Prefetch in the background + const relatedData = await fetchRelatedData(); + await RunCache.set({ + key: 'related-products', + value: relatedData, + tags: ['product-data', 'related'] + }); +} +``` + +### Conditional Tag Invalidation + +Implement conditional tag invalidation logic: + +```typescript +async function conditionalInvalidate(tag, condition) { + if (await condition()) { + console.log(`Invalidating tag: ${tag}`); + await RunCache.invalidateByTag(tag); + return true; + } + console.log(`Condition not met, tag ${tag} not invalidated`); + return false; +} + +// Usage +await conditionalInvalidate('user-data', async () => { + const lastUpdate = await getLastUpdateTimestamp('user-data'); + const threshold = Date.now() - (60 * 60 * 1000); // 1 hour ago + return lastUpdate < threshold; +}); +``` + +## Best Practices for Tag-based Invalidation + +### 1. Use Consistent Tag Naming Conventions + +Adopt a consistent tag naming convention: + +```typescript +// Good - consistent naming with clear hierarchy +tags: ['entity:user', 'user:1', 'type:profile'] + +// Avoid - inconsistent naming +tags: ['User', 'user_1', 'Profile'] +``` + +### 2. Keep Tag Lists Manageable + +Don't use too many tags per cache entry: + +```typescript +// Good - focused, relevant tags +tags: ['user:1', 'profile', 'settings'] + +// Avoid - too many tags +tags: ['user:1', 'profile', 'settings', 'john', 'doe', 'admin', 'active', 'verified', 'english', 'premium'] +``` + +### 3. Document Tag Schemas + +Document your tag naming conventions and schemas: + +```typescript +/** + * Tag Schema: + * - entity:{entityType} - The type of entity (user, product, etc.) + * - {entityType}:{id} - Specific entity instance (user:1, product:xyz) + * - type:{dataType} - The type of data (profile, settings, etc.) + * - role:{roleName} - User role (admin, customer, etc.) + * - region:{regionCode} - Geographic region (us, eu, etc.) + * - version:{versionNumber} - Application version + */ +``` + +### 4. Avoid Overly Generic Tags + +Be specific enough with tags to avoid unintended invalidations: + +```typescript +// Too generic - affects too many entries +tags: ['data'] + +// Better - more specific +tags: ['user-data'] + +// Best - most specific for the use case +tags: ['user:1:profile-data'] +``` + +### 5. Consider Tag Cardinality + +Be mindful of how many cache entries a tag might apply to: + +```typescript +// High cardinality - unique to one entry +tags: [`unique:${uuid()}`] // Avoid unless needed + +// Medium cardinality - applies to a reasonable group +tags: [`user:${userId}`] // Good for user-specific data + +// Low cardinality - applies to many entries +tags: ['global'] // Use carefully +``` + +## Common Tag-based Invalidation Use Cases + +### 1. User Data Invalidation + +Cache and invalidate user-specific data: + +```typescript +// Store user data with tags +await RunCache.set({ + key: `user:${userId}:profile`, + value: profile, + tags: [`user:${userId}`] +}); + +await RunCache.set({ + key: `user:${userId}:preferences`, + value: preferences, + tags: [`user:${userId}`] +}); + +await RunCache.set({ + key: `user:${userId}:activity`, + value: activity, + tags: [`user:${userId}`] +}); + +// When user data changes +async function handleUserDataChange(userId) { + // Invalidate all data for this user + await RunCache.invalidateByTag(`user:${userId}`); +} +``` + +### 2. Content Management + +Cache and invalidate content by category: + +```typescript +// Store content with category tags +await RunCache.set({ + key: `article:${articleId}`, + value: article, + tags: ['content', `category:${article.category}`, `author:${article.authorId}`] +}); + +// Invalidation scenarios +async function handleCategoryUpdate(category) { + // Invalidate all content in this category + await RunCache.invalidateByTag(`category:${category}`); +} + +async function handleAuthorUpdate(authorId) { + // Invalidate all content by this author + await RunCache.invalidateByTag(`author:${authorId}`); +} + +async function handleGlobalContentUpdate() { + // Invalidate all content + await RunCache.invalidateByTag('content'); +} +``` + +### 3. API Response Caching + +Cache API responses with appropriate tags: + +```typescript +async function cachedApiRequest(endpoint, params = {}, options = {}) { + // Generate a cache key based on the endpoint and params + const key = `api:${endpoint}:${JSON.stringify(params)}`; + + // Define tags based on the endpoint and params + const tags = ['api']; + tags.push(`api:${endpoint}`); + + if (params.userId) { + tags.push(`user:${params.userId}`); + } + + if (params.category) { + tags.push(`category:${params.category}`); + } + + // Check cache first + const cachedResponse = await RunCache.get(key); + if (cachedResponse !== undefined) { // false and 0 are valid cached responses + return cachedResponse; + } + + // If not in cache, make the API request + const response = await fetch(`https://api.example.com/${endpoint}`, { + method: 'POST', + body: JSON.stringify(params), + headers: { 'Content-Type': 'application/json' } + }); + + const data = await response.json(); + + // Cache the response with appropriate tags and TTL + await RunCache.set({ + key, + value: data, + tags, + ttl: options.ttl || 300000 // 5 minutes default + }); + + return data; +} + +// Usage +const userData = await cachedApiRequest('users/profile', { userId: 123 }); + +// When user data changes +async function invalidateUserApiCache(userId) { + await RunCache.invalidateByTag(`user:${userId}`); +} +``` + +### 4. Multi-level Caching + +Implement multi-level caching with tags: + +```typescript +// L1 cache (short TTL, frequently accessed) +await RunCache.set({ + key: 'dashboard:summary', + value: summary, + tags: ['dashboard', 'summary', 'l1-cache'], + ttl: 60000 // 1 minute +}); + +// L2 cache (longer TTL, less frequently accessed) +await RunCache.set({ + key: 'dashboard:details', + value: details, + tags: ['dashboard', 'details', 'l2-cache'], + ttl: 3600000 // 1 hour +}); + +// Selective invalidation +async function invalidateL1Cache() { + await RunCache.invalidateByTag('l1-cache'); +} + +async function invalidateDashboard() { + await RunCache.invalidateByTag('dashboard'); +} +``` + +## Next Steps + +Now that you understand tag-based invalidation, explore these related topics: + +- [Dependency Tracking](./dependency-tracking.md) - Learn about establishing relationships between cache entries +- [Event System](./event-system.md) - Understand how to use events for cache monitoring +- [Pattern Matching](../features/pattern-matching.md) - Learn about wildcard pattern matching for cache operations +- [Resource Management](./resource-management.md) - Learn about memory management and cleanup \ No newline at end of file diff --git a/gitbook-versions/v1.7/advanced/type-validation.md b/gitbook-versions/v1.7/advanced/type-validation.md new file mode 100644 index 0000000..c17e9f5 --- /dev/null +++ b/gitbook-versions/v1.7/advanced/type-validation.md @@ -0,0 +1,79 @@ +# Type Safety + +RunCache's typing is compile-time only. The generic parameter on `set`, `get` and `createTypedCache` tells TypeScript what you expect to find, but nothing checks the stored value at runtime. This page covers what the types give you and how to add a runtime check where you need one. + +## What the types guarantee + +```typescript +import { RunCache } from 'run-cache'; + +interface User { + id: number; + name: string; +} + +// The value is checked against User when you set it +await RunCache.set({ key: 'user:1', value: { id: 1, name: 'Ada' } }); + +// get() is typed as User | User[] | undefined: +// an array when the key is a wildcard pattern, undefined on a miss +const user = (await RunCache.get('user:1')) as User | undefined; +``` + +`createTypedCache()` fixes the type once for a group of keys, so every `set`, `get` and event callback uses `T`. See the [Typed Cache Interface](../api/typed-cache-interface.md). + +What the types do **not** guarantee: + +- A key set elsewhere with a different type is still returned as `T`. +- Data restored from a storage adapter, or written by an older version of your app, is returned as `T` whatever its shape. +- Values that JSON cannot represent (a `Date`, a `Map`, a class instance) come back in their JSON form, not as `T`. See [Value Serialization](serialization-adapters.md). + +RunCache does not export runtime validators, and no cache method accepts a validator option. + +## Adding a runtime check + +When a value may come from outside your control, check it after reading. A type guard keeps the check and the type together: + +```typescript +interface User { + id: number; + name: string; +} + +function isUser(value: unknown): value is User { + return ( + typeof value === 'object' && + value !== null && + typeof (value as User).id === 'number' && + typeof (value as User).name === 'string' + ); +} + +async function getUser(key: string): Promise { + const value = await RunCache.get(key); + if (value === undefined) return undefined; + if (!isUser(value)) { + // Drop the bad entry; the next get() returns undefined until you set it again + await RunCache.delete(key); + return undefined; + } + return value; +} +``` + +If you already use a schema library such as Zod, Valibot or io-ts, use its parser in place of the hand-written guard. Checking on read is usually enough; checking before `set()` as well catches bad data where it enters. + +## Wildcard reads + +A key containing `*` returns an array of every matching value, so narrow the result before treating it as a single value: + +```typescript +const result = await RunCache.get('user:*'); +const users = Array.isArray(result) ? result.filter(isUser) : []; +``` + +## Next Steps + +- [Typed Caching](../getting-started/typed-caching.md) - Using generics with RunCache +- [Typed Cache Interface](../api/typed-cache-interface.md) - API reference for `createTypedCache` +- [Value Serialization](serialization-adapters.md) - Which values round-trip unchanged diff --git a/gitbook-versions/v1.7/api/events.md b/gitbook-versions/v1.7/api/events.md new file mode 100644 index 0000000..cd2687d --- /dev/null +++ b/gitbook-versions/v1.7/api/events.md @@ -0,0 +1,647 @@ +# Events API Reference + +RunCache provides a comprehensive event system that allows you to monitor and respond to various cache lifecycle events. This page provides a complete reference for all event types, event objects, and event handling methods. + +## Event Types + +RunCache defines several event types in the `EVENT` enum: + +```typescript +enum EVENT { + EXPIRE = 'expire', + REFETCH = 'refetch', + REFETCH_FAILURE = 'refetch_failure', + TAG_INVALIDATION = 'tag_invalidation', + DEPENDENCY_INVALIDATION = 'dependency_invalidation' +} +``` + +Import the enum from the RunCache package: + +```typescript +import { RunCache, EVENT } from 'run-cache'; +``` + +## Event Objects + +Every listener receives an object of the exported `EventParam` type. The interfaces below describe which fields are set for each event; they are not exported under these names. + +### ExpiryEvent + +Triggered when a cache entry expires. + +```typescript +interface ExpiryEvent { + key: string; // The key of the expired entry + value: string; // The stored value at the time it expired (after middleware) + ttl: number; // The TTL value in milliseconds + createdAt: number; // Timestamp when the entry was created + updatedAt: number; // Timestamp when the entry was last updated +} +``` + +An expiry is reported exactly once per version of an entry. The event fires when the TTL timer elapses, or earlier if a `get()` or `has()` call notices the expiry first; it is never repeated for the same expiry. Each time an auto-refetched entry is refreshed it gets a new version, so its next expiry is reported again. An entry that is overwritten or deleted before its TTL elapses does not emit an expiry event. + +`value` is the stored string. For entries cached from non-string values (for example through a typed cache), it is the serialized form. + +### RefetchEvent + +Triggered when a cache entry is refreshed. + +```typescript +interface RefetchEvent { + key: string; // The key of the refreshed entry + value: string; // The value returned by the source function + ttl?: number; // The entry's TTL in milliseconds, if it has one + createdAt: number; // Timestamp of the refetch + updatedAt: number; // Timestamp of the refetch +} +``` + +### RefetchFailureEvent + +Triggered when a cache refresh operation fails. + +```typescript +interface RefetchFailureEvent { + key: string; // The key of the entry that failed to refresh + value: string; // The value still in the cache (the last successful one) + ttl?: number; // The entry's TTL in milliseconds, if it has one + createdAt: number; // Timestamp when the entry was created + updatedAt: number; // Timestamp of the last successful update + error: unknown; // The error thrown by the source function +} +``` + +`error` is exactly what the source function threw or rejected with, so you can inspect its type, status code or message. If the source function resolved to `undefined`, `error` is a `SourceFnError` describing that. + +### TagInvalidationEvent + +Triggered when a cache entry is invalidated by tag. + +```typescript +interface TagInvalidationEvent { + key: string; // The key of the invalidated entry + value: string; // The value the entry held + ttl?: number; // The entry's TTL in milliseconds, if it had one + createdAt: number; // Timestamp when the entry was created + updatedAt: number; // Timestamp when the entry was last updated + tag: string; // The tag that caused the invalidation +} +``` + +### DependencyInvalidationEvent + +Triggered when a cache entry is invalidated due to a dependency. + +```typescript +interface DependencyInvalidationEvent { + key: string; // The key of the invalidated entry + value: string; // The value the entry held + ttl?: number; // The entry's TTL in milliseconds, if it had one + createdAt: number; // Timestamp when the entry was created + updatedAt: number; // Timestamp when the entry was last updated + dependencyKey: string; // The key of the dependency that caused the invalidation +} +``` + +## Global Event Listeners + +Global event listeners are triggered for all cache entries that match the specified event type. + +### onExpiry + +Registers a callback for all expiry events. + +```typescript +await RunCache.onExpiry(callback: (event: ExpiryEvent) => void): Promise +``` + +**Parameters:** +- `callback`: Function to call when any entry expires + +**Example:** + +```typescript +await RunCache.onExpiry((event) => { + console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); +}); +``` + +### onRefetch + +Registers a callback for all refetch events. + +```typescript +await RunCache.onRefetch(callback: (event: RefetchEvent) => void): Promise +``` + +**Parameters:** +- `callback`: Function to call when any entry is refreshed + +**Example:** + +```typescript +await RunCache.onRefetch((event) => { + console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); +}); +``` + +### onRefetchFailure + +Registers a callback for all refetch failure events. + +```typescript +await RunCache.onRefetchFailure(callback: (event: RefetchFailureEvent) => void): Promise +``` + +**Parameters:** +- `callback`: Function to call when any refresh fails + +**Example:** + +```typescript +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}:`, event.error); +}); +``` + +### onTagInvalidation + +Registers a callback for all tag invalidation events. + +```typescript +await RunCache.onTagInvalidation(callback: (event: TagInvalidationEvent) => void): Promise +``` + +**Parameters:** +- `callback`: Function to call when any entry is invalidated by tag + +**Example:** + +```typescript +await RunCache.onTagInvalidation((event) => { + console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### onDependencyInvalidation + +Registers a callback for all dependency invalidation events. + +```typescript +await RunCache.onDependencyInvalidation(callback: (event: DependencyInvalidationEvent) => void): Promise +``` + +**Parameters:** +- `callback`: Function to call when any entry is invalidated by dependency + +**Example:** + +```typescript +await RunCache.onDependencyInvalidation((event) => { + console.log(`Cache key ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +## Key-Specific Event Listeners + +Key-specific event listeners are triggered only for cache entries with keys that match the specified key or pattern. + +### onKeyExpiry + +Registers a callback for expiry events for a specific key or pattern. + +```typescript +await RunCache.onKeyExpiry(key: string, callback: (event: ExpiryEvent) => void): Promise +``` + +**Parameters:** +- `key`: The key or pattern to watch +- `callback`: Function to call when matching entries expire + +**Example:** + +```typescript +// Specific key +await RunCache.onKeyExpiry("api-data", (event) => { + console.log(`API data cache expired`); +}); + +// Pattern matching +await RunCache.onKeyExpiry("user:*:profile", (event) => { + console.log(`User profile ${event.key} expired`); +}); +``` + +### onKeyRefetch + +Registers a callback for refetch events for a specific key or pattern. + +```typescript +await RunCache.onKeyRefetch(key: string, callback: (event: RefetchEvent) => void): Promise +``` + +**Parameters:** +- `key`: The key or pattern to watch +- `callback`: Function to call when matching entries are refreshed + +**Example:** + +```typescript +// Specific key +await RunCache.onKeyRefetch("weather-data", (event) => { + console.log(`Weather data was refreshed`); +}); + +// Pattern matching +await RunCache.onKeyRefetch("api:*:data", (event) => { + console.log(`API data ${event.key} was refreshed`); +}); +``` + +### onKeyRefetchFailure + +Registers a callback for refetch failure events for a specific key or pattern. + +```typescript +await RunCache.onKeyRefetchFailure(key: string, callback: (event: RefetchFailureEvent) => void): Promise +``` + +**Parameters:** +- `key`: The key or pattern to watch +- `callback`: Function to call when matching refreshes fail + +**Example:** + +```typescript +// Specific key +await RunCache.onKeyRefetchFailure("api-data", (event) => { + console.error(`API data refresh failed:`, event.error); +}); + +// Pattern matching +await RunCache.onKeyRefetchFailure("api:*", (event) => { + console.error(`API data ${event.key} refresh failed:`, event.error); +}); +``` + +### onKeyTagInvalidation + +Registers a callback for tag invalidation events for a specific key or pattern. + +```typescript +await RunCache.onKeyTagInvalidation(key: string, callback: (event: TagInvalidationEvent) => void): Promise +``` + +**Parameters:** +- `key`: The key or pattern to watch +- `callback`: Function to call when matching entries are invalidated by tag + +**Example:** + +```typescript +// Specific key +await RunCache.onKeyTagInvalidation("user:1:profile", (event) => { + console.log(`User profile was invalidated by tag: ${event.tag}`); +}); + +// Pattern matching +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { + console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### onKeyDependencyInvalidation + +Registers a callback for dependency invalidation events for a specific key or pattern. + +```typescript +await RunCache.onKeyDependencyInvalidation(key: string, callback: (event: DependencyInvalidationEvent) => void): Promise +``` + +**Parameters:** +- `key`: The key or pattern to watch +- `callback`: Function to call when matching entries are invalidated by dependency + +**Example:** + +```typescript +// Specific key +await RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { + console.log(`Main dashboard was invalidated due to dependency on: ${event.dependencyKey}`); +}); + +// Pattern matching +await RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { + console.log(`Dashboard ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +## Managing Event Listeners + +### clearEventListeners + +Removes event listeners based on the specified options. + +```typescript +await RunCache.clearEventListeners(options?: { + event?: EventName; + key?: string; +}): Promise +``` + +**Parameters:** +- `options?`: Options to specify which listeners to remove + - `event?`: The event type to remove listeners for. Only that exact event is affected: clearing `EVENT.REFETCH` leaves `EVENT.REFETCH_FAILURE` listeners in place. + - `key?`: The key or wildcard pattern to remove listeners for. Without `event`, the key's listeners are removed for every event type. + +With no options, every listener is removed. An options object that selects nothing, such as `{}` or `{ event: undefined }`, removes nothing and returns `false`. + +An exact key only clears listeners registered for that exact key. Wildcard listeners that match it, such as `api-*` for `api-data`, stay registered; clear them by passing the pattern itself. + +**Returns:** `Promise` - `true` if at least one listener was removed, `false` if there was nothing to remove. + +**Examples:** + +```typescript +// Remove all event listeners +await RunCache.clearEventListeners(); + +// Remove all expiry event listeners +await RunCache.clearEventListeners({ + event: EVENT.EXPIRE +}); + +// Remove all listeners for a specific key +await RunCache.clearEventListeners({ + key: "api-data" +}); + +// Remove specific event listeners for a key +await RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: "api-data" +}); + +// Check whether anything was removed +const removed = await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); +``` + +Removing a single handler is not supported; clear the event (and key) it was registered for and register the remaining handlers again. + +## Event Metadata + +Cache entries cannot carry custom metadata, and event objects only contain the fields listed in the [Events API](events.md). To associate extra information with a key, keep it in your own map: + +```typescript +const entryInfo = new Map(); + +await RunCache.set({ key: 'api-data', value: { results: [] } }); +entryInfo.set('api-data', { source: 'external-api', version: '1.0' }); + +await RunCache.onKeyExpiry('api-data', (event) => { + const info = entryInfo.get(event.key); + console.log(`API data expired. Source: ${info?.source}, Version: ${info?.version}`); +}); +``` + +## Practical Event System Use Cases + +### 1. Logging and Monitoring + +```typescript +// Set up logging for all major events +await RunCache.onExpiry((event) => { + logger.info(`Cache expired: ${event.key}`); +}); + +await RunCache.onRefetch((event) => { + logger.info(`Cache refreshed: ${event.key}`); +}); + +await RunCache.onRefetchFailure((event) => { + logger.error(`Cache refresh failed: ${event.key}`, event.error); +}); + +await RunCache.onTagInvalidation((event) => { + logger.info(`Cache invalidated by tag: ${event.key} (tag: ${event.tag})`); +}); + +await RunCache.onDependencyInvalidation((event) => { + logger.info(`Cache invalidated by dependency: ${event.key} (depends on: ${event.dependencyKey})`); +}); +``` + +### 2. Implementing Retry Logic + +```typescript +// Set up retry logic with exponential backoff +// Attempts per key; RunCache events carry no custom metadata +const retryCounts = new Map(); + +await RunCache.onRefetchFailure((event) => { + const retryCount = (retryCounts.get(event.key) ?? 0) + 1; + retryCounts.set(event.key, retryCount); + + if (retryCount <= 3) { + const delay = Math.pow(2, retryCount) * 1000; // Exponential backoff + console.log(`Retrying ${event.key} in ${delay}ms (attempt ${retryCount})`); + + setTimeout(() => { + RunCache.refetch(event.key) + .catch(() => { /* reported again through onRefetchFailure */ }); + }, delay); + } else { + console.error(`Failed to refresh ${event.key} after ${retryCount} attempts`); + } +}); + +// Any successful refresh (a retry, a manual refetch or an automatic one) resets the +// count, so a key that recovers gets a full retry sequence the next time it fails. +await RunCache.onRefetch((event) => { + retryCounts.delete(event.key); +}); +``` + +### 3. UI Updates + +```typescript +// One RunCache listener per key, shared by every component that shows that key. +// clearEventListeners() removes *all* listeners for an event and key, so a component +// that clears on unmount would also remove the listener of another component, or of +// a newer effect run, watching the same key. Components subscribe here instead and +// remove only their own callback. +const refetchSubscribers = new Map void>>(); + +function subscribeToRefetch(key: string, callback: () => void): () => void { + let callbacks = refetchSubscribers.get(key); + if (!callbacks) { + const created = new Set<() => void>(); + callbacks = created; + refetchSubscribers.set(key, created); + // Registered once per key and kept; it does nothing while no callback is subscribed. + RunCache.onKeyRefetch(key, () => created.forEach((cb) => cb())) + .catch((error) => console.error(`Could not watch ${key}`, error)); + } + const own = callbacks; + own.add(callback); + return () => { own.delete(callback); }; +} + +// React component example +function UserProfile({ userId }) { + const [profile, setProfile] = useState(null); + + useEffect(() => { + const key = `user:${userId}:profile`; + + let active = true; + + // get() returns the stored object, no parsing needed + const load = async () => { + const data = await RunCache.get(key); + if (active && data !== undefined) setProfile(data); + }; + + // This effect run owns only its own callback; the cleanup removes just that one, + // so a newer run (or another component) watching the same key keeps its updates. + const unsubscribe = subscribeToRefetch(key, () => { load().catch(console.error); }); + load().catch(console.error); + + return () => { + active = false; // ignore a load that finishes after cleanup + unsubscribe(); + }; + }, [userId]); + + // Render profile... +} +``` + +### 4. Cache Analytics + +```typescript +// Set up analytics tracking +let metrics = { + expiryCount: 0, + refetchCount: 0, + refetchFailureCount: 0, + tagInvalidationCount: 0, + dependencyInvalidationCount: 0 +}; + +await RunCache.onExpiry(() => metrics.expiryCount++); +await RunCache.onRefetch(() => metrics.refetchCount++); +await RunCache.onRefetchFailure(() => metrics.refetchFailureCount++); +await RunCache.onTagInvalidation(() => metrics.tagInvalidationCount++); +await RunCache.onDependencyInvalidation(() => metrics.dependencyInvalidationCount++); + +// Report metrics periodically +setInterval(() => { + console.log('Cache metrics:', metrics); + // Send metrics to monitoring system + sendMetricsToMonitoring(metrics); + + // Reset counters + metrics = { + expiryCount: 0, + refetchCount: 0, + refetchFailureCount: 0, + tagInvalidationCount: 0, + dependencyInvalidationCount: 0 + }; +}, 60000); // Every minute +``` + +## Best Practices for Event Handling + +### 1. Keep Event Handlers Lightweight + +Event handlers should be fast and non-blocking: + +```typescript +// Good - lightweight handler +await RunCache.onExpiry((event) => { + console.log(`Cache expired: ${event.key}`); +}); + +// Avoid - heavy processing in handler +await RunCache.onExpiry(async (event) => { + // DON'T do this - blocks the event loop + await heavyProcessing(); + await networkRequest(); +}); +``` + +If you need to perform heavy work, delegate it to a separate process or queue. + +### 2. Handle Errors in Event Handlers + +RunCache isolates listeners from cache operations. If a listener throws, or an `async` listener rejects, the error is written to `console.error` (naming the event and key), the remaining listeners still run, and the cache operation that emitted the event completes normally. A failing listener can therefore never abort an invalidation, crash the process from an expiry timer, or cause an unhandled promise rejection. The error is not passed back to the code that triggered the event. To route listener errors to your own logging instead of the console, set `onListenerError`: + +```typescript +await RunCache.configure({ + onListenerError: (error, { event, key }) => logger.error({ err: error, event, key }, 'RunCache listener failed'), +}); +``` + +To react to errors inside a specific listener, handle them there: + +```typescript +// Good - error handling +await RunCache.onRefetch((event) => { + try { + processRefetchEvent(event); + } catch (error) { + console.error('Error in refetch handler:', error); + } +}); +``` + +### 3. Use Specific Key Patterns + +Use specific key patterns to minimize unnecessary event processing: + +```typescript +// Too broad - triggers for all keys +await RunCache.onKeyExpiry('*', (event) => { + // This will run for EVERY expiry +}); + +// Better - more specific pattern +await RunCache.onKeyExpiry('api:*', (event) => { + // This will only run for API-related expirations +}); +``` + +### 4. Clean Up Event Listeners + +Remove event listeners when they're no longer needed: + +```typescript +// In a component or module initialization +async function initializeModule() { + // Set up event listeners + await RunCache.onKeyRefetch('module-data', handleRefetch); + + // Return cleanup function + return () => + RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: 'module-data' + }); +} + +// Later, when shutting down +const cleanup = await initializeModule(); +// When module is unloaded +await cleanup(); +``` + +## Next Steps + +- [RunCache API](./run-cache.md) - Learn about the main RunCache API +- [Storage Adapters](./storage-adapters.md) - Understand persistent storage options +- [Types](./types.md) - Explore TypeScript type definitions +- [Event System](../advanced/event-system.md) - Learn more about using events in your application \ No newline at end of file diff --git a/gitbook-versions/v1.7/api/run-cache.md b/gitbook-versions/v1.7/api/run-cache.md new file mode 100644 index 0000000..33f2ca0 --- /dev/null +++ b/gitbook-versions/v1.7/api/run-cache.md @@ -0,0 +1,774 @@ +# RunCache API Reference + +This page provides a complete reference for the RunCache class, including all methods, parameters, and return types. + +## Class: RunCache + +The main class that provides caching functionality. All methods are static and can be called directly on the RunCache class. + +## Configuration Methods + +### `configure(config)` + +Configures the cache with global settings. + +**Parameters:** + +- `config`: `CacheConfig` - Configuration object with the following properties: + - `maxEntries?`: `number` - Maximum number of entries before eviction (default: unlimited) + - `evictionPolicy?`: `EvictionPolicy` - Eviction policy to use (default: NONE) + - `debug?`: `boolean` - Enable debug logging (default: false) + - `handleProcessSignals?`: `boolean` - Shut the cache down (saving to the storage adapter) on `SIGTERM`/`SIGINT` in Node.js and on `beforeunload` in browsers (default: false). In Node.js the signal is re-raised after shutdown unless your application has its own listener, so the process exits as it would without RunCache. Importing RunCache installs no handlers unless this is enabled. + - `onListenerError?`: `(error, { event, key }) => void` - Receives errors thrown (or rejected) by event listeners. By default they are written to `console.error`; listener errors never reach the cache operation that emitted the event. + - `storageAdapter?`: `StorageAdapter` - Storage adapter for persistence (default: none). Attaching an adapter loads the data it already holds; if a different adapter was attached before, the current entries are saved to it first, and `configure()` rejects (keeping that adapter) if the save fails. The `maxEntries` and `evictionPolicy` stored with the data are not applied. Pass `undefined` to detach persistence. + +**Returns:** `Promise` - resolves once the configuration is applied, including loading from a newly attached storage adapter + +**Example:** + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU, + debug: true +}); +``` + +### `getConfig()` + +Gets the current cache configuration. + +**Returns:** `Promise` - A copy of the current configuration + +**Example:** + +```typescript +const config = await RunCache.getConfig(); +console.log(config); // { maxEntries: 1000, evictionPolicy: "LRU", debug: true } +``` + +## Cache Operations + +### `set(options)` + +Sets a cache entry with the specified options. Strings are stored as-is; any other value is stored as JSON and parsed again by `get()`, so it must be JSON-serializable (see [Value Serialization](../advanced/serialization-adapters.md)). + +**Type Parameters:** + +- `T` - The type of value being cached (defaults to `string` for backward compatibility) + +**Parameters:** + +- `options`: `Object` - Cache entry options + - `key`: `string` - Unique identifier for the cache entry + - `value?`: `T` - Value to cache (required if no sourceFn). An empty string is a valid value. + - `ttl?`: `number` - Time-to-live in milliseconds. Must be a finite, positive number; omit it for entries that never expire. TTLs longer than the `setTimeout` limit (about 24.8 days) are supported. + - `autoRefetch?`: `boolean` - Automatically refetch on expiry (requires ttl and sourceFn) + - `sourceFn?`: `() => T | Promise` - Function to generate cache value (required if no value) + - `tags?`: `string[]` - Array of tags for tag-based invalidation + - `dependencies?`: `string[]` - Array of cache keys this entry depends on. The entry is invalidated automatically when any of them changes. Overwriting an existing key with `set()` also invalidates the entries that depend on it. + +**Returns:** `Promise` - Returns `true` if the value was successfully set. Returns `false` if another `set()` for the same key started later and has already written its value while this one was still waiting for its `sourceFn` or middleware; the newer value is kept. A later `set()` that fails does not affect an earlier one. `delete()` and `flush()` act on what is cached when they run, so they do not cancel a `set()` that is still waiting for its value. + +**Throws:** +- `Error` - If key is empty +- `Error` - If neither value nor sourceFn is provided +- `Error` - If autoRefetch is true but ttl or sourceFn is not provided +- `Error` - If ttl is `0` or negative (`` `ttl` cannot be negative ``), not a number or `NaN` (`` `ttl` must be a number ``), or `Infinity` (`` `ttl` must be a finite number ``) +- `Error` - If `dependencies` contains the key itself, or would create a cycle (`Circular dependency detected`) +- `SourceFnError` - If the source function throws or rejects (the original error is in `error.cause`), or resolves to `undefined` +- `MiddlewareError` - If a middleware throws (original error in `error.cause`) or produces `undefined` + +`SourceFnError` and `MiddlewareError` extend `RunCacheError`, which extends `Error` and also carries the cache `key`. All three are exported from `run-cache`. + +**Example:** + +```typescript +// Basic string usage (backward compatible) +await RunCache.set({ key: 'greeting', value: 'Hello, World!' }); + +// Typed object caching +interface User { + id: number; + name: string; + email: string; +} + +const user: User = { id: 1, name: 'John', email: 'john@example.com' }; +await RunCache.set({ key: 'user:1', value: user }); + +// Array caching with types +await RunCache.set({ key: 'scores', value: [95, 87, 92] }); + +// With TTL (a Date would come back as a string, so store the ISO string) +await RunCache.set({ + key: 'last-update', + value: new Date().toISOString(), + ttl: 60000 +}); + +// Typed source function +await RunCache.set({ + key: 'api-user', + sourceFn: async (): Promise => { + const response = await fetch('https://api.example.com/user'); + return response.json(); // Returns typed User object + }, + ttl: 300000 +}); + +// With auto-refetch and types +await RunCache.set<{ temperature: number; humidity: number }>({ + key: 'weather', + sourceFn: () => fetchWeatherData(), + ttl: 600000, + autoRefetch: true +}); + +// With tags and dependencies +await RunCache.set({ + key: 'user:1:profile', + value: user, + tags: ['user:1', 'profile'], + dependencies: ['user:1:session'] +}); +``` + +### `get(key)` + +Retrieves a cache entry by key or pattern with full type safety. + +**Type Parameters:** + +- `T` - The expected type of the cached value (defaults to `string` for backward compatibility) + +**Parameters:** + +- `key`: `string` - The key to retrieve, or a pattern with wildcards + +**Returns:** `Promise` +- If `key` is a specific key, returns the typed value or undefined if not found +- If `key` is a pattern, returns an array of matching typed values + +Values stored as strings are returned unchanged, even if they look like JSON (`"123"`, `"true"`, `'{"a":1}'`). Only values that were stored from non-string types are deserialized. + +**Example:** + +```typescript +// Get a specific string entry (backward compatible) +const greeting = await RunCache.get('greeting'); +console.log(greeting); // "Hello, World!" + +// Get typed object +interface User { + id: number; + name: string; + email: string; +} + +const user = await RunCache.get('user:1'); +if (user) { + console.log(user.name); // TypeScript knows this is a string + console.log(user.id); // TypeScript knows this is a number +} + +// Get typed array +const scores = await RunCache.get('scores'); +if (scores) { + const average = scores.reduce((a, b) => a + b) / scores.length; +} + +// Get entries matching a pattern with types +const userProfiles = await RunCache.get('user:*:profile'); +if (Array.isArray(userProfiles)) { + userProfiles.forEach(profile => { + console.log(`User: ${profile.name} (${profile.email})`); + }); +} + +// Complex typed retrieval +interface ApiResponse { + success: boolean; + data: T; + timestamp: number; +} + +const response = await RunCache.get>('api:users'); +if (response?.success) { + response.data.forEach(user => console.log(user.name)); +} +``` + +### `has(key)` + +Checks if a valid (non-expired) cache entry exists. + +**Parameters:** + +- `key`: `string` - The key to check, or a pattern with wildcards + +**Returns:** `Promise` +- If `key` is a specific key, returns true if it exists and hasn't expired +- If `key` is a pattern, returns true if any matching key exists + +**Example:** + +```typescript +// Check if a specific key exists +const hasGreeting = await RunCache.has('greeting'); +console.log(hasGreeting); // true or false + +// Check if any keys match a pattern +const hasUserData = await RunCache.has('user:1:*'); +console.log(hasUserData); // true or false +``` + +### `delete(key)` + +Removes a cache entry or entries matching a pattern. + +**Parameters:** + +- `key`: `string` - The key to delete, or a pattern with wildcards + +**Returns:** `Promise` - `true` if at least one entry was deleted + +**Example:** + +```typescript +// Delete a specific entry +await RunCache.delete('greeting'); + +// Delete entries matching a pattern +await RunCache.delete('user:1:*'); +``` + +### `flush()` + +Removes all cache entries. + +**Returns:** `Promise` + +**Example:** + +```typescript +// Clear the entire cache +await RunCache.flush(); +``` + +### `refetch(key)` + +Manually refreshes a cache entry or entries matching a pattern by running their stored `sourceFn`. + +**Parameters:** + +- `key`: `string` - The key to refresh, or a pattern with wildcards + +**Returns:** `Promise` +- `true` if the entry (or, for a pattern, at least one matching entry) was refreshed +- `false` if the key does not exist, has no source function, is already being refetched, or was changed while its source function was running + +If an entry is deleted, flushed, evicted, invalidated or overwritten with `set()` while its refetch is in progress, the refetch result is discarded. The entry is not re-created and no `refetch` event is emitted. + +**Throws:** +- `SourceFnError` - If the source function of a single key throws or resolves to `undefined`. The original error is in `error.cause`, the previous value stays in the cache, and a `refetch_failure` event is emitted with the same error in `event.error`. +- `MiddlewareError` - If a middleware throws (original error in `error.cause`) or produces `undefined` for the new value. The previous value stays in the cache. + +**Example:** + +```typescript +// Refresh a specific entry +await RunCache.refetch('api-data'); + +// Refresh entries matching a pattern +await RunCache.refetch('user:*:profile'); + +``` + +## Tag Operations + +### `invalidateByTag(tag)` + +Invalidates all cache entries with the specified tag. + +**Parameters:** + +- `tag`: `string` - The tag to invalidate + +**Returns:** `Promise` - `true` if at least one entry was invalidated + +**Example:** + +```typescript +// Invalidate all entries with the 'user:1' tag +await RunCache.invalidateByTag('user:1'); +``` + +## Dependency Operations + +### `invalidateByDependency(key)` + +Invalidates all entries that depend on `key`, directly or indirectly. The entry for `key` itself is kept. Each invalidated entry emits a `dependency_invalidation` event with `dependencyKey` set to `key`. + +You only need this to invalidate dependents explicitly. The same cascade runs automatically when `key` is updated with `set()`, refetched, deleted, evicted, invalidated by tag or expires. + +**Parameters:** + +- `key`: `string` - The key whose dependents should be invalidated + +**Returns:** `Promise` - `true` if at least one entry was invalidated + +**Example:** + +```typescript +// Invalidate every entry that depends on 'user:1:profile' +await RunCache.invalidateByDependency('user:1:profile'); +``` + +### `isDependencyOf(key, dependencyKey)` + +Checks if one entry depends on another (directly or indirectly). + +**Parameters:** + +- `key`: `string` - The key to check +- `dependencyKey`: `string` - The potential dependency key + +**Returns:** `Promise` - True if key depends on dependencyKey. Returns false if `key`, or an intermediate entry in the chain, does not exist or has expired. + +This is a read-only check: it does not count as an access for eviction, emit events or remove expired entries. + +**Example:** + +```typescript +// Check if 'dashboard' depends on 'user:1:profile' +const isDependency = await RunCache.isDependencyOf('dashboard', 'user:1:profile'); +console.log(isDependency); // true or false +``` + +## Event System + +### `onExpiry(callback)` + +Registers a callback for all expiry events. + +**Parameters:** + +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry expires + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onExpiry((event) => { + console.log(`Cache key ${event.key} expired`); +}); +``` + +### `onKeyExpiry(key, callback)` + +Registers a callback for expiry events for a specific key or pattern. + +**Parameters:** + +- `key`: `string` - The key or pattern to watch +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries expire + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onKeyExpiry('api-data', (event) => { + console.log('API data expired'); +}); + +await RunCache.onKeyExpiry('user:*:profile', (event) => { + console.log(`User profile ${event.key} expired`); +}); +``` + +### `onRefetch(callback)` + +Registers a callback for all refetch events. + +**Parameters:** + +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is refreshed + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onRefetch((event) => { + console.log(`Cache key ${event.key} was refreshed`); +}); +``` + +### `onKeyRefetch(key, callback)` + +Registers a callback for refetch events for a specific key or pattern. + +**Parameters:** + +- `key`: `string` - The key or pattern to watch +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are refreshed + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onKeyRefetch('weather-data', (event) => { + console.log('Weather data was refreshed'); +}); +``` + +### `onRefetchFailure(callback)` + +Registers a callback for all refetch failure events. + +**Parameters:** + +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any refresh fails + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh ${event.key}:`, event.error); +}); +``` + +### `onKeyRefetchFailure(key, callback)` + +Registers a callback for refetch failure events for a specific key or pattern. + +**Parameters:** + +- `key`: `string` - The key or pattern to watch +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching refreshes fail + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onKeyRefetchFailure('api-data', (event) => { + console.error(`API data refresh failed: ${event.key}`, event.error); +}); +``` + +### `onTagInvalidation(callback)` + +Registers a callback for all tag invalidation events. + +**Parameters:** + +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is invalidated by tag + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onTagInvalidation((event) => { + console.log(`${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### `onKeyTagInvalidation(key, callback)` + +Registers a callback for tag invalidation events for a specific key or pattern. + +**Parameters:** + +- `key`: `string` - The key or pattern to watch +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are invalidated by tag + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onKeyTagInvalidation('user:*:profile', (event) => { + console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); +}); +``` + +### `onDependencyInvalidation(callback)` + +Registers a callback for all dependency invalidation events. + +**Parameters:** + +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is invalidated by dependency + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onDependencyInvalidation((event) => { + console.log(`${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +### `onKeyDependencyInvalidation(key, callback)` + +Registers a callback for dependency invalidation events for a specific key or pattern. + +**Parameters:** + +- `key`: `string` - The key or pattern to watch +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are invalidated by dependency + +**Returns:** `Promise` + +**Example:** + +```typescript +await RunCache.onKeyDependencyInvalidation('dashboard:*', (event) => { + console.log(`Dashboard ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); +}); +``` + +### `clearEventListeners(options?)` + +Removes event listeners based on the specified options. + +**Parameters:** + +- `options?`: `Object` - Options to specify which listeners to remove. With no options, every listener is removed; an object that selects nothing (`{}`) removes nothing. + - `event?`: `EventName` - The event type to remove listeners for. Only that exact event is affected; for example, clearing `EVENT.REFETCH` keeps `EVENT.REFETCH_FAILURE` listeners. + - `key?`: `string` - The key or wildcard pattern to remove listeners for. Without `event`, the key's listeners are removed for every event type. An exact key does not remove wildcard listeners that match it. + +**Returns:** `Promise` - `true` if at least one listener was removed, `false` if there was nothing to remove. + +**Example:** + +```typescript +// Remove all event listeners +await RunCache.clearEventListeners(); + +// Remove all expiry listeners +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); + +// Remove listeners for a specific key +await RunCache.clearEventListeners({ key: 'api-data' }); + +// Remove specific event listeners for a key +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'api-data' }); +``` + +## Middleware + +### `use(middleware)` + +Adds a middleware function to intercept and transform cache operations. + +**Parameters:** + +- `middleware`: `MiddlewareFunction` - The middleware function to add + +**Returns:** `Promise` + +**Example:** + +```typescript +// Add a logging middleware +await RunCache.use(async (value, context, next) => { + console.log(`${context.operation} operation for key: ${context.key}`); + return next(value); +}); + +// Add an encryption middleware +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + return next(encrypt(value)); + } else if (context.operation === 'get' && value) { + const encrypted = await next(value); + return encrypted ? decrypt(encrypted) : undefined; + } + return next(value); +}); +``` + +### `clearMiddleware()` + +Removes all middleware functions. + +**Returns:** `Promise` + +**Example:** + +```typescript +// Remove all middleware +await RunCache.clearMiddleware(); +``` + +## Storage Operations + +### `setupAutoSave(interval)` + +Configures automatic saving to persistent storage. + +**Parameters:** + +- `interval`: `number` - The interval in milliseconds between saves (0 to disable) + +**Returns:** `Promise` + +**Example:** + +```typescript +// Save cache to storage every 5 minutes +await RunCache.setupAutoSave(300000); + +// Disable auto-saving +await RunCache.setupAutoSave(0); +``` + +### `saveToStorage()` + +Manually saves the cache state to persistent storage. Expired entries and source functions are not saved. + +**Returns:** `Promise` - `true` if the data was saved, `false` if no storage adapter is configured or the adapter failed + +**Example:** + +```typescript +// Manually save cache state +await RunCache.saveToStorage(); +``` + +### `loadFromStorage()` + +Manually loads the cache state from persistent storage and merges it into the cache. Keys that already exist in memory keep their current value, expired stored entries are skipped, and each restored entry expires after the time remaining on its original TTL. The stored `maxEntries` and `evictionPolicy` are not applied. + +Because loading merges, it does not undo changes made since the last save. To return to exactly the saved state, call `flush()` first, then `loadFromStorage()`. + +**Returns:** `Promise` - `true` if data was found and loaded, `false` otherwise + +**Example:** + +```typescript +// Manually load cache state +await RunCache.loadFromStorage(); +``` + +### `createTypedCache()` + +Creates a typed cache interface that provides type-safe operations for a specific type. + +**Type Parameters:** + +- `T` - The type of values that will be cached + +**Returns:** A typed wrapper around the same global cache. See [Typed Cache Interface](typed-cache-interface.md). + +**Example:** + +```typescript +interface User { + id: number; + name: string; + email: string; +} + +interface Product { + id: number; + name: string; + price: number; +} + +// Create typed cache instances +const userCache = RunCache.createTypedCache(); +const productCache = RunCache.createTypedCache(); + +// All operations are now strongly typed +await userCache.set({ + key: 'user:123', + value: { id: 123, name: 'John', email: 'john@example.com' } +}); + +await productCache.set({ + key: 'product:456', + value: { id: 456, name: 'Laptop', price: 999.99 } +}); + +// Type-safe retrieval +const user = await userCache.get('user:123'); // User | User[] | undefined (an array for wildcard keys) +const product = await productCache.get('product:456'); // Product | Product[] | undefined + +// TypeScript will enforce correct types +// userCache.set({ key: 'test', value: { wrong: 'type' } }); // ❌ Type error +``` + +## Resource Management + +### `shutdown()` + +Shuts down the cache: saves to the storage adapter (if one is configured), then clears all entries, timers and event listeners, removes any handlers installed with `handleProcessSignals`, and resets the configuration to its defaults. + +**Returns:** `Promise` + +**Example:** + +```typescript +// Shut down the cache +await RunCache.shutdown(); + +// Or let RunCache do it when the process receives SIGTERM/SIGINT +await RunCache.configure({ handleProcessSignals: true }); +``` + +## Enums + +### `EvictionPolicy` + +Enum for cache eviction policies: + +- `NONE`: No automatic eviction +- `LRU`: Least Recently Used +- `LFU`: Least Frequently Used + +**Example:** + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +await RunCache.configure({ + evictionPolicy: EvictionPolicy.LRU +}); +``` + +### `EVENT` + +Enum for event types: + +- `EXPIRE`: Expiry events +- `REFETCH`: Refetch events +- `REFETCH_FAILURE`: Refetch failure events +- `TAG_INVALIDATION`: Tag invalidation events +- `DEPENDENCY_INVALIDATION`: Dependency invalidation events + +**Example:** + +```typescript +import { RunCache, EVENT } from 'run-cache'; + +await RunCache.clearEventListeners({ + event: EVENT.EXPIRE +}); +``` + +## Type Definitions + +The exported types (`CacheConfig`, `EventParam`, `EventName`, `MiddlewareFunction`, `MiddlewareContext`, `StorageAdapter`, `StorageAdapterConfig`) and the `EvictionPolicy` enum are documented in [Types](types.md). diff --git a/gitbook-versions/v1.7/api/storage-adapters.md b/gitbook-versions/v1.7/api/storage-adapters.md new file mode 100644 index 0000000..213c12f --- /dev/null +++ b/gitbook-versions/v1.7/api/storage-adapters.md @@ -0,0 +1,358 @@ +# Storage Adapters + +RunCache includes built-in storage adapters that allow you to persist cache data across application restarts. This page provides a complete reference for the available storage adapters and how to use them. + +## Overview + +Storage adapters implement a common interface to save and load cache data to/from persistent storage. RunCache includes three built-in adapters: + +1. **LocalStorageAdapter**: For browser environments, uses the browser's localStorage API +2. **IndexedDBAdapter**: For browser environments, uses the browser's IndexedDB API for larger datasets +3. **FilesystemAdapter**: For Node.js environments, stores cache data in the filesystem + +## Common Configuration Options + +All storage adapters accept the following options (`FilesystemAdapter` also accepts `filePath`): + +- `storageKey?`: `string` - The key to store under (for `FilesystemAdapter`, the file name). Default: `"run-cache-data"` +- `autoSaveInterval?`: `number` - Save at this interval in milliseconds while the adapter is attached. Default: `0` (off) +- `autoLoadOnInit?`: `boolean` - Load existing data when the adapter is attached. Default: `true` + +Loaded entries are merged into the cache, keep the time remaining on their TTL, and have no source function. See [Restoring Data](../advanced/persistent-storage.md#restoring-data). + +These options take effect when the adapter is attached with `RunCache.configure({ storageAdapter })`. With `autoLoadOnInit: false`, existing data is only loaded when you call `RunCache.loadFromStorage()`. A positive `autoSaveInterval` starts saving at that interval. That interval belongs to the adapter: it stops when the adapter is replaced or detached, unlike one started explicitly with `RunCache.setupAutoSave(interval)`, which keeps running. Auto-save intervals never keep a Node.js process alive on their own. + +## LocalStorageAdapter + +The `LocalStorageAdapter` uses the browser's localStorage API to persist cache data. This adapter is suitable for small to medium-sized cache data in web applications. + +### Import + +```typescript +import { RunCache, LocalStorageAdapter } from 'run-cache'; +``` + +### Constructor + +```typescript +constructor(config?: Partial) +``` + +#### Parameters + +- `config?`: `StorageAdapterConfig` - Optional configuration options + - `storageKey?`: `string` - Key to use in localStorage (default: "run-cache-data") + +### Example Usage + +```typescript +// Basic usage with default options +await RunCache.configure({ + storageAdapter: new LocalStorageAdapter() +}); + +// With custom options +await RunCache.configure({ + storageAdapter: new LocalStorageAdapter({ + storageKey: 'my-app-cache', + }) +}); +``` + +### Limitations + +- Limited to approximately 5-10MB of data (varies by browser) +- Synchronous API that can block the main thread with large data +- Only supports string data + +## IndexedDBAdapter + +The `IndexedDBAdapter` uses the browser's IndexedDB API to persist cache data. This adapter is suitable for larger datasets in web applications. + +### Import + +```typescript +import { RunCache, IndexedDBAdapter } from 'run-cache'; +``` + +### Constructor + +```typescript +constructor(config?: Partial) +``` + +#### Parameters + +- `config?`: `StorageAdapterConfig` - Optional configuration options + - `storageKey?`: `string` - Database and store name (default: "run-cache-data") + +### Example Usage + +```typescript +// Basic usage with default options +await RunCache.configure({ + storageAdapter: new IndexedDBAdapter() +}); + +// With custom options +await RunCache.configure({ + storageAdapter: new IndexedDBAdapter({ + storageKey: 'my-app-cache', + }) +}); +``` + +### Advantages + +- Supports much larger data sizes (typically 50-100MB or more) +- Asynchronous API that doesn't block the main thread +- Better performance with large datasets + +### Limitations + +- More complex API +- Not available in all browser contexts (e.g., some private browsing modes) + +## FilesystemAdapter + +The `FilesystemAdapter` stores cache data in the filesystem. This adapter is suitable for Node.js applications. + +### Import + +```typescript +import { RunCache, FilesystemAdapter } from 'run-cache'; +``` + +### Constructor + +```typescript +constructor(config?: FilesystemAdapterConfig) +``` + +#### Parameters + +- `config?`: `FilesystemAdapterConfig` - Optional configuration options + - `storageKey?`: `string` - Filename to use (default: "run-cache-data") + - `filePath?`: `string` - Custom file path (default: current working directory) + +### Example Usage + +```typescript +// Basic usage with default options +await RunCache.configure({ + storageAdapter: new FilesystemAdapter() +}); + +// With custom options +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ + storageKey: 'my-app-cache', + filePath: '/path/to/cache/directory', + }) +}); +``` + +### Advantages + +- Supports very large data sizes (limited only by disk space) +- Persists across application restarts +- Can be configured to store in specific locations + +### Limitations + +- Only available in Node.js environments. The constructor throws elsewhere. The `fs` and `path` modules are loaded on first use rather than at import time, so importing `run-cache` in a browser bundle is safe. +- Requires appropriate file system permissions +- May have performance implications with very frequent writes + +## Custom Storage Adapters + +You can create your own storage adapter by implementing the `StorageAdapter` interface: + +```typescript +interface StorageAdapter { + save(data: string): Promise; + load(): Promise; + clear(): Promise; + + // Optional: picked up when the adapter is attached with configure() + readonly autoSaveInterval?: number; // Save at this interval (ms) when > 0 + readonly autoLoadOnInit?: boolean; // Load existing data on attach (default: true) +} +``` + +### Example Custom Adapter + +Here's an example of a custom adapter that uses a RESTful API for storage: + +```typescript +import type { StorageAdapter } from 'run-cache'; + +class ApiStorageAdapter implements StorageAdapter { + private apiUrl: string; + private apiKey: string; + + constructor(apiUrl: string, apiKey: string) { + this.apiUrl = apiUrl; + this.apiKey = apiKey; + } + + async save(data: string): Promise { + try { + await fetch(`${this.apiUrl}/cache`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${this.apiKey}` + }, + body: JSON.stringify({ data }) + }); + } catch (error) { + console.error('Failed to save cache to API:', error); + throw error; + } + } + + async load(): Promise { + try { + const response = await fetch(`${this.apiUrl}/cache`, { + headers: { + 'Authorization': `Bearer ${this.apiKey}` + } + }); + + if (!response.ok) { + return null; + } + + const result = await response.json(); + return result.data; + } catch (error) { + console.error('Failed to load cache from API:', error); + return null; + } + } + + async clear(): Promise { + const response = await fetch(`${this.apiUrl}/cache`, { + method: 'DELETE', + headers: { 'Authorization': `Bearer ${this.apiKey}` } + }); + // fetch() resolves on HTTP errors too; report them so callers can retry + if (!response.ok) { + throw new Error(`Failed to clear remote cache: HTTP ${response.status}`); + } + } +} + +// Usage +await RunCache.configure({ + storageAdapter: new ApiStorageAdapter('https://api.example.com', 'your-api-key') +}); +``` + +## Working with Storage Adapters + +### Manual Save and Load + +You can manually trigger save and load operations: + +```typescript +// Manually save cache state +await RunCache.saveToStorage(); + +// Manually load cache state +await RunCache.loadFromStorage(); +``` + +### Auto-Save Configuration + +Configure automatic saving at regular intervals: + +```typescript +// Save cache to storage every 5 minutes +await RunCache.setupAutoSave(300000); + +// Disable auto-saving +await RunCache.setupAutoSave(0); +``` + +### Storage Cleanup + +To clear persistent storage, either save an empty cache or clear the adapter directly: + +```typescript +// Clear cache and save empty state to storage +await RunCache.flush(); +await RunCache.saveToStorage(); + +// Or remove the stored data, keeping the in-memory entries +await adapter.clear(); // the adapter instance passed to configure() +``` + +## Best Practices + +### 1. Choose the Right Adapter + +- Use `LocalStorageAdapter` for simple web applications with small cache data +- Use `IndexedDBAdapter` for web applications with larger cache data +- Use `FilesystemAdapter` for Node.js applications + +### 2. Handle Storage Errors + +`saveToStorage()` and `loadFromStorage()` do not throw on adapter errors; they return `false`. Check the result, and turn on `debug` to see the underlying error: + +```typescript +if (!(await RunCache.loadFromStorage())) { + console.warn('No cache data loaded; starting with an empty cache'); +} + +if (!(await RunCache.saveToStorage())) { + console.error('Saving the cache failed (storage full or unavailable?)'); +} +``` + +### 3. Manage Storage Size + +Be mindful of storage limits, especially in browsers: + +```typescript +// Configure cache with size limits +await RunCache.configure({ + maxEntries: 1000, // Limit to 1000 entries + evictionPolicy: EvictionPolicy.LRU, + storageAdapter: new LocalStorageAdapter() +}); +``` + +### 4. Use Appropriate Save Intervals + +Balance between data freshness and performance: + +```typescript +// For frequently changing data, save more often +await RunCache.setupAutoSave(60000); // 1 minute + +// For relatively stable data, save less frequently +await RunCache.setupAutoSave(3600000); // 1 hour +``` + +### 5. Consider Data Serialization + +Be aware that all data is serialized to strings: + +```typescript +// Large binary data might not be suitable for storage +// Consider storing references or URLs instead +await RunCache.set({ + key: 'large-image', + value: imageUrl, // Store URL instead of base64 data + ttl: 3600000 +}); +``` + +## Next Steps + +- [RunCache API](./run-cache.md) - Learn about the main RunCache API +- [Events](./events.md) - Understand the event system +- [Types](./types.md) - Explore TypeScript type definitions +- [Persistent Storage](../advanced/persistent-storage.md) - Learn more about persistence strategies \ No newline at end of file diff --git a/gitbook-versions/v1.7/api/typed-cache-interface.md b/gitbook-versions/v1.7/api/typed-cache-interface.md new file mode 100644 index 0000000..cd51cb4 --- /dev/null +++ b/gitbook-versions/v1.7/api/typed-cache-interface.md @@ -0,0 +1,459 @@ +# Typed Cache Interface + +`RunCache.createTypedCache()` returns a thin wrapper around the static RunCache methods with `T` filled in, so you do not have to repeat the type parameter on every call. It does not create a separate cache: every typed cache reads and writes the same global store, and the typing is compile-time only (see [Type Safety](../advanced/type-validation.md)). + +The class itself (`TypedCacheInterface`) is not exported; use `ReturnType>` if you need to name the type. + +## Class: TypedCacheInterface + +Created using `RunCache.createTypedCache()`, this interface provides all standard cache operations with strong typing for the specified type `T`. + +### Type Parameters + +- `T` - The type of values that will be cached in this interface + +## Cache Operations + +### `set(options)` + +Sets a cache entry. Same as `RunCache.set()`. + +**Parameters:** + +- `options`: `Object` - Cache entry options + - `key`: `string` - Unique identifier for the cache entry + - `value?`: `T` - Typed value to cache (required if no sourceFn) + - `ttl?`: `number` - Time-to-live in milliseconds + - `autoRefetch?`: `boolean` - Automatically refetch on expiry (requires ttl and sourceFn) + - `sourceFn?`: `() => T | Promise` - Function to generate typed cache value (required if no value) + - `tags?`: `string[]` - Array of tags for tag-based invalidation + - `dependencies?`: `string[]` - Array of cache keys this entry depends on + +**Returns:** `Promise` - Returns `true` if the value was successfully set + +**Example:** + +```typescript +interface User { + id: number; + name: string; + email: string; + profile?: { + avatar?: string; + bio?: string; + }; +} + +const userCache = RunCache.createTypedCache(); + +// Type-safe setting +await userCache.set({ + key: 'user:123', + value: { + id: 123, + name: 'John Doe', + email: 'john@example.com', + profile: { + avatar: 'https://example.com/avatar.jpg', + bio: 'Software developer' + } + }, + ttl: 3600000 // 1 hour +}); + +// With source function +await userCache.set({ + key: 'user:456', + sourceFn: async (): Promise => { + const response = await fetch('/api/users/456'); + return response.json(); + }, + ttl: 1800000, // 30 minutes + autoRefetch: true +}); + +// TypeScript will catch type errors at compile time +// await userCache.set({ +// key: 'user:789', +// value: { id: '789', name: 'Jane' } // ❌ Type error: id should be number +// }); +``` + +### `get(key)` + +Retrieves a typed cache entry by key or pattern. + +**Parameters:** + +- `key`: `string` - The key to retrieve, or a pattern with wildcards + +**Returns:** `Promise` +- If `key` is a specific key, returns the typed value or undefined if not found +- If `key` is a pattern, returns an array of matching typed values + +**Example:** + +```typescript +// Get a specific user +const user = await userCache.get('user:123'); +if (user) { + console.log(user.name); // TypeScript knows this is a string + console.log(user.id); // TypeScript knows this is a number + console.log(user.profile?.bio); // Optional chaining with type safety +} + +// Get multiple users with pattern matching +const allUsers = await userCache.get('user:*'); +if (Array.isArray(allUsers)) { + allUsers.forEach(u => { + console.log(`${u.name} (${u.email})`); // Full type safety + }); +} +``` + +### `has(key)` + +Checks if a valid (non-expired) cache entry exists. + +**Parameters:** + +- `key`: `string` - The key to check, or a pattern with wildcards + +**Returns:** `Promise` + +**Example:** + +```typescript +const exists = await userCache.has('user:123'); +if (exists) { + console.log('User is cached'); +} + +// Check if any users are cached +const hasAnyUsers = await userCache.has('user:*'); +``` + +### `delete(key)` + +Removes a cache entry or entries matching a pattern. + +**Parameters:** + +- `key`: `string` - The key to delete, or a pattern with wildcards + +**Returns:** `Promise` - `true` if at least one entry was deleted + +**Example:** + +```typescript +// Delete a specific user +await userCache.delete('user:123'); + +// Delete all users +await userCache.delete('user:*'); +``` + +### `refetch(key)` + +Runs the stored `sourceFn` again for an entry, or for every entry matching a pattern. + +**Parameters:** + +- `key`: `string` - The key to refresh, or a pattern with wildcards + +**Returns:** `Promise` - `true` if at least one entry was refetched + +**Example:** + +```typescript +// Refresh a specific user +await userCache.refetch('user:123'); + +// Refresh all users +await userCache.refetch('user:*'); +``` + +## Event System Integration + +The typed cache has `onExpiry`, `onKeyExpiry`, `onRefetch`, `onKeyRefetch`, `onRefetchFailure` and `onKeyRefetchFailure`. They register the same listeners as the static RunCache methods, so: + +- `onExpiry`, `onRefetch` and `onRefetchFailure` fire for **every** key in the cache, not only keys set through this typed cache. Use the `onKey...` variants with a pattern to scope them. +- `event.value` is the entry's stored form: strings as they were set, other values as their JSON string, even though it is typed as `T`. Parse it when you need the object. + +### Event Registration + +```typescript +// Scope listeners to this cache's keys with a pattern +await userCache.onKeyExpiry('user:*', (event) => { + // event.value is the stored JSON string for object values + const user = JSON.parse(event.value as unknown as string) as User; + console.log(`User ${user.name} expired from cache`); +}); + +await userCache.onKeyRefetch('user:*', (event) => { + console.log(`User cache refreshed: ${event.key}`); +}); + +await userCache.onKeyRefetchFailure('user:*', (event) => { + console.error(`Failed to refresh user: ${event.key}`, event.error); +}); +``` + +## Advanced Usage Patterns + +### Repository Pattern + +Use typed cache interfaces to implement repository patterns: + +```typescript +class UserRepository { + private cache = RunCache.createTypedCache(); + + async findById(id: number): Promise { + // get() is typed T | T[] | undefined because a key may be a wildcard pattern + return (await this.cache.get(`user:${id}`)) as User | undefined; + } + + async save(user: User, ttl?: number): Promise { + await this.cache.set({ + key: `user:${user.id}`, + value: user, + ttl: ttl || 3600000, // Default 1 hour + tags: ['user', `user:${user.id}`] + }); + } + + async findByEmail(email: string): Promise { + const users = await this.cache.get('user:*'); + if (Array.isArray(users)) { + return users.find(u => u.email === email); + } + return undefined; + } + + async invalidateUser(id: number): Promise { + await this.cache.delete(`user:${id}`); + } + + async refreshUser(id: number): Promise { + await this.cache.refetch(`user:${id}`); + } +} + +// Usage +const userRepo = new UserRepository(); +const user = await userRepo.findById(123); +if (user) { + console.log(user.name); // Fully typed +} +``` + +### Service Layer Integration + +Integrate typed caches with service layers: + +```typescript +interface Product { + id: number; + name: string; + price: number; + category: string; + inStock: boolean; +} + +class ProductService { + private cache = RunCache.createTypedCache(); + + async getProduct(id: number): Promise { + // Try cache first + const cached = (await this.cache.get(`product:${id}`)) as Product | undefined; + if (cached) { + return cached; + } + + // Fetch from database/API + const product = await this.fetchProductFromDB(id); + if (product) { + // Cache with 30-minute TTL + await this.cache.set({ + key: `product:${id}`, + value: product, + ttl: 1800000, + tags: ['product', `category:${product.category}`] + }); + } + + return product; + } + + async updateProduct(product: Product): Promise { + await this.updateProductInDB(product); + + // Update cache + await this.cache.set({ + key: `product:${product.id}`, + value: product, + ttl: 1800000, + tags: ['product', `category:${product.category}`] + }); + } + + async invalidateCategory(category: string): Promise { + // Tag invalidation is only on RunCache; it covers entries set through any typed cache + await RunCache.invalidateByTag(`category:${category}`); + } + + private async fetchProductFromDB(id: number): Promise { + // Database fetch logic + return null; // Placeholder + } + + private async updateProductInDB(product: Product): Promise { + // Database update logic + } +} +``` + +### Multi-Type Cache Management + +Manage multiple typed caches in a single class: + +```typescript +interface Order { + id: number; + userId: number; + products: Product[]; + total: number; + status: 'pending' | 'processing' | 'shipped' | 'delivered'; +} + +class CacheManager { + private userCache = RunCache.createTypedCache(); + private productCache = RunCache.createTypedCache(); + private orderCache = RunCache.createTypedCache(); + + // User operations + async getUser(id: number): Promise { + return (await this.userCache.get(`user:${id}`)) as User | undefined; + } + + async setUser(user: User): Promise { + await this.userCache.set({ + key: `user:${user.id}`, + value: user, + ttl: 3600000, + tags: ['user'] + }); + } + + // Product operations + async getProduct(id: number): Promise { + return (await this.productCache.get(`product:${id}`)) as Product | undefined; + } + + async setProduct(product: Product): Promise { + await this.productCache.set({ + key: `product:${product.id}`, + value: product, + ttl: 1800000, + tags: ['product', `category:${product.category}`] + }); + } + + // Order operations + async getOrder(id: number): Promise { + return (await this.orderCache.get(`order:${id}`)) as Order | undefined; + } + + async setOrder(order: Order): Promise { + await this.orderCache.set({ + key: `order:${order.id}`, + value: order, + ttl: 7200000, // 2 hours + tags: ['order', `user:${order.userId}`], + dependencies: [`user:${order.userId}`] + }); + } + + // Cross-type operations + async getUserOrders(userId: number): Promise { + const orders = await this.orderCache.get('order:*'); + if (Array.isArray(orders)) { + return orders.filter(order => order.userId === userId); + } + return []; + } + + async invalidateUserData(userId: number): Promise { + await this.userCache.delete(`user:${userId}`); + await RunCache.invalidateByTag(`user:${userId}`); + } +} +``` + +## Type Safety Benefits + +### Compile-Time Type Checking + +```typescript +interface StrictUser { + id: number; + name: string; + email: string; + createdAt: string; // ISO date: a Date would come back from get() as a string +} + +const strictUserCache = RunCache.createTypedCache(); + +// ✅ Valid usage +await strictUserCache.set({ + key: 'user:1', + value: { + id: 1, + name: 'John', + email: 'john@example.com', + createdAt: new Date().toISOString() + } +}); + +// ❌ Compile-time errors +/* +await strictUserCache.set({ + key: 'user:2', + value: { + id: '2', // ❌ Type error: string not assignable to number + name: 'Jane', + email: 'jane@example.com' + // ❌ Type error: missing required property 'createdAt' + } +}); +*/ +``` + +### Runtime Type Validation + +The type parameter is not checked at runtime, and no cache method accepts a validator. See [Type Safety](../advanced/type-validation.md#adding-a-runtime-check) for checking values after reading them. + +## Performance Considerations + +Typed cache interfaces have minimal overhead compared to the main RunCache: + +- **Type Checking**: Zero runtime cost (compile-time only) +- **Memory Usage**: Same as main RunCache (just a wrapper) +- **Serialization**: Same as RunCache: non-string values are stored as JSON +- **Method Calls**: One extra function call per operation + +## Best Practices + +1. **Use for Consistent Types**: Create typed interfaces for types you cache frequently +2. **Repository Pattern**: Combine with repository patterns for clean architecture +3. **Service Integration**: Integrate with service layers for business logic separation +4. **Runtime Checks**: Validate values that may come from outside your control after reading them +5. **Event Handling**: Scope listeners with the `onKey...` methods and a key pattern + +## Next Steps + +- Learn about [Value Serialization](../advanced/serialization-adapters.md) for complex types +- Read [Type Safety](../advanced/type-validation.md) for runtime checking +- See [Best Practices](../guides/best-practices.md) for typed caching patterns +- Check the main [RunCache API](run-cache.md) for additional methods \ No newline at end of file diff --git a/gitbook-versions/v1.7/api/types.md b/gitbook-versions/v1.7/api/types.md new file mode 100644 index 0000000..a8041b6 --- /dev/null +++ b/gitbook-versions/v1.7/api/types.md @@ -0,0 +1,263 @@ +# TypeScript Types + +This page lists every type the `run-cache` package exports. Import them with `import type`: + +```typescript +import type { + CacheConfig, + EventParam, + EventName, + MiddlewareFunction, + MiddlewareContext, + StorageAdapter, + StorageAdapterConfig +} from 'run-cache'; +``` + +The values `RunCache` (also the default export), `EvictionPolicy`, `EVENT`, `LocalStorageAdapter`, `IndexedDBAdapter`, `FilesystemAdapter` and the [error classes](#error-classes) are exported too. Nothing else is part of the public API. + +## CacheConfig + +Options for `RunCache.configure()`. Every option is optional, and a call only changes the options it passes. + +```typescript +interface CacheConfig { + /** Maximum number of entries. Default: unlimited */ + maxEntries?: number; + + /** Declared but not used: entries without a ttl never expire */ + defaultTTL?: number; + + /** What to evict when maxEntries is reached. Default: EvictionPolicy.NONE */ + evictionPolicy?: EvictionPolicy; + + /** Adapter to persist the cache with. Attaching one loads its saved data */ + storageAdapter?: StorageAdapter; + + /** Log operations and errors to the console. Default: false */ + debug?: boolean; + + /** Call shutdown() on SIGINT/SIGTERM (Node.js) or beforeunload (browser). Default: false */ + handleProcessSignals?: boolean; + + /** Receives errors thrown by event listeners. Default: console.error */ + onListenerError?: (error: unknown, context: { event: string; key: string }) => void; +} +``` + +## Set options + +`RunCache.set()` takes an inline options object; there is no exported name for it: + +```typescript +{ + key: string; // must not be empty + value?: T; // strings (including '') are stored as-is, other values as JSON + ttl?: number; // milliseconds; finite and > 0 (omit it for entries that never expire) + autoRefetch?: boolean; // requires ttl, and a sourceFn to have any effect + sourceFn?: () => T | Promise; + tags?: string[]; + dependencies?: string[]; +} +``` + +One of `value` or `sourceFn` is required. If you need the type, derive it: `Parameters[0]`. + +## Event Types + +### EVENT + +```typescript +const EVENT = { + EXPIRE: 'expire', + REFETCH: 'refetch', + REFETCH_FAILURE: 'refetch_failure', + TAG_INVALIDATION: 'tag_invalidation', + DEPENDENCY_INVALIDATION: 'dependency_invalidation', +} as const; +``` + +### EventName + +```typescript +type EventName = keyof typeof EVENT + | 'expire' | 'refetch' | 'refetch_failure' | 'tag_invalidation' | 'dependency_invalidation'; +``` + +Accepted by `RunCache.clearEventListeners({ event })`. + +### EventParam + +Every event listener receives an `EventParam`: + +```typescript +type EventParam = { + key: string; + value: T; // see the note below + serializedValue?: string; + ttl?: number; + createdAt: number; // ms since epoch + updatedAt: number; + tag?: string; // tag_invalidation events only + dependencyKey?: string; // dependency_invalidation events only + error?: unknown; // refetch_failure events only +}; +``` + +`value` holds the entry's stored form: a string set as a string is passed unchanged, but any other value is passed as its JSON string, even when a typed cache declares `T`. `error` is set on `refetch_failure` events to what the source function threw (or a `SourceFnError` if it resolved to `undefined`). See [Events](events.md). + +## Middleware Types + +### MiddlewareFunction + +```typescript +type MiddlewareFunction = ( + value: T, + context: MiddlewareContext, + next: (nextValue: T) => Promise +) => Promise; +``` + +`RunCache.use()` takes a `MiddlewareFunction`: middleware always sees the stored string, never the original object. + +### MiddlewareContext + +```typescript +interface MiddlewareContext { + key: string; + operation: 'get' | 'set' | 'delete' | 'has' | 'refetch'; + value?: T; + serializedValue?: string; + ttl?: number; + autoRefetch?: boolean; + timestamp: number; +} +``` + +Although the type lists `delete` and `has`, middleware only runs for `set`, `refetch`, and `get` when the key is found. See [Middleware](../advanced/middleware.md). + +## Storage Types + +### StorageAdapter + +```typescript +interface StorageAdapter { + save(data: string): Promise; + load(): Promise; + + /** + * Remove the stored cache data + */ + clear(): Promise; + + /** + * Optional auto-save interval in milliseconds, applied when the adapter is attached + */ + readonly autoSaveInterval?: number; + + /** + * Optional: whether existing data is loaded when the adapter is attached (default: true) + */ + readonly autoLoadOnInit?: boolean; +} +``` + +Implement it to persist the cache somewhere other than the built-in adapters. See [Persistent Storage](../advanced/persistent-storage.md#custom-storage-adapters). + +### StorageAdapterConfig + +```typescript +interface StorageAdapterConfig { + /** Key (or file name, for FilesystemAdapter) to store under. Default: "run-cache-data" */ + storageKey?: string; + /** Save at this interval (ms) while the adapter is attached. Default: 0 (off) */ + autoSaveInterval?: number; + /** Load existing data when the adapter is attached. Default: true */ + autoLoadOnInit?: boolean; +} +``` + +The adapter constructors take `Partial`; `FilesystemAdapter` additionally accepts `filePath?: string`. + +## Error Classes + +```typescript +import { RunCacheError, SourceFnError, MiddlewareError } from 'run-cache'; +``` + +| Class | Thrown when | Extends | +| --- | --- | --- | +| `RunCacheError` | Base class for the errors below | `Error` | +| `SourceFnError` | A source function throws, rejects or resolves to `undefined` | `RunCacheError` | +| `MiddlewareError` | A middleware function throws or produces `undefined` | `RunCacheError` | + +Each has `key` (the cache key of the failing operation) and, when there is an underlying error, `cause`: + +```typescript +import { RunCache, SourceFnError } from 'run-cache'; + +try { + await RunCache.refetch('api-data'); +} catch (error) { + if (error instanceof SourceFnError) { + console.error(`Refetch of ${error.key} failed`, error.cause); + } +} +``` + +## EvictionPolicy + +```typescript +enum EvictionPolicy { + NONE = 'NONE', // never evict (default) + LRU = 'LRU', // evict the least recently used entry + LFU = 'LFU', // evict the least frequently used entry +} +``` + +## Examples + +### Configuration + +```typescript +import { RunCache, EvictionPolicy, type CacheConfig } from 'run-cache'; + +const config: CacheConfig = { + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU, + debug: process.env.NODE_ENV !== 'production' +}; + +await RunCache.configure(config); +``` + +### Middleware + +```typescript +import { RunCache, type MiddlewareFunction } from 'run-cache'; + +const logOperations: MiddlewareFunction = async (value, context, next) => { + console.log(`${context.operation} ${context.key}`); + return next(value); +}; + +await RunCache.use(logOperations); +``` + +### Event handler + +```typescript +import { RunCache, type EventParam } from 'run-cache'; + +function logExpiry(event: EventParam) { + console.log(`${event.key} expired after ${event.ttl}ms`); +} + +await RunCache.onExpiry(logExpiry); +``` + +## Next Steps + +- [RunCache API](run-cache.md) - Method reference +- [Events](events.md) - Event reference +- [Typed Cache Interface](typed-cache-interface.md) - `createTypedCache()` diff --git a/gitbook-versions/v1.7/features/auto-refetch.md b/gitbook-versions/v1.7/features/auto-refetch.md new file mode 100644 index 0000000..b435562 --- /dev/null +++ b/gitbook-versions/v1.7/features/auto-refetch.md @@ -0,0 +1,294 @@ +# Automatic Refetching + +Automatic refetching is a powerful feature in RunCache that allows cache entries to be refreshed in the background when they expire. This guide explains how to use automatic refetching and its benefits for your applications. + +## Understanding Automatic Refetching + +When a cache entry with `autoRefetch: true` expires: + +1. The next `get()` call will return the stale value immediately +2. Simultaneously, RunCache triggers a background refresh using the source function +3. Once the refresh completes, the cache is updated with fresh data +4. Subsequent calls will get the new data + +This approach provides several benefits: +- **Zero Wait Time**: Users never wait for cache refreshes +- **Prevents Cache Stampedes**: Only one refresh happens regardless of concurrent requests +- **Always Fresh Data**: Cache entries are automatically kept up-to-date +- **Resilience**: If refresh fails, stale data is still available + +## Setting Up Automatic Refetching + +To enable automatic refetching, you need to: +1. Provide a `sourceFn` to generate the cache value +2. Set a `ttl` (Time-to-Live) value +3. Set `autoRefetch: true` + +```typescript +await RunCache.set({ + key: 'weather-data', + sourceFn: async () => { + const response = await fetch('https://api.weather.com/current'); + const data = await response.json(); + return data; + }, + ttl: 5 * 60 * 1000, // 5 minutes + autoRefetch: true +}); +``` + +## How It Works Behind the Scenes + +Let's walk through what happens with automatic refetching: + +1. **Initial Cache Miss**: + - First `get('weather-data')` finds no cache entry + - RunCache calls the `sourceFn` to fetch data + - User waits for this initial fetch + - Result is stored in cache with TTL + +2. **Cache Hit (Before Expiry)**: + - Subsequent `get('weather-data')` within TTL period + - RunCache returns cached value immediately + - No source function call occurs + +3. **After TTL Expires**: + - Next `get('weather-data')` after TTL expired + - RunCache returns stale value immediately + - RunCache triggers background refresh using `sourceFn` + - Cache is updated when refresh completes + - User experiences no delay + +## Monitoring Refetch Events + +RunCache provides events to monitor automatic refetching: + +```typescript +// Global refetch event +await RunCache.onRefetch((event) => { + console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); +}); + +// Specific key refetch +await RunCache.onKeyRefetch("weather-data", (event) => { + console.log(`Weather data was refreshed`); +}); + +// Pattern-based refetch events +await RunCache.onKeyRefetch("user:*:profile", (event) => { + console.log(`User profile ${event.key} was refreshed`); +}); +``` + +## Handling Refetch Failures + +If a background refresh fails, RunCache provides events to handle the failure: + +```typescript +// Global refetch failure event +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}: ${event.error}`); +}); + +// Specific key refetch failure +await RunCache.onKeyRefetchFailure("weather-data", (event) => { + console.error(`Weather data refresh failed: ${event.error}`); + + // Implement retry logic + setTimeout(() => RunCache.refetch("weather-data"), 30000); // Retry after 30 seconds +}); +``` + +When a refetch fails: +1. The stale data remains in the cache +2. The failure event is triggered +3. No automatic retry is attempted (you must implement retry logic) + +## Manual Refetching + +You can also manually trigger a refresh for any cache entry with a source function: + +```typescript +// Manually refresh a specific entry +await RunCache.refetch('weather-data'); + +// Refresh multiple entries using a pattern +await RunCache.refetch('user:*:profile'); +``` + +Manual refetching is useful for: +- Forcing a refresh before the TTL expires +- Retrying after a failed automatic refresh +- Refreshing data after related data changes + +`refetch()` resolves to `true` when the new value was stored. It resolves to `false` if the entry changed while the source function was running, for example because it was deleted, invalidated, flushed or overwritten with `set()`. In that case the result is discarded, so a refetch never brings back an entry that was removed, and never overwrites a newer value. + +## Best Practices for Automatic Refetching + +### 1. Use for Critical Data Only + +Automatic refetching is most beneficial for: +- Frequently accessed data +- Data that should never be unavailable +- Data where freshness is important but not critical + +```typescript +// Good candidate for autoRefetch +await RunCache.set({ + key: 'global-settings', + sourceFn: () => fetchGlobalSettings(), + ttl: 5 * 60 * 1000, + autoRefetch: true +}); + +// May not need autoRefetch +await RunCache.set({ + key: 'user-activity-log', + sourceFn: () => fetchUserActivity(), + ttl: 30 * 60 * 1000, + // No autoRefetch as it's less critical +}); +``` + +### 2. Consider Resource Usage + +Each automatic refetch consumes resources: +- Network bandwidth for API calls +- CPU time for processing +- Memory for storing results + +For high-traffic applications, be selective about which entries use automatic refetching. + +### 3. Set Appropriate TTL Values + +The TTL value determines how often automatic refetches occur: +- Too short: Excessive refreshes waste resources +- Too long: Data becomes stale + +```typescript +// Frequently changing data +await RunCache.set({ + key: 'stock-prices', + sourceFn: () => fetchStockPrices(), + ttl: 60 * 1000, // 1 minute + autoRefetch: true +}); + +// Relatively stable data +await RunCache.set({ + key: 'product-catalog', + sourceFn: () => fetchProductCatalog(), + ttl: 60 * 60 * 1000, // 1 hour + autoRefetch: true +}); +``` + +### 4. Implement Proper Error Handling + +Always implement error handling for refetch failures: + +```typescript +// Attempts and pending retry per key; RunCache events carry no custom metadata +const retryCounts = new Map(); +const retryTimers = new Map>(); + +await RunCache.onRefetchFailure((event) => { + // Log the error + console.error(`Refetch failed for ${event.key}:`, event.error); + + // Implement exponential backoff retry + const retryCount = (retryCounts.get(event.key) ?? 0) + 1; + retryCounts.set(event.key, retryCount); + const delay = Math.min(1000 * Math.pow(2, retryCount), 30000); // Max 30 seconds + + clearTimeout(retryTimers.get(event.key)); + retryTimers.set(event.key, setTimeout(() => { + retryTimers.delete(event.key); + RunCache.refetch(event.key) + .catch(() => { /* reported again through onRefetchFailure */ }); + }, delay)); +}); + +// Any successful refresh (the retry, a manual refetch or the next automatic one) +// resets the backoff and cancels a retry that is no longer needed. +await RunCache.onRefetch((event) => { + retryCounts.delete(event.key); + clearTimeout(retryTimers.get(event.key)); + retryTimers.delete(event.key); +}); +``` + +### 5. Track Refetch Statistics + +Cache entries have no metadata option, and refetch events only carry the entry's key, value, TTL and timestamps. Track anything else yourself, keyed by cache key: + +```typescript +const refreshStats = new Map(); + +await RunCache.set({ + key: 'api-data', + sourceFn: () => fetchApiData(), + ttl: 300000, + autoRefetch: true +}); + +await RunCache.onRefetch((event) => { + const stats = refreshStats.get(event.key) ?? { refreshCount: 0, lastRefreshedAt: 0 }; + stats.refreshCount++; + stats.lastRefreshedAt = event.updatedAt; + refreshStats.set(event.key, stats); +}); +``` + +## Advanced Patterns + +### Cascading Refreshes + +You can implement cascading refreshes using dependencies. Each automatic refetch of the primary entry invalidates its dependents: + +```typescript +// Primary data +await RunCache.set({ + key: 'user:1:profile', + sourceFn: () => fetchUserProfile(1), + ttl: 300000, + autoRefetch: true +}); + +// Dependent data +await RunCache.set({ + key: 'user:1:recommendations', + sourceFn: () => fetchUserRecommendations(1), + ttl: 300000, + autoRefetch: true, + dependencies: ['user:1:profile'] // Invalidated each time the profile is refetched +}); +``` + +Invalidated entries are removed, not refetched, even when they have their own `sourceFn` and `autoRefetch`: set `user:1:recommendations` again the next time you need it, or from a `dependency_invalidation` listener. + +### Conditional Refetching + +You can implement conditional refetching by checking certain conditions: + +```typescript +// Custom refetch logic +await RunCache.onKeyExpiry('conditional-data', async (event) => { + const shouldRefresh = await checkIfRefreshNeeded(event.key); + + if (shouldRefresh) { + await RunCache.refetch(event.key); + } else { + console.log('Skipping refresh based on condition'); + } +}); +``` + +## Next Steps + +Now that you understand automatic refetching, explore these related topics: + +- [TTL and Expiration](./ttl-expiration.md) - Learn more about time-to-live functionality +- [Source Functions](./source-functions.md) - Dive deeper into source functions +- [Event System](../advanced/event-system.md) - Understand how to use events for cache monitoring +- [Dependency Tracking](../advanced/dependency-tracking.md) - Learn about relationships between cache entries \ No newline at end of file diff --git a/gitbook-versions/v1.7/features/cache-management.md b/gitbook-versions/v1.7/features/cache-management.md new file mode 100644 index 0000000..0d08f30 --- /dev/null +++ b/gitbook-versions/v1.7/features/cache-management.md @@ -0,0 +1,224 @@ +# Cache Management + +This guide covers the core cache management operations in RunCache, including how to store, retrieve, and delete cache entries. + +## Basic Cache Operations + +RunCache provides a set of fundamental operations for managing cache entries: + +- **Set**: Store a value in the cache +- **Get**: Retrieve a value from the cache +- **Has**: Check if a key exists in the cache +- **Delete**: Remove a specific entry from the cache +- **Flush**: Clear the entire cache + +Let's explore each of these operations in detail. + +## Setting Cache Entries + +The `set` method is used to store values in the cache: + +```typescript +await RunCache.set({ + key: string, // Required: Unique identifier for the cache entry + value?: string, // Optional: String value to cache (required if no sourceFn) + ttl?: number, // Optional: Time-to-live in milliseconds + autoRefetch?: boolean, // Optional: Automatically refetch on expiry + sourceFn?: () => string | Promise, // Optional: Function to generate cache value + tags?: string[], // Optional: Array of tags for tag-based invalidation + dependencies?: string[] // Optional: Array of cache keys this entry depends on +}); +``` + +### Basic Examples + +```typescript +// Store a simple string +await RunCache.set({ key: 'greeting', value: 'Hello, World!' }); + +// Store an object (serialized for you) +const user = { id: 1, name: 'John Doe' }; +await RunCache.set({ key: 'user:1', value: user }); + +// Store with expiration (TTL) +await RunCache.set({ + key: 'temporary-data', + value: 'This will expire soon', + ttl: 60000 // 1 minute +}); +``` + +### Advanced Examples + +```typescript +// Store with a source function +await RunCache.set({ + key: 'api-data', + sourceFn: async () => { + const response = await fetch('https://api.example.com/data'); + const data = await response.json(); + return data; + } +}); + +// Store with tags for group invalidation +await RunCache.set({ + key: 'user:1:profile', + value: { name: 'John Doe' }, + tags: ['user:1', 'profile'] +}); + +// Store with dependencies +await RunCache.set({ + key: 'dashboard:1', + value: { widgets: [...] }, + dependencies: ['user:1:profile'] +}); +``` + +## Retrieving Cache Entries + +The `get` method is used to retrieve values from the cache: + +```typescript +const value = await RunCache.get(key); +``` + +### Basic Examples + +```typescript +// Get a simple string +const greeting = await RunCache.get('greeting'); +console.log(greeting); // Output: Hello, World! + +// Get an object: it comes back parsed +// (get() is typed T | T[] | undefined, because a key may be a wildcard pattern) +const user = (await RunCache.get('user:1')) as { name: string } | undefined; +if (user) { + console.log(user.name); // Output: John Doe +} +``` + +### Using Patterns + +You can use wildcard patterns to retrieve multiple related entries: + +```typescript +// Get all user profiles +const profiles = await RunCache.get('user:*:profile'); +console.log(profiles); // Array of all matching values + +// Get all data for user 1 +const userData = await RunCache.get('user:1:*'); +``` + +When using patterns, `get` returns an array of values that match the pattern. + +## Checking Cache Status + +The `has` method checks if a valid (non-expired) cache entry exists: + +```typescript +const exists = await RunCache.has(key); +``` + +### Examples + +```typescript +// Check if a specific key exists +const hasGreeting = await RunCache.has('greeting'); +if (hasGreeting) { + console.log('Greeting is cached'); +} + +// Check if any keys matching a pattern exist +const hasUserData = await RunCache.has('user:1:*'); +if (hasUserData) { + console.log('User 1 has some cached data'); +} +``` + +## Deleting Cache Entries + +The `delete` method removes entries from the cache: + +```typescript +await RunCache.delete(key); +``` + +### Examples + +```typescript +// Delete a specific entry +await RunCache.delete('greeting'); + +// Delete multiple entries using a pattern +await RunCache.delete('user:1:*'); // Deletes all entries that match the pattern +``` + +## Clearing the Entire Cache + +The `flush` method removes all entries from the cache: + +```typescript +await RunCache.flush(); +``` + +This is useful for: +- Testing scenarios +- Handling major data changes +- User logout operations +- Freeing up memory + +## Refreshing Cache Entries + +The `refetch` method manually refreshes cache entries that were created with a source function: + +```typescript +await RunCache.refetch(key); +``` + +### Examples + +```typescript +// Refresh a specific entry +await RunCache.refetch('api-data'); + +// Refresh multiple entries using a pattern +await RunCache.refetch('user:*:profile'); +``` + +## Best Practices + +Here are some best practices for effective cache management: + +1. **Use consistent key naming conventions**: + - Adopt a structured approach like `entity:id:attribute` + - Use lowercase for consistency + - Use colons (`:`) as separators for hierarchical keys + +2. **Handle cache misses gracefully**: + - Always check if values exist before using them + - Provide fallback mechanisms for cache misses + +3. **Use appropriate TTL values**: + - Consider data volatility when setting TTL + - Use shorter TTLs for frequently changing data + - Use longer TTLs for stable data + +4. **Implement cache warming**: + - Pre-populate critical cache entries on application startup + - Use source functions for automatic population + +5. **Monitor cache usage**: + - Use the event system to track cache operations + - Implement logging for cache hits and misses + +## Next Steps + +Now that you understand basic cache management, explore these related topics: + +- [TTL and Expiration](./ttl-expiration.md) - Learn more about time-to-live functionality +- [Eviction Policies](./eviction-policies.md) - Configure how cache entries are evicted +- [Pattern Matching](./pattern-matching.md) - Master wildcard patterns +- [Tag-based Invalidation](../advanced/tag-invalidation.md) - Group and invalidate related cache entries \ No newline at end of file diff --git a/gitbook-versions/v1.7/features/eviction-policies.md b/gitbook-versions/v1.7/features/eviction-policies.md new file mode 100644 index 0000000..5c757aa --- /dev/null +++ b/gitbook-versions/v1.7/features/eviction-policies.md @@ -0,0 +1,133 @@ +# Eviction Policies + +Eviction policies determine how RunCache manages memory usage by automatically removing entries when the cache reaches a defined size limit. This page explains the available policies and how to configure them. + +## Available Eviction Policies + +RunCache provides three eviction policies: + +### NONE (Default) + +With this policy, the cache will never automatically evict entries based on size. Entries are only removed when: + +- They expire based on their TTL +- They are manually deleted via `delete()` or `flush()` +- The application shuts down + +This is the default policy and is suitable for cases where you have full control over the cache size through TTLs or manual management. + +### LRU (Least Recently Used) + +The LRU policy removes the least recently accessed entries when the cache exceeds its maximum size. This is ideal for cases where recently accessed items are more likely to be accessed again. + +An entry counts as used when it is written with `set()` (including overwriting an existing key) and when it is read with `get()` or `has()`. When the cache reaches its maximum size, the entry that has gone unused for the longest time is removed first. A freshly written entry is the most recently used one, even if it has not been read yet, so a write-heavy workload keeps its newest entries. When several operations happen within the same millisecond, they are still ordered by the sequence in which they happened. Refreshing an entry with `refetch()` or `autoRefetch` does not count as a use: a refresh keeps the value current, but it does not mean the application needs the entry, so auto-refetched entries that are never read can still be evicted. + +```typescript +await RunCache.configure({ maxEntries: 2, evictionPolicy: EvictionPolicy.LRU }); + +await RunCache.set({ key: 'a', value: '1' }); +await RunCache.get('a'); +await RunCache.set({ key: 'b', value: '2' }); +await RunCache.set({ key: 'c', value: '3' }); // evicts 'a', the least recently used +``` + +### LFU (Least Frequently Used) + +The LFU policy removes the least frequently accessed entries when the cache exceeds its maximum size. This is ideal for cases where frequency of access is a better predictor of future access than recency. + +Each time an entry is read with `get()` or `has()`, its access count is incremented; overwriting an entry with `set()` keeps its count. When the cache reaches its maximum size, entries with the lowest access count are removed first. If multiple entries have the same access count, the least recently used one is removed. + +## Configuring Eviction Policies + +You can set the eviction policy and maximum cache size through the `configure()` method: + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +// Configure the cache with a max size of 100 entries and LRU eviction policy +await RunCache.configure({ + maxEntries: 100, + evictionPolicy: EvictionPolicy.LRU +}); +``` + +### Setting Maximum Size + +The `maxEntries` parameter determines how many entries the cache can hold before eviction occurs: + +```typescript +// Allow up to 500 entries +await RunCache.configure({ + maxEntries: 500, + evictionPolicy: EvictionPolicy.LFU +}); +``` + +If you don't specify a `maxEntries`, it defaults to `Infinity`, meaning the cache will grow without bounds (unless you set a policy other than `NONE`). + +### Changing Policies at Runtime + +You can change the eviction policy at any time: + +```typescript +// Start with LRU +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU +}); + +// Later, switch to LFU +await RunCache.configure({ + evictionPolicy: EvictionPolicy.LFU +}); +``` + +When changing policies, the cache preserves all access metadata (recency and frequency), so the new policy can make informed decisions about which entries to evict. + +## Checking Current Configuration + +You can retrieve the current configuration using the `getConfig()` method: + +```typescript +const config = await RunCache.getConfig(); +console.log(config); +// Output: { maxEntries: 100, evictionPolicy: "lru", debug: false, ... } +``` + +## How Eviction Works + +When a new entry is added to the cache and the cache size exceeds `maxEntries`: + +1. The eviction policy determines which entries to remove +2. Selected entries are removed from the cache +3. Any intervals associated with those entries are cleared +4. The new entry is added to the cache + +Eviction is also checked after configuration changes if the new `maxEntries` is smaller than the current cache size. + +## Best Practices + +- **Choose the right policy for your access patterns:** + - Use LRU when recent access is the best predictor of future access + - Use LFU when frequency of access is more important than recency + - Use NONE when you want full manual control or rely on TTL + +- **Set a reasonable `maxEntries`:** Too small and you'll have frequent evictions, too large and you may consume too much memory. + +- **Monitor evictions:** Enable debug logging to see when entries are being evicted, which can help tune your cache size. + +```typescript +await RunCache.configure({ + debug: true, + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU +}); +``` + +- **Consider TTL alongside eviction policies:** Even with eviction policies, setting TTLs for entries can help ensure data freshness. + +## Next Steps + +- Learn about [Tag-based Invalidation](../advanced/tag-invalidation.md) for more control over cache entry lifecycle +- Explore [Dependency Tracking](../advanced/dependency-tracking.md) to establish relationships between cache entries +- Check out [Resource Management](../advanced/resource-management.md) for more on memory usage optimization \ No newline at end of file diff --git a/gitbook-versions/v1.7/features/pattern-matching.md b/gitbook-versions/v1.7/features/pattern-matching.md new file mode 100644 index 0000000..2445f7f --- /dev/null +++ b/gitbook-versions/v1.7/features/pattern-matching.md @@ -0,0 +1,322 @@ +# Pattern Matching + +RunCache supports wildcard pattern matching for operating on multiple related cache keys simultaneously. This guide explains how to use pattern matching effectively in your applications. + +## Understanding Pattern Matching + +Pattern matching allows you to: +- Retrieve multiple related cache entries at once +- Delete groups of related entries +- Check if any entries matching a pattern exist +- Refresh multiple entries with a single call +- Register event listeners for groups of keys + +The pattern matching system uses the `*` character as a wildcard that matches any sequence of characters in a key. + +## Basic Pattern Syntax + +The pattern matching syntax is simple: +- `*` matches any sequence of characters +- Any other character matches itself + +Examples: +- `user:*` matches any key starting with "user:" +- `*:profile` matches any key ending with ":profile" +- `user:*:settings` matches keys like "user:1:settings", "user:john:settings", etc. +- `*stats*` matches any key containing "stats" anywhere + +## Using Patterns with Get + +The `get` method supports patterns to retrieve multiple cache entries: + +```typescript +// Set multiple related entries +await RunCache.set({ key: 'user:1:name', value: 'Alice' }); +await RunCache.set({ key: 'user:1:email', value: 'alice@example.com' }); +await RunCache.set({ key: 'user:2:name', value: 'Bob' }); +await RunCache.set({ key: 'user:2:email', value: 'bob@example.com' }); + +// Get all user names +const names = await RunCache.get('user:*:name'); +console.log(names); // Output: ['Alice', 'Bob'] + +// Get all data for user 1 +const user1Data = await RunCache.get('user:1:*'); +console.log(user1Data); // Output: ['Alice', 'alice@example.com'] +``` + +When using patterns with `get`: +- Returns an array of values for matching keys +- Returns an empty array if no keys match +- Order is not guaranteed (don't rely on the order of results) + +## Using Patterns with Delete + +The `delete` method supports patterns to remove multiple cache entries: + +```typescript +// Delete all data for user 1 +await RunCache.delete('user:1:*'); + +// Delete all email entries +await RunCache.delete('user:*:email'); + +// Delete all user data +await RunCache.delete('user:*'); +``` + +## Using Patterns with Has + +The `has` method supports patterns to check if any matching entries exist: + +```typescript +// Check if any user 2 data exists +const hasUser2Data = await RunCache.has('user:2:*'); +if (hasUser2Data) { + console.log('User 2 has some cached data'); +} + +// Check if any email data exists +const hasEmails = await RunCache.has('*:email'); +``` + +When using patterns with `has`: +- Returns `true` if any matching key exists (and hasn't expired) +- Returns `false` if no matching keys exist + +## Using Patterns with Refetch + +The `refetch` method supports patterns to refresh multiple cache entries: + +```typescript +// Refresh all profile data +await RunCache.refetch('user:*:profile'); + +// Refresh all data for user 1 +await RunCache.refetch('user:1:*'); +``` + +This only works for entries that were created with a source function. + +## Pattern Matching with Event Listeners + +You can use patterns when registering event listeners: + +```typescript +// Listen for expiry of any user profile +await RunCache.onKeyExpiry('user:*:profile', (event) => { + console.log(`User profile ${event.key} expired`); +}); + +// Listen for refetch of any API data +await RunCache.onKeyRefetch('api:*', (event) => { + console.log(`API data ${event.key} was refreshed`); +}); +``` + +## Pattern Matching Best Practices + +### 1. Use Structured Key Naming + +Adopt a consistent key naming convention to make pattern matching more effective: + +```typescript +// Good - structured naming with clear segments +await RunCache.set({ key: 'user:1:profile', value: '...' }); +await RunCache.set({ key: 'user:1:settings', value: '...' }); +await RunCache.set({ key: 'post:123:comments', value: '...' }); + +// Less effective - inconsistent naming +await RunCache.set({ key: 'user1Profile', value: '...' }); +await RunCache.set({ key: 'user1_settings', value: '...' }); +await RunCache.set({ key: 'post123Comments', value: '...' }); +``` + +A common convention is to use colons (`:`) as separators for hierarchical keys: +- `entity:id:attribute` +- `domain:subDomain:item` +- `context:identifier:property` + +### 2. Be Specific with Patterns + +Use patterns that are as specific as possible to avoid unintended matches: + +```typescript +// Too broad - might match unrelated keys +await RunCache.delete('user*'); + +// Better - more specific pattern +await RunCache.delete('user:*'); + +// Best - most specific pattern for the use case +await RunCache.delete('user:1:*'); +``` + +### 3. Consider Performance Implications + +Pattern matching operations require checking all cache keys, which can be expensive for large caches: + +```typescript +// Inefficient for large caches - checks all keys +const allUserData = await RunCache.get('user:*'); + +// More efficient - use specific patterns when possible +const specificUserData = await RunCache.get('user:1:*'); +``` + +### 4. Use Tags for Complex Grouping + +For complex grouping needs, consider using tags instead of relying solely on pattern matching: + +```typescript +// Set entries with tags +await RunCache.set({ + key: 'user:1:profile', + value: '...', + tags: ['user:1', 'profile'] +}); + +await RunCache.set({ + key: 'user:1:settings', + value: '...', + tags: ['user:1', 'settings'] +}); + +// Later, invalidate by tag +await RunCache.invalidateByTag('user:1'); +``` + +## Common Pattern Matching Use Cases + +### 1. User-Specific Data + +Cache and manage user-specific data: + +```typescript +// Store user data +await RunCache.set({ key: `user:${userId}:profile`, value: profileData }); +await RunCache.set({ key: `user:${userId}:preferences`, value: preferencesData }); +await RunCache.set({ key: `user:${userId}:activity`, value: activityData }); + +// When user logs out, clear all their data +await RunCache.delete(`user:${userId}:*`); +``` + +### 2. API Response Caching + +Cache API responses with structured keys: + +```typescript +// Cache API responses +await RunCache.set({ + key: `api:users:list:page=${page}:limit=${limit}`, + value: usersList, + ttl: 300000 // 5 minutes +}); + +// Invalidate all user list caches when data changes +await RunCache.delete('api:users:list:*'); +``` + +### 3. Feature Flags + +Manage feature flags with pattern matching: + +```typescript +// Set feature flags +await RunCache.set({ key: 'feature:darkMode:enabled', value: 'true' }); +await RunCache.set({ key: 'feature:newUI:enabled', value: 'false' }); + +// Check if a feature is enabled +const featureFlags = await RunCache.get('feature:*:enabled'); +const darkModeEnabled = featureFlags.includes('true'); + +// Disable all features +await RunCache.set({ key: 'feature:*:enabled', value: 'false' }); +``` + +### 4. Hierarchical Data + +Manage hierarchical data structures: + +```typescript +// Store hierarchical data +await RunCache.set({ key: 'org:1:dept:engineering:team:frontend', value: '...' }); +await RunCache.set({ key: 'org:1:dept:engineering:team:backend', value: '...' }); +await RunCache.set({ key: 'org:1:dept:marketing:team:content', value: '...' }); + +// Get all engineering teams +const engineeringTeams = await RunCache.get('org:1:dept:engineering:team:*'); + +// Delete all marketing teams +await RunCache.delete('org:1:dept:marketing:team:*'); +``` + +## Advanced Pattern Matching Techniques + +### 1. Dynamic Pattern Generation + +Generate patterns dynamically based on application state: + +```typescript +function generateUserPattern(userId, section = null) { + if (section) { + return `user:${userId}:${section}:*`; + } + return `user:${userId}:*`; +} + +// Usage +const userProfileData = await RunCache.get(generateUserPattern(userId, 'profile')); +await RunCache.delete(generateUserPattern(userId)); // Delete all user data +``` + +### 2. Pattern-Based Cache Warming + +Use patterns to implement cache warming strategies: + +```typescript +async function warmUserCache(userId) { + // Check if user data is already cached + const hasUserData = await RunCache.has(`user:${userId}:*`); + + if (!hasUserData) { + // Fetch and cache user data + const userData = await fetchUserData(userId); + await RunCache.set({ key: `user:${userId}:profile`, value: userData.profile }); + await RunCache.set({ key: `user:${userId}:preferences`, value: userData.preferences }); + // ...more user data + } +} +``` + +### 3. Combining Patterns with Other Features + +Combine pattern matching with other RunCache features: + +```typescript +// Set up entries with TTL and autoRefetch +await RunCache.set({ + key: `data:region:${region}:stats`, + sourceFn: () => fetchRegionStats(region), + ttl: 300000, + autoRefetch: true +}); + +// Listen for refetch events on all region stats +await RunCache.onKeyRefetch('data:region:*:stats', (event) => { + console.log(`Stats for ${event.key} were refreshed`); +}); + +// Manually refresh all region stats +await RunCache.refetch('data:region:*:stats'); +``` + +## Next Steps + +Now that you understand pattern matching, explore these related topics: + +- [Cache Management](./cache-management.md) - Learn more about basic cache operations +- [Tag-based Invalidation](../advanced/tag-invalidation.md) - Another way to group and invalidate related cache entries +- [Event System](../advanced/event-system.md) - Understand how to use events with pattern matching +- [Resource Management](../advanced/resource-management.md) - Learn about memory management and cleanup \ No newline at end of file diff --git a/gitbook-versions/v1.7/features/source-functions.md b/gitbook-versions/v1.7/features/source-functions.md new file mode 100644 index 0000000..6a4732e --- /dev/null +++ b/gitbook-versions/v1.7/features/source-functions.md @@ -0,0 +1,391 @@ +# Source Functions + +Source functions are a powerful feature in RunCache that allow you to dynamically generate cache values. This guide explains how to use source functions effectively in your applications. + +## Understanding Source Functions + +A source function is a function that generates a value for a cache entry. Instead of providing a static value when setting a cache entry, you provide a function that RunCache will call to generate the value when needed. + +Key benefits of using source functions: + +- **Lazy Loading**: Values are only generated when actually needed +- **Automatic Serialization**: No need to manually stringify the result +- **Error Handling**: RunCache handles errors from the source function +- **Automatic Refresh**: Can be combined with TTL and autoRefetch + +## Basic Usage + +To use a source function, provide it as the `sourceFn` parameter when setting a cache entry: + +```typescript +await RunCache.set({ + key: 'user-profile', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1'); + const data = await response.json(); + return data; + } +}); +``` + +When `RunCache.get('user-profile')` is called for the first time, RunCache will: +1. Execute the source function +2. Store the returned value in the cache +3. Return the value to the caller + +Subsequent calls to `RunCache.get('user-profile')` will return the cached value without calling the source function again. + +## Synchronous vs. Asynchronous Source Functions + +RunCache supports both synchronous and asynchronous source functions: + +### Synchronous Source Functions + +```typescript +await RunCache.set({ + key: 'computed-value', + sourceFn: () => { + const result = performExpensiveCalculation(); + return result; + } +}); +``` + +### Asynchronous Source Functions + +```typescript +await RunCache.set({ + key: 'api-data', + sourceFn: async () => { + const response = await fetch('https://api.example.com/data'); + const data = await response.json(); + return data; + } +}); +``` + +Both types of functions are handled appropriately by RunCache. + +## Source Functions with TTL + +You can combine source functions with TTL (Time-to-Live) to automatically invalidate cache entries after a certain period: + +```typescript +await RunCache.set({ + key: 'weather-data', + sourceFn: async () => { + const response = await fetch('https://api.weather.com/current'); + const data = await response.json(); + return data; + }, + ttl: 30 * 60 * 1000 // 30 minutes +}); +``` + +In this example: +1. The first call to `RunCache.get('weather-data')` will execute the source function +2. Subsequent calls within 30 minutes will return the cached value +3. After 30 minutes, the next call will execute the source function again + +## Source Functions with Automatic Refetching + +For critical data that should always be available, combine source functions with automatic refetching: + +```typescript +await RunCache.set({ + key: 'stock-prices', + sourceFn: async () => { + const response = await fetch('https://api.example.com/stocks'); + const data = await response.json(); + return data; + }, + ttl: 60000, // 1 minute + autoRefetch: true +}); +``` + +With `autoRefetch: true`: +1. When the TTL expires, the next `get()` call will return the stale data immediately +2. Simultaneously, RunCache will trigger a background refresh using the source function +3. Once the refresh completes, the cache is updated with fresh data + +## Manually Refreshing Source Function Values + +You can manually trigger a refresh for any cache entry with a source function: + +```typescript +await RunCache.refetch('stock-prices'); +``` + +This will: +1. Execute the source function again +2. Update the cache with the new value +3. Reset the TTL timer (if applicable) + +## Error Handling in Source Functions + +If a source function throws an error, RunCache handles it appropriately: + +### Initial Fetch + +`set()` calls the source function before anything is written. If it throws: +1. The error is propagated to the caller of `set()` +2. No cache entry is created, and no TTL timer is started for it (so no `expire` event or auto-refetch follows) + +```typescript +try { + await RunCache.set({ key: 'api-data', sourceFn: fetchApiData, ttl: 60000 }); +} catch (error) { + console.error('Failed to fetch API data:', error); +} +``` + +### Overwriting an Existing Entry + +If `set()` is called for a key that already exists and the source function (or a middleware) throws, the existing entry is left exactly as it was. It keeps its value, its TTL timer and, if enabled, its automatic refetching. A new value only replaces the old one, together with its TTL, once it has been produced successfully. + +### Refetch Failures + +If the source function throws during an automatic refetch: +1. The stale value remains in the cache +2. A refetch failure event is triggered +3. The error doesn't propagate to the caller of `get()` + +```typescript +// Register for refetch failure events +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh ${event.key}:`, event.error); + + // Implement retry logic + setTimeout(() => RunCache.refetch(event.key), 30000); +}); +``` + +## Advanced Source Function Patterns + +### Parameterized Source Functions + +You can create source functions that use parameters from the cache key: + +```typescript +// Helper function to create parameterized source functions +function createUserProfileSource(userId) { + return async () => { + const response = await fetch(`https://api.example.com/users/${userId}`); + return response.json(); + }; +} + +// Set cache entries with different parameters +await RunCache.set({ + key: 'user:1:profile', + sourceFn: createUserProfileSource(1) +}); + +await RunCache.set({ + key: 'user:2:profile', + sourceFn: createUserProfileSource(2) +}); +``` + +### Caching Function Results + +You can create a wrapper to automatically cache function results: + +```typescript +async function cachedFetch(url, options = {}) { + const cacheKey = `fetch:${url}`; + + // Try to get from cache first + const cachedResponse = await RunCache.get(cacheKey); + if (cachedResponse !== undefined) { // false and 0 are valid cached responses + return cachedResponse; + } + + // Set up cache with source function + await RunCache.set({ + key: cacheKey, + sourceFn: async () => { + const response = await fetch(url, options); + const data = await response.json(); + return data; + }, + ttl: options.ttl || 60000 // Default 1 minute TTL + }); + + // Get the newly cached value + return RunCache.get(cacheKey); +} + +// Usage +const userData = await cachedFetch('https://api.example.com/users/1', { ttl: 300000 }); +``` + +### Source Functions with Dependencies + +You can create source functions that depend on other cached values: + +```typescript +interface UserProfile { + preferences: string[]; +} + +// Primary data +await RunCache.set({ + key: 'user:1:profile', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1'); + const data = await response.json(); + return data; + } +}); + +// Dependent data +await RunCache.set({ + key: 'user:1:recommendations', + sourceFn: async () => { + // Get the user profile from cache first + const profile = await RunCache.get('user:1:profile'); + if (!profile || Array.isArray(profile)) { + throw new Error('User profile is not cached'); + } + + // Use profile data to fetch recommendations + const response = await fetch(`https://api.example.com/recommendations?preferences=${profile.preferences.join(',')}`); + const recommendations = await response.json(); + return recommendations; + }, + dependencies: ['user:1:profile'] // Removed by invalidateByDependency('user:1:profile') +}); +``` + +## Best Practices for Source Functions + +### 1. Keep Source Functions Pure + +Source functions should: +- Have no side effects +- Return the same result for the same inputs +- Not depend on external state that might change + +```typescript +// Good - pure function +await RunCache.set({ + key: 'user:1', + sourceFn: () => fetchUserById(1) +}); + +// Avoid - depends on external state +let currentUserId = 1; +await RunCache.set({ + key: 'current-user', + sourceFn: () => fetchUserById(currentUserId) // Will break if currentUserId changes +}); +``` + +### 2. Handle Errors Properly + +Always implement error handling in your source functions: + +```typescript +await RunCache.set({ + key: 'api-data', + sourceFn: async () => { + try { + const response = await fetch('https://api.example.com/data'); + if (!response.ok) { + throw new Error(`API returned ${response.status}`); + } + const data = await response.json(); + return data; + } catch (error) { + console.error('Source function error:', error); + throw error; // Rethrow to let RunCache handle it + } + } +}); +``` + +### 3. Return the Value You Want Back + +A source function can return a string or any serializable value. Whatever it returns is what `get()` gives back: + + +```typescript +// Returns an object: get() returns the object +await RunCache.set({ + key: 'user-data', + sourceFn: async () => fetchUserData() +}); +const user = await RunCache.get('user-data'); // UserData object + +// Returns a string: get() returns the same string, even if it looks like JSON +await RunCache.set({ + key: 'user-data:raw', + sourceFn: async () => JSON.stringify(await fetchUserData()) +}); +const raw = await RunCache.get('user-data:raw'); // string; JSON.parse it yourself +``` + +Non-string results are serialized on every fetch and refetch, so middleware always receives a string. + +### 4. Optimize for Performance + +Keep source functions efficient: +- Fetch only the data you need +- Use appropriate caching headers for API requests +- Consider batching related requests + +```typescript +// Inefficient - fetches too much data +await RunCache.set({ + key: 'user-name', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1'); + const user = await response.json(); + return user.name; // Only needed the name + } +}); + +// Better - uses a more targeted endpoint +await RunCache.set({ + key: 'user-name', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1/name'); + const name = await response.text(); + return name; + } +}); +``` + +### 5. Use Appropriate TTL Values + +Set TTL values based on: +- How frequently the underlying data changes +- How critical data freshness is +- Resource constraints of your application + +```typescript +// Frequently changing data +await RunCache.set({ + key: 'stock-price', + sourceFn: () => fetchStockPrice(), + ttl: 60 * 1000 // 1 minute +}); + +// Relatively stable data +await RunCache.set({ + key: 'company-info', + sourceFn: () => fetchCompanyInfo(), + ttl: 24 * 60 * 60 * 1000 // 1 day +}); +``` + +## Next Steps + +Now that you understand source functions, explore these related topics: + +- [TTL and Expiration](./ttl-expiration.md) - Learn more about time-to-live functionality +- [Automatic Refetching](./auto-refetch.md) - Dive deeper into background refresh functionality +- [Dependency Tracking](../advanced/dependency-tracking.md) - Learn about relationships between cache entries +- [Event System](../advanced/event-system.md) - Understand how to use events for cache monitoring \ No newline at end of file diff --git a/gitbook-versions/v1.7/features/ttl-expiration.md b/gitbook-versions/v1.7/features/ttl-expiration.md new file mode 100644 index 0000000..82da4a4 --- /dev/null +++ b/gitbook-versions/v1.7/features/ttl-expiration.md @@ -0,0 +1,255 @@ +# TTL and Expiration + +Time-to-Live (TTL) is a fundamental feature of RunCache that allows you to control how long cache entries remain valid. This guide explains how TTL works and how to effectively use it in your applications. + +## Understanding TTL + +TTL (Time-to-Live) defines the lifespan of a cache entry in milliseconds. After the TTL period expires, the cache entry is considered stale and will be removed from the cache when accessed. + +Key benefits of using TTL: + +- **Data Freshness**: Ensures cached data doesn't become too stale +- **Memory Management**: Helps prevent the cache from growing indefinitely +- **Consistency**: Provides a mechanism to periodically refresh data + +## Setting TTL + +You can set TTL when creating a cache entry using the `set` method: + +```typescript +await RunCache.set({ + key: 'user-profile', + value: { name: 'John Doe' }, + ttl: 3600000 // 1 hour in milliseconds +}); +``` + +### Common TTL Values + +Here are some common TTL values for reference: + +```typescript +const TTL = { + MINUTE: 60 * 1000, // 60,000 ms + HOUR: 60 * 60 * 1000, // 3,600,000 ms + DAY: 24 * 60 * 60 * 1000, // 86,400,000 ms + WEEK: 7 * 24 * 60 * 60 * 1000 // 604,800,000 ms +}; + +// Examples +await RunCache.set({ key: 'frequently-updated', value: 'data', ttl: TTL.MINUTE }); +await RunCache.set({ key: 'daily-stats', value: 'statistics', ttl: TTL.DAY }); +``` + +### Valid TTL Values + +`ttl` must be a finite, positive number of milliseconds. `set()` throws for `0`, negative values, `NaN`, `Infinity` and non-numbers. To cache an entry that never expires, leave `ttl` out. + +There is no upper limit. Long TTLs, including ones beyond the roughly 24.8-day maximum delay of `setTimeout`, expire at the right time: + +```typescript +// Expires in 90 days +await RunCache.set({ key: 'quarterly-report', value: 'report', ttl: 90 * TTL.DAY }); +``` + +## How Expiration Works + +Each entry with a TTL has a timer. When the TTL elapses: + +1. An `expire` event is emitted +2. What happens next depends on the entry: + - **Plain values** (no `sourceFn`) are removed from memory immediately, whether or not they are ever read again. They no longer count towards `maxEntries`. + - **Entries with `autoRefetch`** are refreshed in the background. Until the refresh completes, `get()` returns the previous (stale) value. + - **Entries with a `sourceFn` but without `autoRefetch`** stay in memory so that you can still call `refetch(key)`, for example from an expiry listener. A `get()` or `has()` on such an entry returns `undefined`/`false` and removes it. + +Expired entries are never served by `get()` (except the stale value of an auto-refetched entry described above), and they are not written to storage by `saveToStorage()`. + +In Node.js the timers are `unref()`'d, so pending TTLs never keep a process from exiting on its own. + +## Checking Expiration Status + +You can check if a key exists (and hasn't expired) using the `has` method: + +```typescript +const isValid = await RunCache.has('user-profile'); +if (isValid) { + console.log('The user profile is still valid'); +} else { + console.log('The user profile has expired or doesn\'t exist'); +} +``` + +## Expiry Events + +RunCache provides an event system to monitor when cache entries expire: + +```typescript +// Global expiry event +await RunCache.onExpiry((event) => { + console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); +}); + +// Specific key expiry +await RunCache.onKeyExpiry("api-data", (event) => { + console.log(`API data cache expired`); +}); + +// Pattern-based expiry events +await RunCache.onKeyExpiry("user-*", (event) => { + console.log(`User cache ${event.key} expired`); +}); +``` + +Each expiry is reported once, with the entry's stored `value` and its `ttl`. The event fires when the TTL timer elapses. If a `get()` or `has()` call notices the expiry first, the event fires then instead, and it is not repeated. Entries that are overwritten or deleted before their TTL elapses do not emit an expiry event. + +These events can be useful for: +- Logging and monitoring +- Triggering background processes +- Updating UI components when data becomes stale + +## TTL with Source Functions + +When using source functions with TTL, you can create a powerful pattern for keeping cached data fresh: + +```typescript +await RunCache.set({ + key: 'weather-data', + sourceFn: async () => { + const response = await fetch('https://api.weather.com/current'); + const data = await response.json(); + return data; + }, + ttl: 30 * 60 * 1000 // 30 minutes +}); +``` + +In this example: +1. The first call to `RunCache.get('weather-data')` will fetch from the API +2. Subsequent calls within 30 minutes will return the cached data +3. After 30 minutes, the next call will trigger a new API fetch + +## Automatic Refetching + +For critical data that should always be available, you can combine TTL with automatic refetching: + +```typescript +await RunCache.set({ + key: 'critical-stats', + sourceFn: async () => { + const response = await fetch('https://api.example.com/stats'); + const data = await response.json(); + return data; + }, + ttl: 5 * 60 * 1000, // 5 minutes + autoRefetch: true +}); +``` + +With `autoRefetch: true`: +1. When the TTL expires, the next `get()` call will return the stale data immediately +2. Simultaneously, RunCache will trigger a background refresh using the source function +3. Once the refresh completes, the cache is updated with fresh data +4. Subsequent calls will get the new data + +This pattern prevents cache stampedes and ensures users always get a response quickly. + +## Handling Refetch Failures + +When using `autoRefetch`, it's important to handle potential failures in the background refresh: + +```typescript +// Global refetch failure event +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}: ${event.error}`); +}); + +// Specific key refetch failure +await RunCache.onKeyRefetchFailure("critical-stats", (event) => { + console.error(`Critical stats refresh failed: ${event.error}`); + + // Implement retry logic or fallback mechanism + setTimeout(() => RunCache.refetch("critical-stats"), 30000); // Retry after 30 seconds +}); +``` + +## TTL Best Practices + +Here are some best practices for effectively using TTL: + +1. **Match TTL to data volatility**: + - Use shorter TTL for frequently changing data + - Use longer TTL for stable data + - Consider the consequences of serving stale data + +2. **Use appropriate time units**: + - Define constants for common TTL values + - Use clear variable names to indicate time units + +3. **Consider access patterns**: + - For frequently accessed data, longer TTL improves performance + - For infrequently accessed data, shorter TTL keeps memory usage down + +4. **Implement staggered expiration**: + - Add small random variations to TTL to prevent mass expiration + ```typescript + const baseTTL = 3600000; // 1 hour + const jitter = Math.floor(Math.random() * 300000); // 0-5 minutes + await RunCache.set({ key: 'data', value: 'value', ttl: baseTTL + jitter }); + ``` + +5. **Use `autoRefetch` for critical data**: + - Ensures users always get a response + - Prevents cache stampedes + - Maintains data freshness in the background + +## Advanced TTL Scenarios + +### Sliding Expiration + +RunCache doesn't directly support sliding expiration (extending TTL on access), but you can implement it manually: + +```typescript +async function getWithSlidingExpiration(key, slidingTTL) { + const value = await RunCache.get(key); + if (value) { + // Reset the TTL by setting the same value again + await RunCache.set({ key, value, ttl: slidingTTL }); + } + return value; +} + +// Usage +const userData = await getWithSlidingExpiration('user:1', 3600000); +``` + +### Conditional Expiration + +You can implement conditional expiration by checking certain conditions before refreshing: + +```typescript +async function getWithConditionalRefresh(key) { + const value = await RunCache.get(key); + + // If value exists but some condition requires refresh + if (value !== undefined && shouldRefreshData(value)) { + await RunCache.refetch(key); + return await RunCache.get(key); + } + + return value; +} + +function shouldRefreshData(data) { + // Custom logic to determine if data needs refresh + return data.version < CURRENT_VERSION; +} +``` + +## Next Steps + +Now that you understand TTL and expiration, explore these related topics: + +- [Automatic Refetching](./auto-refetch.md) - Learn more about background refresh functionality +- [Source Functions](./source-functions.md) - Dive deeper into source functions +- [Event System](../advanced/event-system.md) - Understand how to use events for cache monitoring +- [Resource Management](../advanced/resource-management.md) - Learn about memory management and cleanup \ No newline at end of file diff --git a/gitbook-versions/v1.7/getting-started/basic-usage.md b/gitbook-versions/v1.7/getting-started/basic-usage.md new file mode 100644 index 0000000..d199727 --- /dev/null +++ b/gitbook-versions/v1.7/getting-started/basic-usage.md @@ -0,0 +1,305 @@ +# Basic Usage + +This guide covers the fundamental operations and patterns for using RunCache in your applications. After reading this guide, you'll understand how to perform basic caching operations and integrate RunCache into your projects. + +## Importing the Library + +First, import RunCache in your JavaScript or TypeScript file: + +```typescript +import { RunCache } from 'run-cache'; +``` + +## Basic Cache Operations + +### Setting Cache Values + +The most basic operation is storing a value in the cache: + +```typescript +// Store a simple string +await RunCache.set({ key: 'greeting', value: 'Hello, World!' }); +``` + +Objects, arrays, numbers and booleans can be stored directly. RunCache stores them as JSON and `get()` returns them parsed (see [Value Serialization](../advanced/serialization-adapters.md) for types JSON cannot represent): + +```typescript +// Store a JSON object +const user = { id: 1, name: 'John Doe', email: 'john@example.com' }; +await RunCache.set({ key: 'user:1', value: user }); +``` + +### Getting Cache Values + +To retrieve values from the cache: + +```typescript +// Get a simple string +const greeting = await RunCache.get('greeting'); +console.log(greeting); // Output: Hello, World! + +// Get an object: it comes back parsed +// (get() is typed T | T[] | undefined, because a key may be a wildcard pattern) +const user = (await RunCache.get('user:1')) as { name: string } | undefined; +if (user) { + console.log(user.name); // Output: John Doe +} +``` + +### Checking if a Key Exists + +To check if a key exists in the cache (and hasn't expired): + +```typescript +const exists = await RunCache.has('greeting'); +if (exists) { + console.log('The greeting is cached'); +} else { + console.log('The greeting is not cached'); +} +``` + +### Deleting Cache Entries + +To remove a specific entry from the cache: + +```typescript +await RunCache.delete('greeting'); +``` + +### Clearing the Entire Cache + +To remove all entries from the cache: + +```typescript +await RunCache.flush(); +``` + +## Working with Time-to-Live (TTL) + +You can set an expiration time for cache entries using the `ttl` parameter (in milliseconds): + +```typescript +// Cache with 5-minute expiration +await RunCache.set({ + key: 'temporary-data', + value: 'This will expire soon', + ttl: 5 * 60 * 1000 // 5 minutes in milliseconds +}); +``` + +After the TTL period, the value will be automatically removed from the cache when accessed. + +## Using Source Functions + +Source functions allow you to generate cache values dynamically. This is particularly useful for API calls or expensive computations: + +```typescript +// Define a function that fetches data +async function fetchUserData(userId) { + console.log(`Fetching data for user ${userId}...`); + // Simulate API call + return { + id: userId, + name: `User ${userId}`, + lastUpdated: new Date().toISOString() + }; +} + +// Cache the result of the source function +await RunCache.set({ + key: 'user:2', + sourceFn: () => fetchUserData(2) +}); + +// The first time you get the value, it calls fetchUserData +const userData = await RunCache.get('user:2'); +console.log(userData); // Output: {"id":2,"name":"User 2","lastUpdated":"..."} + +// Subsequent calls use the cached value without calling fetchUserData again +const cachedData = await RunCache.get('user:2'); +``` + +### Benefits of Source Functions + +Using source functions provides several advantages: + +1. **Lazy Loading**: The function is only called when the value is first requested +2. **Automatic Serialization**: No need to manually stringify the result +3. **Error Handling**: RunCache handles errors from the source function +4. **Automatic Refresh**: Can be combined with TTL and autoRefetch + +## Automatic Refetching + +You can configure cache entries to automatically refresh when they expire: + +```typescript +await RunCache.set({ + key: 'stock-price', + sourceFn: async () => { + // Simulate API call + const price = Math.floor(Math.random() * 1000) / 10; + return { symbol: 'AAPL', price }; + }, + ttl: 60000, // 1 minute + autoRefetch: true +}); + +// Even after expiration, get() will return the last value while refreshing in background +const stockPrice = await RunCache.get('stock-price'); +``` + +With `autoRefetch: true`, when the TTL expires, RunCache will: +1. Return the stale value to the caller immediately +2. Trigger a background refresh using the source function +3. Update the cache with the new value + +This pattern prevents cache stampedes and ensures users always get a response quickly. + +## Working with Patterns + +RunCache supports wildcard patterns for operating on multiple related cache keys: + +```typescript +// Set multiple related entries +await RunCache.set({ key: 'product:1:name', value: 'Laptop' }); +await RunCache.set({ key: 'product:1:price', value: '999.99' }); +await RunCache.set({ key: 'product:2:name', value: 'Smartphone' }); +await RunCache.set({ key: 'product:2:price', value: '499.99' }); + +// Get all product names +const names = await RunCache.get('product:*:name'); +console.log(names); // Output: ['Laptop', 'Smartphone'] + +// Delete all data for product 1 +await RunCache.delete('product:1:*'); +``` + +Patterns are useful for: +- Batch operations on related cache entries +- Implementing hierarchical cache structures +- Organizing cache entries by domain or entity type + +## Error Handling + +RunCache operations can throw errors in certain situations: + +```typescript +try { + await RunCache.set({ key: '', value: 'Invalid key' }); +} catch (error) { + console.error('Error setting cache:', error.message); + // Output: Error setting cache: Empty key +} + +try { + await RunCache.set({ key: 'valid-key' }); +} catch (error) { + console.error('Error setting cache:', error.message); + // Output: Error setting cache: `value` can't be empty without a `sourceFn` +} +``` + +An empty string is a valid value (`value: ''`); only a missing value requires a `sourceFn`. + +Failures in a source function or in middleware are thrown as `SourceFnError` or `MiddlewareError` (both extend `RunCacheError`). The original error is available as `cause`, and the key as `key`: + +```typescript +import { RunCache, SourceFnError } from 'run-cache'; + +try { + await RunCache.set({ key: 'user:1', sourceFn: () => fetchUser(1) }); +} catch (error) { + if (error instanceof SourceFnError) { + console.error(`Loading ${error.key} failed:`, error.cause); + } +} +``` + +`refetch_failure` events carry the same original error in `event.error`. + +Common error scenarios include: +- Empty or invalid keys +- Missing required parameters +- Source function errors +- Storage adapter failures + +## Basic Configuration + +Configure RunCache with global settings: + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +// Configure cache settings +await RunCache.configure({ + maxEntries: 1000, // Maximum number of entries + evictionPolicy: EvictionPolicy.LRU, // Least Recently Used eviction policy + debug: true // Enable debug logging for debugging +}); + +// Get current configuration +const config = await RunCache.getConfig(); +console.log(config); +``` + +Configuration options include: +- `maxEntries`: Maximum number of entries before eviction +- `evictionPolicy`: Strategy for removing entries when maxEntries is reached +- `debug`: Enable detailed logging for debugging +- `storageAdapter`: Configure persistent storage + +## Practical Example: API Caching + +Here's a practical example of using RunCache to cache API responses: + +```typescript +async function fetchUserWithCache(userId) { + const cacheKey = `user:${userId}`; + + // Try to get from cache first + const cachedUser = await RunCache.get(cacheKey); + if (cachedUser) { + console.log('Cache hit for user:', userId); + return cachedUser; + } + + // Cache miss, fetch from API + console.log('Cache miss for user:', userId); + try { + const response = await fetch(`https://api.example.com/users/${userId}`); + const userData = await response.json(); + + // Store in cache with 1-hour TTL + await RunCache.set({ + key: cacheKey, + value: userData, + ttl: 60 * 60 * 1000 // 1 hour + }); + + return userData; + } catch (error) { + console.error('Error fetching user data:', error); + throw error; + } +} + +// Usage +const user1 = await fetchUserWithCache(1); // Cache miss, fetches from API +const user1Again = await fetchUserWithCache(1); // Cache hit, returns cached data +``` + +This pattern is commonly used to: +- Reduce API calls and improve performance +- Decrease load on backend services +- Improve user experience with faster response times +- Handle intermittent API failures gracefully + +## Next Steps + +Now that you understand RunCache, you can explore more advanced features: + +- [TTL and Expiration](../features/ttl-expiration.md) - Learn more about time-to-live functionality +- [Source Functions](../features/source-functions.md) - Dive deeper into source functions +- [Eviction Policies](../features/eviction-policies.md) - Configure how cache entries are evicted +- [Pattern Matching](../features/pattern-matching.md) - Master wildcard patterns \ No newline at end of file diff --git a/gitbook-versions/v1.7/getting-started/installation.md b/gitbook-versions/v1.7/getting-started/installation.md new file mode 100644 index 0000000..934168f --- /dev/null +++ b/gitbook-versions/v1.7/getting-started/installation.md @@ -0,0 +1,99 @@ +# Installation + +RunCache can be easily installed using npm, yarn, or pnpm. The library has no external dependencies, making it lightweight and simple to integrate into your projects. + +## Using npm + +```bash +npm install run-cache +``` + +## Using yarn + +```bash +yarn add run-cache +``` + +## Using pnpm + +```bash +pnpm add run-cache +``` + +## Module Formats + +The package provides both CommonJS and ES module builds, selected automatically through the `exports` field in `package.json`: + +| How you load it | File used | +| --- | --- | +| `import { RunCache } from 'run-cache'` (Node.js ESM, bundlers) | `dist/index.mjs` | +| `require('run-cache')` | `dist/index.js` | +| ` +``` + +## TypeScript Support + +RunCache includes TypeScript definitions, so no additional packages are required for TypeScript projects. The library is written in TypeScript, ensuring type safety and excellent IDE integration. + +```typescript +// TypeScript example +import { RunCache, EvictionPolicy } from 'run-cache'; + +// Configure with proper type checking +async function setupCache(): Promise { + await RunCache.configure({ + maxEntries: 100, + evictionPolicy: EvictionPolicy.LRU + }); +} + +setupCache().catch(console.error); +``` + +## Verifying Installation + +To verify that RunCache is installed correctly, you can create a simple test file: + +```typescript +import { RunCache } from 'run-cache'; + +async function testRunCache() { + await RunCache.set({ key: 'test', value: 'It works!' }); + const value = await RunCache.get('test'); + console.log(value); // Should output: It works! +} + +testRunCache(); +``` + +## Next Steps + +Once you have RunCache installed, check out the [Basic Usage](basic-usage.md) guide to learn how to use the basic features of the library. \ No newline at end of file diff --git a/gitbook-versions/v1.7/getting-started/typed-caching.md b/gitbook-versions/v1.7/getting-started/typed-caching.md new file mode 100644 index 0000000..a3895fe --- /dev/null +++ b/gitbook-versions/v1.7/getting-started/typed-caching.md @@ -0,0 +1,434 @@ +# Typed Caching + +RunCache provides powerful TypeScript support that allows you to cache any serializable JavaScript value while maintaining full type safety. This guide covers the new typed features and how to use them effectively in your applications. + +## Overview + +The typed caching features include: + +- **Generic Type Support**: Cache any JavaScript type with full TypeScript intellisense +- **Automatic Serialization**: Built-in serialization for objects, arrays, primitives, and special types +- **Type Safety**: Compile-time and runtime type checking +- **Backward Compatibility**: Existing string-based code continues to work unchanged +- **Custom Serialization**: Extensible serialization system for complex types + +## Basic Typed Operations + +### Simple Typed Values + +```typescript +import { RunCache } from 'run-cache'; + +// Cache primitive types with automatic type inference +await RunCache.set({ key: 'user-count', value: 42 }); +await RunCache.set({ key: 'feature-enabled', value: true }); +await RunCache.set({ key: 'tags', value: ['typescript', 'cache', 'performance'] }); + +// Retrieve values with full type safety +const count = await RunCache.get('user-count'); // number | undefined +const enabled = await RunCache.get('feature-enabled'); // boolean | undefined +const tags = await RunCache.get('tags'); // string[] | undefined +``` + +### Complex Objects and Interfaces + +```typescript +interface User { + id: number; + name: string; + email: string; + preferences: { + theme: 'light' | 'dark'; + notifications: boolean; + }; +} + +const user: User = { + id: 123, + name: 'John Doe', + email: 'john@example.com', + preferences: { + theme: 'dark', + notifications: true + } +}; + +// Cache with full type safety +await RunCache.set({ key: 'user:123', value: user }); + +// Retrieve with automatic type checking +const retrievedUser = await RunCache.get('user:123'); +if (retrievedUser) { + console.log(retrievedUser.name); // TypeScript knows this is a string + console.log(retrievedUser.preferences.theme); // 'light' | 'dark' +} +``` + +### Arrays and Collections + +```typescript +interface Product { + id: number; + name: string; + price: number; + category: string; +} + +const products: Product[] = [ + { id: 1, name: 'Laptop', price: 999.99, category: 'Electronics' }, + { id: 2, name: 'Smartphone', price: 599.99, category: 'Electronics' }, + { id: 3, name: 'Coffee Mug', price: 12.99, category: 'Home' } +]; + +// Cache arrays with type safety +await RunCache.set({ + key: 'products:featured', + value: products, + ttl: 300000 // 5 minutes +}); + +const featuredProducts = await RunCache.get('products:featured'); +if (featuredProducts) { + featuredProducts.forEach(product => { + console.log(`${product.name}: $${product.price}`); // Full type checking + }); +} +``` + +## Typed Cache Instances + +For better type safety and organization, you can create typed cache instances: + +```typescript +// Create a typed cache for a specific type +const userCache = RunCache.createTypedCache(); + +// All operations are now strongly typed for User objects +await userCache.set({ + key: 'user:456', + value: { + id: 456, + name: 'Jane Smith', + email: 'jane@example.com', + preferences: { theme: 'light', notifications: false } + } +}); + +const user = await userCache.get('user:456'); // User | undefined +``` + +## Generic Types and APIs + +RunCache works seamlessly with generic types and API response patterns: + +```typescript +interface ApiResponse { + success: boolean; + data: T; + message: string; + timestamp: number; +} + +interface UserList { + users: User[]; + total: number; + page: number; +} + +// Cache API responses with nested generics +const apiResponse: ApiResponse = { + success: true, + data: { + users: [/* user data */], + total: 150, + page: 1 + }, + message: 'Users retrieved successfully', + timestamp: Date.now() +}; + +await RunCache.set>({ + key: 'api:users:page:1', + value: apiResponse, + ttl: 600000 // 10 minutes +}); + +const cachedResponse = await RunCache.get>('api:users:page:1'); +if (cachedResponse?.success) { + console.log(`Found ${cachedResponse.data.total} users`); +} +``` + +## Source Functions with Types + +Source functions work seamlessly with typed values: + +```typescript +interface WeatherData { + temperature: number; + humidity: number; + condition: 'sunny' | 'cloudy' | 'rainy' | 'snowy'; + location: string; + timestamp: Date; +} + +// Typed source function +const fetchWeatherData = async (city: string): Promise => { + const response = await fetch(`https://api.weather.com/v1/current?city=${city}`); + const data = await response.json(); + + return { + temperature: data.temp, + humidity: data.humidity, + condition: data.condition, + location: city, + timestamp: new Date() + }; +}; + +// Cache with typed source function +await RunCache.set({ + key: 'weather:new-york', + sourceFn: () => fetchWeatherData('New York'), + ttl: 300000, // 5 minutes + autoRefetch: true +}); + +const weather = await RunCache.get('weather:new-york'); +if (weather) { + console.log(`Temperature in ${weather.location}: ${weather.temperature}°F`); +} +``` + +The value returned by a source function is serialized in the same way as a `value` passed to `set()`, both on the initial fetch and on every refetch. Middleware therefore always receives the serialized string. + +## Union Types and Enums + +RunCache supports complex TypeScript types including unions and enums: + +```typescript +enum UserRole { + ADMIN = 'admin', + MODERATOR = 'moderator', + USER = 'user' +} + +type NotificationPreference = 'email' | 'sms' | 'push' | 'none'; + +interface UserProfile { + id: number; + username: string; + role: UserRole; + notifications: NotificationPreference[]; + metadata?: Record; +} + +const profile: UserProfile = { + id: 789, + username: 'admin_user', + role: UserRole.ADMIN, + notifications: ['email', 'push'], + metadata: { lastLogin: new Date().toISOString() } +}; + +await RunCache.set({ key: 'profile:789', value: profile }); + +const userProfile = await RunCache.get('profile:789'); +if (userProfile?.role === UserRole.ADMIN) { + console.log('User has admin privileges'); +} +``` + +## Optional Properties and Partial Types + +TypeScript's optional properties work naturally with RunCache: + +```typescript +interface UserSettings { + theme: 'light' | 'dark'; + language: string; + timezone?: string; + notifications?: { + email?: boolean; + push?: boolean; + sms?: boolean; + }; +} + +// Partial settings updates +const partialSettings: Partial = { + theme: 'dark', + notifications: { email: true } +}; + +await RunCache.set>({ + key: 'settings:partial:123', + value: partialSettings +}); + +const settings = await RunCache.get>('settings:partial:123'); +if (settings?.theme) { + console.log(`User prefers ${settings.theme} theme`); +} +``` + +## Advanced Patterns + +### Conditional Types and Mapped Types + +```typescript +type CacheableEntity = User | Product | UserProfile; + +interface EntityCache { + entity: T; + lastModified: Date; + version: number; +} + +async function cacheEntity( + id: string, + entity: T +): Promise { + const cacheEntry: EntityCache = { + entity, + lastModified: new Date(), + version: 1 + }; + + await RunCache.set>({ + key: `entity:${id}`, + value: cacheEntry, + ttl: 3600000 // 1 hour + }); +} + +// Usage with type inference +await cacheEntity('user-123', user); // T inferred as User +await cacheEntity('product-456', products[0]); // T inferred as Product +``` + +### Repository Pattern with Types + +```typescript +class TypedCacheRepository { + constructor(private prefix: string) {} + + async save(id: string, entity: T, ttl?: number): Promise { + await RunCache.set({ + key: `${this.prefix}:${id}`, + value: entity, + ttl + }); + } + + async findById(id: string): Promise { + return RunCache.get(`${this.prefix}:${id}`); + } + + async findAll(): Promise { + const results = await RunCache.get(`${this.prefix}:*`); + return Array.isArray(results) ? results : []; + } + + async delete(id: string): Promise { + await RunCache.delete(`${this.prefix}:${id}`); + } +} + +// Create typed repositories +const userRepo = new TypedCacheRepository('users'); +const productRepo = new TypedCacheRepository('products'); + +// Usage with full type safety +await userRepo.save('123', user); +const foundUser = await userRepo.findById('123'); // User | undefined +const allUsers = await userRepo.findAll(); // User[] +``` + +## Integration with Existing Features + +All existing RunCache features work seamlessly with typed values: + +### Tags and Dependencies + +```typescript +await RunCache.set({ + key: 'user:123', + value: user, + tags: ['user', 'profile', 'active'], + dependencies: ['user:session:123'] +}); + +// Invalidate all user-related cache entries +await RunCache.invalidateByTag('user'); +``` + +### Events with Types + +```typescript +await RunCache.onExpiry((event) => { + console.log(`User ${event.value.name} expired from cache`); +}); + +await RunCache.onKeyExpiry('product:*', (event) => { + console.log(`Product ${event.value.name} expired`); +}); +``` + +### TTL and Auto-Refetch + +```typescript +await RunCache.set({ + key: 'weather:current', + sourceFn: () => fetchWeatherData('London'), + ttl: 300000, + autoRefetch: true +}); +``` + +## Backward Compatibility + +Existing string-based code continues to work without any changes: + + +```typescript +// This still works exactly as before +await RunCache.set({ key: 'legacy:data', value: 'string value' }); +const legacyData = await RunCache.get('legacy:data'); // string | undefined + +// Mixed usage in the same application +await RunCache.set({ key: 'modern:user', value: user }); +await RunCache.set({ key: 'legacy:config', value: JSON.stringify(config) }); +``` + +Strings are always returned exactly as they were stored. RunCache only deserializes values that it serialized itself, that is values that were not strings when they were set (or returned by a source function). A string that happens to look like JSON keeps its type: + + +```typescript +await RunCache.set({ key: 'zip', value: '02134' }); +await RunCache.set({ key: 'config', value: JSON.stringify({ theme: 'dark' }) }); + +await RunCache.get('zip'); // '02134' (string, not the number 2134) +await RunCache.get('config'); // '{"theme":"dark"}' (string, parse it yourself) + +await RunCache.set<{ theme: string }>({ key: 'config:typed', value: { theme: 'dark' } }); +await RunCache.get<{ theme: string }>('config:typed'); // { theme: 'dark' } +``` + +To get an object back from `get()`, store the object itself rather than its JSON string. + +## Performance Considerations + +Typed caching adds minimal overhead: + +- **Serialization**: Automatic JSON serialization with optimizations for strings +- **Memory Usage**: Efficient in-memory storage with the same footprint as string caching +- **Type Checking**: Zero runtime cost for TypeScript type annotations +- **Custom Types**: Extensible serialization system for complex types + +## Next Steps + +- Learn about [Serialization Adapters](../advanced/serialization-adapters.md) for custom types +- Explore [Type Validation](../advanced/type-validation.md) for runtime type checking +- See the [Migration Guide](../guides/migration-guide.md) for upgrading existing code +- Check out [Best Practices](../guides/best-practices.md) for typed caching patterns \ No newline at end of file diff --git a/gitbook-versions/v1.7/guides/best-practices.md b/gitbook-versions/v1.7/guides/best-practices.md new file mode 100644 index 0000000..9a221f5 --- /dev/null +++ b/gitbook-versions/v1.7/guides/best-practices.md @@ -0,0 +1,838 @@ +# Best Practices + +This guide provides recommendations and best practices for using RunCache effectively in your applications. Following these guidelines will help you optimize performance, maintain data consistency, and avoid common pitfalls. + +## Cache Key Design + +### Use Structured Key Naming + +Adopt a consistent key naming convention to make pattern matching more effective and your code more maintainable: + +```typescript +// Good - structured naming with clear segments +await RunCache.set({ key: 'user:1:profile', value: '...' }); +await RunCache.set({ key: 'user:1:settings', value: '...' }); +await RunCache.set({ key: 'post:123:comments', value: '...' }); + +// Less effective - inconsistent naming +await RunCache.set({ key: 'user1Profile', value: '...' }); +await RunCache.set({ key: 'user1_settings', value: '...' }); +await RunCache.set({ key: 'post123Comments', value: '...' }); +``` + +### Recommended Key Structure + +A common convention is to use colons (`:`) as separators for hierarchical keys: + +``` +entity:id:attribute +``` + +Examples: +- `user:1:profile` - Profile for user with ID 1 +- `product:xyz:details` - Details for product with ID xyz +- `api:users:list:page=1:limit=20` - API response for users list with pagination + +### Be Specific with Keys + +Make keys as specific as needed to avoid collisions: + +```typescript +// Too generic - might cause collisions +await RunCache.set({ key: 'profile', value: '...' }); + +// Better - more specific +await RunCache.set({ key: 'user:1:profile', value: '...' }); +``` + +## TTL and Expiration + +### Match TTL to Data Volatility + +Set TTL values based on how frequently the underlying data changes: + +```typescript +// Frequently changing data +await RunCache.set({ + key: 'stock-price', + value: price, + ttl: 60 * 1000 // 1 minute +}); + +// Relatively stable data +await RunCache.set({ + key: 'product-catalog', + value: catalog, + ttl: 60 * 60 * 1000 // 1 hour +}); + +// Very stable data +await RunCache.set({ + key: 'app-configuration', + value: config, + ttl: 24 * 60 * 60 * 1000 // 1 day +}); +``` + +### Define TTL Constants + +Create constants for common TTL values to ensure consistency: + +```typescript +// Define TTL constants +const TTL = { + SHORT: 60 * 1000, // 1 minute + MEDIUM: 30 * 60 * 1000, // 30 minutes + LONG: 60 * 60 * 1000, // 1 hour + VERY_LONG: 24 * 60 * 60 * 1000 // 1 day +}; + +// Use constants consistently +await RunCache.set({ key: 'user:1:profile', value: '...', ttl: TTL.LONG }); +await RunCache.set({ key: 'api:weather', value: '...', ttl: TTL.SHORT }); +``` + +### Implement Staggered Expiration + +Add small random variations to TTL to prevent mass expiration: + +```typescript +function setWithJitter(key, value, baseTTL) { + const jitter = Math.floor(Math.random() * (baseTTL * 0.1)); // 10% jitter + return RunCache.set({ + key, + value, + ttl: baseTTL + jitter + }); +} + +// Usage +await setWithJitter('api-data-1', jsonData1, 300000); +await setWithJitter('api-data-2', jsonData2, 300000); +await setWithJitter('api-data-3', jsonData3, 300000); +``` + +## Source Functions + +### Keep Source Functions Pure + +Source functions should: +- Have no side effects +- Return the same result for the same inputs +- Not depend on external state that might change + +```typescript +// Good - pure function +await RunCache.set({ + key: 'user:1', + sourceFn: () => fetchUserById(1) +}); + +// Avoid - depends on external state +let currentUserId = 1; +await RunCache.set({ + key: 'current-user', + sourceFn: () => fetchUserById(currentUserId) // Will break if currentUserId changes +}); +``` + +### Handle Errors Properly + +Always implement error handling in your source functions: + +```typescript +await RunCache.set({ + key: 'api-data', + sourceFn: async () => { + try { + const response = await fetch('https://api.example.com/data'); + if (!response.ok) { + throw new Error(`API returned ${response.status}`); + } + const data = await response.json(); + return data; + } catch (error) { + console.error('Source function error:', error); + throw error; // Rethrow to let RunCache handle it + } + } +}); +``` + +### Optimize for Performance + +Keep source functions efficient: +- Fetch only the data you need +- Use appropriate caching headers for API requests +- Consider batching related requests + +```typescript +// Inefficient - fetches too much data +await RunCache.set({ + key: 'user-name', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1'); + const user = await response.json(); + return user.name; // Only needed the name + } +}); + +// Better - uses a more targeted endpoint +await RunCache.set({ + key: 'user-name', + sourceFn: async () => { + const response = await fetch('https://api.example.com/users/1/name'); + const name = await response.text(); + return name; + } +}); +``` + +## Automatic Refetching + +### Use for Critical Data Only + +Automatic refetching is most beneficial for: +- Frequently accessed data +- Data that should never be unavailable +- Data where freshness is important but not critical + +```typescript +// Good candidate for autoRefetch +await RunCache.set({ + key: 'global-settings', + sourceFn: () => fetchGlobalSettings(), + ttl: 5 * 60 * 1000, + autoRefetch: true +}); + +// May not need autoRefetch +await RunCache.set({ + key: 'user-activity-log', + sourceFn: () => fetchUserActivity(), + ttl: 30 * 60 * 1000 + // No autoRefetch as it's less critical +}); +``` + +### Implement Proper Error Handling + +Always handle potential failures in automatic refetching: + +```typescript +// Attempts per key; RunCache events carry no custom metadata +const retryCounts = new Map(); + +await RunCache.onRefetchFailure((event) => { + // Log the error + console.error(`Refetch failed for ${event.key}:`, event.error); + + // Implement exponential backoff retry + const retryCount = (retryCounts.get(event.key) ?? 0) + 1; + retryCounts.set(event.key, retryCount); + const delay = Math.min(1000 * Math.pow(2, retryCount), 30000); // Max 30 seconds + + setTimeout(() => { + RunCache.refetch(event.key) + .then((ok) => { if (ok) retryCounts.delete(event.key); }) + .catch(() => { /* reported again through onRefetchFailure */ }); + }, delay); +}); +``` + +## Pattern Matching + +### Be Specific with Patterns + +Use patterns that are as specific as possible to avoid unintended matches: + +```typescript +// Too broad - might match unrelated keys +await RunCache.delete('user*'); + +// Better - more specific pattern +await RunCache.delete('user:*'); + +// Best - most specific pattern for the use case +await RunCache.delete('user:1:*'); +``` + +### Consider Performance Implications + +Pattern matching operations require checking all cache keys, which can be expensive for large caches: + +```typescript +// Inefficient for large caches - checks all keys +const allUserData = await RunCache.get('user:*'); + +// More efficient - use specific patterns when possible +const specificUserData = await RunCache.get('user:1:*'); +``` + +## Tags and Dependencies + +### Use Tags for Broad Grouping + +Tags are ideal for grouping related cache entries that need to be invalidated together: + +```typescript +// Set entries with tags +await RunCache.set({ + key: 'user:1:profile', + value: '...', + tags: ['user:1', 'profile'] +}); + +await RunCache.set({ + key: 'user:1:settings', + value: '...', + tags: ['user:1', 'settings'] +}); + +// Later, invalidate all user:1 data +await RunCache.invalidateByTag('user:1'); +``` + +### Use Dependencies for Derived Data + +Dependencies are ideal for derived data that depends on base data: + +```typescript +// Primary data +await RunCache.set({ + key: 'user:1:profile', + value: { name: 'John Doe' } +}); + +// Dependent data +await RunCache.set({ + key: 'user:1:dashboard', + value: { widgets: [...] }, + dependencies: ['user:1:profile'] // This entry depends on the profile +}); + +// When user:1:profile changes, user:1:dashboard will be automatically invalidated +``` + +### Avoid Deep Dependency Chains + +Deep dependency chains can lead to widespread invalidations: + +```typescript +// Potentially problematic - deep dependency chain +A → B → C → D → E → F → G + +// Better - flatter dependency structure +A → B, C, D +E → F, G +``` + +## Event System + +### Keep Event Handlers Lightweight + +Event handlers should be fast and non-blocking: + +```typescript +// Good - lightweight handler +await RunCache.onExpiry((event) => { + console.log(`Cache expired: ${event.key}`); +}); + +// Avoid - heavy processing in handler +await RunCache.onExpiry(async (event) => { + // DON'T do this - blocks the event loop + await heavyProcessing(); + await networkRequest(); +}); +``` + +If you need to perform heavy work, delegate it to a separate process or queue. + +### Clean Up Event Listeners + +Remove event listeners when they're no longer needed: + +```typescript +// In a component or module initialization +async function initializeModule() { + // Set up event listeners + await RunCache.onKeyRefetch('module-data', handleRefetch); + + // Return cleanup function + return () => + RunCache.clearEventListeners({ + event: EVENT.REFETCH, + key: 'module-data' + }); +} + +// Later, when shutting down +const cleanup = await initializeModule(); +// When module is unloaded +await cleanup(); +``` + +## Memory Management + +### Set Appropriate Cache Size Limits + +Configure maximum cache size based on your application's memory constraints: + +```typescript +// Configure cache with size limits +await RunCache.configure({ + maxEntries: 1000, // Limit to 1000 entries + evictionPolicy: EvictionPolicy.LRU +}); +``` + +### Choose the Right Eviction Policy + +Select an eviction policy that matches your access patterns: + +- **LRU (Least Recently Used)**: Best for most applications where recently accessed items are likely to be accessed again +- **LFU (Least Frequently Used)**: Better for cases where access frequency is more important than recency +- **NONE**: Use only when you want manual control over eviction or have other TTL-based mechanisms + +```typescript +// For most applications +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LRU +}); + +// For frequency-based patterns +await RunCache.configure({ + maxEntries: 1000, + evictionPolicy: EvictionPolicy.LFU +}); +``` + +### Optimize Value Size + +Minimize the size of cached values: + +```typescript +// Bad - storing unnecessary data +await RunCache.set({ + key: 'user-profile', + value: { + name: 'John Doe', + email: 'john@example.com', + avatar: largeBase64EncodedImage, // Unnecessarily large + fullHistory: completeUserHistory, // Rarely needed data + // ...more data + } +}); + +// Better - store only what's needed +await RunCache.set({ + key: 'user-profile', + value: { + name: 'John Doe', + email: 'john@example.com', + avatarUrl: '/avatars/john.jpg', // Just the URL, not the image + // ...essential data only + } +}); + +// Store rarely needed data separately +await RunCache.set({ + key: 'user-profile:full-history', + value: completeUserHistory, + ttl: 3600000 // With shorter TTL +}); +``` + +## Persistent Storage + +### Choose the Right Storage Adapter + +Select the appropriate storage adapter based on your environment and requirements: + +- **LocalStorageAdapter**: For browser environments with small cache data +- **IndexedDBAdapter**: For browser environments with larger cache data +- **FilesystemAdapter**: For Node.js applications + +```typescript +// For browser with small data +await RunCache.configure({ + storageAdapter: new LocalStorageAdapter() +}); + +// For browser with larger data +await RunCache.configure({ + storageAdapter: new IndexedDBAdapter() +}); + +// For Node.js applications +await RunCache.configure({ + storageAdapter: new FilesystemAdapter() +}); +``` + +### Handle Storage Errors + +Always handle potential storage errors: + +```typescript +try { + await RunCache.loadFromStorage(); + console.log('Cache loaded successfully'); +} catch (error) { + console.error('Failed to load cache:', error); + // Implement fallback mechanism +} +``` + +### Use Appropriate Save Intervals + +Balance between data freshness and performance: + +```typescript +// For frequently changing data, save more often +await RunCache.setupAutoSave(60000); // 1 minute + +// For relatively stable data, save less frequently +await RunCache.setupAutoSave(3600000); // 1 hour +``` + +## Error Handling + +### Handle Cache Misses Gracefully + +Always handle potential cache misses: + +```typescript +// Good - handles cache miss +const userData = await RunCache.get('user:1'); +if (userData !== undefined) { + // Cache hit: objects come back parsed + displayUser(userData); +} else { + // Cache miss + showLoadingIndicator(); + const user = await fetchUserFromApi(1); + await RunCache.set({ key: 'user:1', value: user }); + displayUser(user); +} +``` + +### Implement Circuit Breakers + +For critical systems, implement circuit breakers to prevent cascading failures: + +```typescript +let cacheFailures = 0; +const FAILURE_THRESHOLD = 5; +const RESET_TIMEOUT = 60000; // 1 minute + +async function getCachedData(key) { + if (cacheFailures >= FAILURE_THRESHOLD) { + // Circuit is open, bypass cache + return fetchDataFromSource(key); + } + + try { + const data = await RunCache.get(key); + if (data !== undefined) return data; + + // Cache miss, fetch from source + const sourceData = await fetchDataFromSource(key); + try { + await RunCache.set({ key, value: sourceData }); + } catch (error) { + cacheFailures++; + if (cacheFailures === FAILURE_THRESHOLD) { + console.error('Cache circuit opened due to repeated failures'); + setTimeout(() => { + cacheFailures = 0; + console.log('Cache circuit reset'); + }, RESET_TIMEOUT); + } + } + return sourceData; + } catch (error) { + cacheFailures++; + // Fall back to source on cache error + return fetchDataFromSource(key); + } +} +``` + +## Performance Optimization + +### Batch Related Operations + +Group related cache operations to minimize overhead: + +```typescript +// Less efficient - multiple separate operations +for (const id of userIds) { + await RunCache.set({ key: `user:${id}:profile`, value: profiles[id] }); +} + +// More efficient - batch processing +async function batchSetProfiles(profiles) { + const operations = Object.entries(profiles).map(([id, profile]) => + RunCache.set({ key: `user:${id}:profile`, value: profile }) + ); + await Promise.all(operations); +} + +await batchSetProfiles(profiles); +``` + +### Implement Cache Warming + +Pre-populate critical cache entries on application startup: + +```typescript +async function warmCache() { + console.log('Warming cache...'); + + // Check if entries already exist + const hasConfig = await RunCache.has('app:config'); + const hasGlobalData = await RunCache.has('app:global-data'); + + // Warm up only what's missing + if (!hasConfig) { + const config = await fetchAppConfig(); + await RunCache.set({ key: 'app:config', value: config }); + } + + if (!hasGlobalData) { + const globalData = await fetchGlobalData(); + await RunCache.set({ key: 'app:global-data', value: globalData }); + } + + console.log('Cache warming complete'); +} + +// Call on application startup +warmCache(); +``` + +### Use Middleware for Cross-Cutting Concerns + +Implement middleware for functionality that applies to all cache operations: + +```typescript +// Add logging middleware +await RunCache.use(async (value, context, next) => { + const start = Date.now(); + const result = await next(value); + const duration = Date.now() - start; + + console.log(`${context.operation} operation for key: ${context.key} took ${duration}ms`); + return result; +}); + +// Add encryption middleware +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + return next(encrypt(value)); + } else if (context.operation === 'get' && value) { + const encrypted = await next(value); + return encrypted ? decrypt(encrypted) : undefined; + } + return next(value); +}); +``` + +## Testing + +### Mock RunCache for Unit Tests + +Create a mock version of RunCache for unit testing: + +```typescript +// mock-run-cache.ts +import { RunCache } from 'run-cache'; + +// Save original methods +const originalMethods = { + get: RunCache.get, + set: RunCache.set, + delete: RunCache.delete, + flush: RunCache.flush +}; + +// Mock data +let mockData = new Map(); + +// Mock implementation +export function mockRunCache() { + // Mock get + RunCache.get = jest.fn(async (key) => { + return mockData.get(key); + }); + + // Mock set + RunCache.set = jest.fn(async (options) => { + mockData.set(options.key, options.value); + return true; + }); + + // Mock delete + RunCache.delete = jest.fn(async (key) => { + mockData.delete(key); + return true; + }); + + // Mock flush + RunCache.flush = jest.fn(async () => { + mockData.clear(); + }); + + // Helper to set mock data directly + return { + setMockData: (key, value) => mockData.set(key, value), + clearMockData: () => mockData.clear(), + restore: () => { + RunCache.get = originalMethods.get; + RunCache.set = originalMethods.set; + RunCache.delete = originalMethods.delete; + RunCache.flush = originalMethods.flush; + } + }; +} +``` + +### Write Integration Tests + +Test the cache with actual storage adapters: + +```typescript +import { RunCache, type StorageAdapter } from 'run-cache'; + +// A minimal in-memory adapter for tests (RunCache does not ship one) +class MemoryStorageAdapter implements StorageAdapter { + private data: string | null = null; + async save(data: string) { this.data = data; } + async load() { return this.data; } + async clear() { this.data = null; } +} + +describe('Cache Integration Tests', () => { + beforeEach(async () => { + // Set up fresh cache for each test + await RunCache.configure({ + storageAdapter: new MemoryStorageAdapter() + }); + await RunCache.flush(); + }); + + afterEach(async () => { + // Clears entries, timers and listeners, and detaches the adapter + await RunCache.shutdown(); + }); + + test('should store and retrieve values', async () => { + await RunCache.set({ key: 'test-key', value: 'test-value' }); + const value = await RunCache.get('test-key'); + expect(value).toBe('test-value'); + }); + + test('should respect TTL', async () => { + await RunCache.set({ key: 'expiring-key', value: 'value', ttl: 100 }); + + // Should exist initially + expect(await RunCache.has('expiring-key')).toBe(true); + + // Wait for expiration + await new Promise(resolve => setTimeout(resolve, 150)); + + // Should be gone after TTL + expect(await RunCache.has('expiring-key')).toBe(false); + }); +}); +``` + +## Monitoring and Logging + +### Track Cache Performance Metrics + +Implement monitoring to track cache performance: + +```typescript +// Set up cache metrics +let metrics = { + hits: 0, + misses: 0, + expirations: 0, + refetches: 0, + errors: 0 +}; + +// Add monitoring middleware +await RunCache.use(async (value, context, next) => { + if (context.operation === 'get') { + const result = await next(value); + if (result) { + metrics.hits++; + } else { + metrics.misses++; + } + return result; + } + return next(value); +}); + +// Monitor events +await RunCache.onExpiry(() => metrics.expirations++); +await RunCache.onRefetch(() => metrics.refetches++); +await RunCache.onRefetchFailure(() => metrics.errors++); + +// Report metrics periodically +setInterval(() => { + const hitRatio = metrics.hits / (metrics.hits + metrics.misses || 1); + console.log(`Cache performance: ${(hitRatio * 100).toFixed(2)}% hit ratio`); + console.log(`Expirations: ${metrics.expirations}, Refetches: ${metrics.refetches}, Errors: ${metrics.errors}`); + + // Send to monitoring system + sendMetricsToMonitoring({ + cacheHitRatio: hitRatio, + cacheExpirations: metrics.expirations, + cacheRefetches: metrics.refetches, + cacheErrors: metrics.errors + }); + + // Reset counters + metrics = { hits: 0, misses: 0, expirations: 0, refetches: 0, errors: 0 }; +}, 60000); // Every minute +``` + +### Implement Comprehensive Logging + +Use middleware and events for comprehensive logging: + +```typescript +// Log all cache operations +await RunCache.use(async (value, context, next) => { + console.log(`Cache operation: ${context.operation}, Key: ${context.key}`); + return next(value); +}); + +// Log cache events +await RunCache.onExpiry((event) => { + console.log(`Cache expired: ${event.key}`); +}); + +await RunCache.onRefetch((event) => { + console.log(`Cache refreshed: ${event.key}`); +}); + +await RunCache.onRefetchFailure((event) => { + console.error(`Cache refresh failed: ${event.key}`, event.error); +}); +``` + +## Next Steps + +Now that you understand the best practices for using RunCache, explore these related topics: + +- [Performance Optimization](./performance.md) - Learn more about optimizing cache performance +- [Debugging and Logging](./debugging.md) - Understand how to troubleshoot cache issues +- [API Reference](../api/run-cache.md) - Explore the complete RunCache API \ No newline at end of file diff --git a/gitbook-versions/v1.7/guides/debugging.md b/gitbook-versions/v1.7/guides/debugging.md new file mode 100644 index 0000000..93d6bc7 --- /dev/null +++ b/gitbook-versions/v1.7/guides/debugging.md @@ -0,0 +1,697 @@ +# Debugging and Logging + +This guide provides techniques and strategies for debugging issues in RunCache and implementing effective logging. By following these recommendations, you can identify and resolve problems more quickly and gain better visibility into cache operations. + +## Built-in Logging + +RunCache includes built-in logging capabilities through its debug mode. + +### Enabling debug Mode + +To enable debug logging: + +```typescript +import { RunCache } from 'run-cache'; + +// Enable debug logging +await RunCache.configure({ + debug: true +}); +``` + +When debug mode is enabled, RunCache logs detailed information about: +- Cache operations (set, get, delete, etc.) +- Entry expiration and eviction +- Refetch operations and failures +- Configuration changes + +All logs include timestamps and operation details. Nothing is logged, not even errors, while debug mode is off. + +### Disabling debug Mode + +To disable debug logging when you're done debugging: + +```typescript +// Disable debug logging +await RunCache.configure({ + debug: false +}); +``` + +## Custom Logging with Middleware + +You can implement more detailed custom logging using middleware. + +### Basic Logging Middleware + +```typescript +import { RunCache } from 'run-cache'; + +// Add logging middleware +await RunCache.use(async (value, context, next) => { + console.log(`[RunCache] ${context.operation.toUpperCase()} operation for key: ${context.key}`); + + try { + const result = await next(value); + console.log(`[RunCache] ${context.operation.toUpperCase()} completed for key: ${context.key}`); + return result; + } catch (error) { + console.error(`[RunCache] ${context.operation.toUpperCase()} failed for key: ${context.key}:`, error); + throw error; + } +}); +``` + +### Advanced Logging Middleware + +For more advanced logging with performance metrics: + +```typescript +await RunCache.use(async (value, context, next) => { + const start = performance.now(); + const operation = context.operation.toUpperCase(); + + console.log(`[RunCache] START ${operation} - Key: ${context.key}`); + + try { + const result = await next(value); + + const duration = performance.now() - start; + console.log( + `[RunCache] END ${operation} - Key: ${context.key}, Duration: ${duration.toFixed(2)}ms, ` + + `Result: ${result ? 'success' : 'empty'}` + ); + + return result; + } catch (error) { + const duration = performance.now() - start; + console.error( + `[RunCache] ERROR ${operation} - Key: ${context.key}, Duration: ${duration.toFixed(2)}ms, ` + + `Error: ${error.message}` + ); + + throw error; + } +}); +``` + +### Logging to External Services + +You can integrate with external logging services: + +```typescript +// Example with Winston logger +import winston from 'winston'; + +const logger = winston.createLogger({ + level: 'info', + format: winston.format.json(), + defaultMeta: { service: 'run-cache' }, + transports: [ + new winston.transports.File({ filename: 'error.log', level: 'error' }), + new winston.transports.File({ filename: 'combined.log' }) + ] +}); + +// Add winston logging middleware +await RunCache.use(async (value, context, next) => { + logger.info({ + message: 'Cache operation started', + operation: context.operation, + key: context.key + }); + + try { + const result = await next(value); + + logger.info({ + message: 'Cache operation completed', + operation: context.operation, + key: context.key, + success: !!result + }); + + return result; + } catch (error) { + logger.error({ + message: 'Cache operation failed', + operation: context.operation, + key: context.key, + error: error.message, + stack: error.stack + }); + + throw error; + } +}); +``` + +## Monitoring Cache Events + +The event system provides another way to debug and monitor cache operations. + +### Basic Event Monitoring + +```typescript +import { RunCache, EVENT } from 'run-cache'; + +// Monitor expiry events +await RunCache.onExpiry((event) => { + console.log(`[RunCache] Key expired: ${event.key}, TTL: ${event.ttl}ms`); +}); + +// Monitor refetch events +await RunCache.onRefetch((event) => { + console.log(`[RunCache] Key refreshed: ${event.key}`); +}); + +// Monitor refetch failures +await RunCache.onRefetchFailure((event) => { + console.error(`[RunCache] Refresh failed for key: ${event.key}`, event.error); +}); + +// Monitor tag invalidations +await RunCache.onTagInvalidation((event) => { + console.log(`[RunCache] Key invalidated by tag: ${event.key}, Tag: ${event.tag}`); +}); + +// Monitor dependency invalidations +await RunCache.onDependencyInvalidation((event) => { + console.log(`[RunCache] Key invalidated by dependency: ${event.key}, Dependency: ${event.dependencyKey}`); +}); +``` + +Event payloads contain `key`, `value` (the stored string), `ttl`, `createdAt` and `updatedAt`, plus `tag` or `dependencyKey` for invalidation events. Refetch failure events also have `error`, set to what the source function threw. A manual `refetch()` additionally rejects with a `SourceFnError` whose `cause` is that error. + +### Monitoring Specific Keys + +For debugging issues with specific keys: + +```typescript +// Monitor operations on a specific key +await RunCache.onKeyExpiry('important-data', (event) => { + console.log(`[RunCache] Important data expired at ${new Date().toISOString()}`); +}); + +await RunCache.onKeyRefetch('important-data', (event) => { + console.log(`[RunCache] Important data refreshed at ${new Date().toISOString()}`); +}); + +await RunCache.onKeyRefetchFailure('important-data', (event) => { + console.error(`[RunCache] Important data refresh failed: ${event.key}`); +}); +``` + +### Using Patterns for Grouped Monitoring + +You can use patterns to monitor groups of related keys: + +```typescript +// Monitor all user-related expirations +await RunCache.onKeyExpiry('user:*', (event) => { + console.log(`[RunCache] User data expired: ${event.key}`); +}); + +// Monitor all API-related refresh failures +await RunCache.onKeyRefetchFailure('api:*', (event) => { + console.error(`[RunCache] API data refresh failed: ${event.key}`, event.error); +}); +``` + +## Debugging Common Issues + +### Diagnosing Cache Misses + +Middleware only runs for `get` on a hit, so it cannot see misses. `debug: true` logs every read with the reason: + +```typescript +await RunCache.configure({ debug: true }); + +await RunCache.get('user:1'); +// RunCache [2026-01-01T00:00:00.000Z] [DEBUG]: Cache miss for key: user:1 (never set, deleted or evicted) +// RunCache [...] [DEBUG]: Cache expired for key: user:1 (TTL passed) +// RunCache [...] [DEBUG]: Removing expired entry for key: user:1 +``` + +To count or log misses in your own code, wrap `get()`: + +```typescript +async function getWithMissLog(key: string) { + const value = await RunCache.get(key); + if (value === undefined) { + console.log(`[RunCache] Cache miss for key: ${key}`); + } + return value; +} +``` + +Common causes of unexpected misses: + +- The TTL is in seconds instead of milliseconds. +- `maxEntries` is set and the entry was evicted. +- The entry was removed by `invalidateByTag()`, or because an entry it depends on was updated, refetched, deleted, evicted or expired; listen with `onTagInvalidation`/`onDependencyInvalidation` to confirm. +- The process restarted and the entry was not saved before exit (see [Persistent Storage](../advanced/persistent-storage.md)). + +### Debugging TTL Issues + +If entries are expiring too soon or not expiring when expected: + +```typescript +// Add TTL debugging middleware +await RunCache.use(async (value, context, next) => { + if (context.operation === 'set' && context.ttl) { + console.log( + `[RunCache] Setting key ${context.key} with TTL ${context.ttl}ms, ` + + `will expire at ${new Date(Date.now() + context.ttl).toISOString()}` + ); + } + return next(value); +}); + +// Monitor all expiry events +await RunCache.onExpiry((event) => { + console.log( + `[RunCache] Key ${event.key} expired. ` + + `TTL was ${event.ttl}ms. ` + + `Last updated at ${new Date(event.updatedAt).toISOString()}, ` + + `expired at ${new Date(event.updatedAt + event.ttl).toISOString()}` + ); +}); +``` + +### Debugging Automatic Refetching + +`set()` throws when `autoRefetch` is given without a `ttl`. Without a `sourceFn`, `autoRefetch` has no effect and the entry is simply removed when it expires. Entries restored from a storage adapter have no `sourceFn`, so they are not refetched until you `set()` them again with one. + +Auto-refetch runs when the TTL timer fires, or when a read finds the entry expired first; in the second case the read returns the stale value while the refetch runs. + +```typescript +// Monitor refetch events and failures +await RunCache.onRefetch((event) => { + console.log(`[RunCache] Auto-refetch successful for key: ${event.key}`); +}); + +await RunCache.onRefetchFailure((event) => { + console.error(`[RunCache] Auto-refetch failed for key: ${event.key}:`, event.error); +}); +``` + +### Debugging Source Functions + +To debug issues with source functions: + +```typescript +// Create a debuggable source function wrapper +function debugSourceFn(key, fn) { + return async () => { + console.log(`[RunCache] Executing source function for key: ${key}`); + const start = performance.now(); + + try { + const result = await fn(); + const duration = performance.now() - start; + console.log( + `[RunCache] Source function for key ${key} completed in ${duration.toFixed(2)}ms. ` + + `Result: ${typeof result}` + ); + return result; + } catch (error) { + const duration = performance.now() - start; + console.error( + `[RunCache] Source function for key ${key} failed after ${duration.toFixed(2)}ms:`, + error + ); + throw error; + } + }; +} + +// Usage +await RunCache.set({ + key: 'data', + sourceFn: debugSourceFn('data', async () => { + const response = await fetch('https://api.example.com/data'); + return response.json(); + }), + ttl: 60000, + autoRefetch: true +}); +``` + +### Debugging Storage Adapters + +With `debug: true`, RunCache logs each save (with its size) and load, and any adapter errors. `saveToStorage()` and `loadFromStorage()` return `false` instead of throwing when the adapter fails. For more detail, wrap the adapter: + +```typescript +import { RunCache, FilesystemAdapter, type StorageAdapter } from 'run-cache'; + +function withLogging(adapter: StorageAdapter): StorageAdapter { + return { + async save(data) { + console.log(`[RunCache] Saving ${data.length} bytes to storage`); + await adapter.save(data); + }, + async load() { + const data = await adapter.load(); + console.log(`[RunCache] Loaded ${data ? data.length : 0} bytes from storage`); + return data; + }, + clear: () => adapter.clear() + }; +} + +await RunCache.configure({ + storageAdapter: withLogging(new FilesystemAdapter({ storageKey: 'my-app-cache' })) +}); +``` + +## Implementing Comprehensive Logging + +For production environments, you might want to implement comprehensive logging: + +### Creating a Logger Service + +```typescript +// logger.js +class CacheLogger { + constructor(options = {}) { + this.level = options.level || 'info'; + this.transports = options.transports || [console]; + this.levels = { + error: 0, + warn: 1, + info: 2, + debug: 3, + trace: 4 + }; + } + + shouldLog(level) { + return this.levels[level] <= this.levels[this.level]; + } + + log(level, message, data = {}) { + if (!this.shouldLog(level)) return; + + const timestamp = new Date().toISOString(); + const logObj = { + timestamp, + level, + message, + ...data + }; + + for (const transport of this.transports) { + if (typeof transport[level] === 'function') { + transport[level](message, logObj); + } else { + transport.log(message, logObj); + } + } + } + + error(message, data) { this.log('error', message, data); } + warn(message, data) { this.log('warn', message, data); } + info(message, data) { this.log('info', message, data); } + debug(message, data) { this.log('debug', message, data); } + trace(message, data) { this.log('trace', message, data); } +} + +export const logger = new CacheLogger({ level: process.env.LOG_LEVEL || 'info' }); +``` + +### Integrating with RunCache + +```typescript +// cache-setup.js +import { RunCache } from 'run-cache'; +import { logger } from './logger'; + +export async function setupCacheLogging() { + // Add logging middleware (runs on set, refetch and get hits) + await RunCache.use(async (value, context, next) => { + logger.debug(`Operation ${context.operation} started for key: ${context.key}`, { + operation: context.operation, + key: context.key + }); + + try { + const result = await next(value); + logger.debug(`Operation ${context.operation} completed for key: ${context.key}`, { + operation: context.operation, + key: context.key, + success: !!result + }); + return result; + } catch (error) { + logger.error(`Operation ${context.operation} failed for key: ${context.key}`, { + operation: context.operation, + key: context.key, + error: error.message, + stack: error.stack + }); + throw error; + } + }); + + // Set up event logging + await RunCache.onExpiry((event) => { + logger.debug(`Key expired: ${event.key}`, { + event: 'expire', + key: event.key, + ttl: event.ttl, + updatedAt: event.updatedAt + }); + }); + + await RunCache.onRefetch((event) => { + logger.debug(`Key refreshed: ${event.key}`, { + event: 'refetch', + key: event.key + }); + }); + + await RunCache.onRefetchFailure((event) => { + logger.error(`Refresh failed for key: ${event.key}`, { + event: 'refetch_failure', + key: event.key, + error: event.error + }); + }); + + await RunCache.onTagInvalidation((event) => { + logger.debug(`Key invalidated by tag: ${event.key}`, { + event: 'tag_invalidation', + key: event.key, + tag: event.tag + }); + }); + + await RunCache.onDependencyInvalidation((event) => { + logger.debug(`Key invalidated by dependency: ${event.key}`, { + event: 'dependency_invalidation', + key: event.key, + dependencyKey: event.dependencyKey + }); + }); +} +``` + +## Debugging in Different Environments + +### Browser Debugging + +For browser environments: + +```typescript +// Enable detailed console output +await RunCache.configure({ debug: true }); + +// Use browser dev tools +// 1. Set breakpoints in source functions +// 2. Monitor network requests for fetch operations +// 3. Use console.trace() to see call stacks +// 4. Watch for errors in the console + +// Add a global debug function +window.__debugRunCache = async function(pattern = '*') { + return { + entries: await RunCache.get(pattern), + config: await RunCache.getConfig(), + // Add any other debug info you need + }; +}; + +// In browser console, you can now run: +// > await window.__debugRunCache('user:*') +``` + +### Node.js Debugging + +For Node.js environments: + +```typescript +// Enable inspector +// Start Node with: node --inspect your-script.js + +// Add debug endpoints to Express app +app.get('/debug/cache', async (req, res) => { + if (process.env.NODE_ENV === 'production') { + return res.status(403).send('Not available in production'); + } + + const pattern = req.query.pattern || '*'; + const entries = await RunCache.get(pattern); + const config = await RunCache.getConfig(); + + res.json({ + pattern, + entries, + config, + memory: process.memoryUsage() + }); +}); +``` + +## Debugging Tools and Utilities + +### Cache Inspector Utility + +RunCache has no public API for listing keys or reading entry metadata. `get()` with a pattern returns the matching values (not their keys), and `has()` tells you whether a pattern matches anything: + +```typescript +// cache-inspector.js +export class CacheInspector { + static async getValues(pattern = '*') { + const values = await RunCache.get(pattern); + if (values === undefined) return []; + // Only a wildcard query returns a list of results; an exact key that stores + // an array is still one value + const isWildcard = pattern.includes('*'); + return isWildcard && Array.isArray(values) ? values : [values]; + } + + static async countMatching(pattern = '*') { + return (await this.getValues(pattern)).length; + } + + static async approximateSize(pattern = '*') { + const values = await this.getValues(pattern); + return values.reduce((size, value) => size + JSON.stringify(value).length, 0); + } +} +``` + +If you need key-level detail, keep your own registry of the keys you set, or use the `debug` log output. + +### Performance Monitoring Utility + +Middleware sees `set`, `refetch` and `get` hits, so a miss count has to come from wrapping `get()`: + +```typescript +// cache-performance.js +export class CachePerformanceMonitor { + constructor() { + this.resetMetrics(); + } + + async start() { + // Timing for operations that reach the middleware chain + await RunCache.use(async (value, context, next) => { + const start = performance.now(); + const result = await next(value); + const op = this.metrics.operations[context.operation]; + if (op) { + op.count++; + op.totalTime += performance.now() - start; + } + return result; + }); + + // Track events + await RunCache.onExpiry(() => { this.metrics.events.expire++; }); + await RunCache.onRefetch(() => { this.metrics.events.refetch++; }); + await RunCache.onRefetchFailure(() => { this.metrics.events.refetch_failure++; }); + await RunCache.onTagInvalidation(() => { this.metrics.events.tag_invalidation++; }); + await RunCache.onDependencyInvalidation(() => { this.metrics.events.dependency_invalidation++; }); + } + + // Use this in place of RunCache.get() to count hits and misses + async get(key) { + const value = await RunCache.get(key); + if (value === undefined) this.metrics.misses++; + else this.metrics.hits++; + return value; + } + + getMetrics() { + const { hits, misses, operations, events } = this.metrics; + return { + hits, + misses, + hitRatio: hits + misses ? hits / (hits + misses) : 0, + events: { ...events }, + operations: Object.fromEntries( + Object.entries(operations).map(([name, op]) => [ + name, + { ...op, avgTime: op.count ? op.totalTime / op.count : 0 } + ]) + ) + }; + } + + resetMetrics() { + this.metrics = { + hits: 0, + misses: 0, + operations: { + get: { count: 0, totalTime: 0 }, + set: { count: 0, totalTime: 0 }, + refetch: { count: 0, totalTime: 0 } + }, + events: { + expire: 0, + refetch: 0, + refetch_failure: 0, + tag_invalidation: 0, + dependency_invalidation: 0 + } + }; + } +} + +// Usage +const monitor = new CachePerformanceMonitor(); +await monitor.start(); +``` + +## Best Practices for Debugging + +1. **Start with debug Mode**: Enable debug mode as your first step when debugging. + +2. **Isolate the Problem**: Focus on specific keys or operations rather than the entire cache. + +3. **Use Pattern Matching Carefully**: Be specific with patterns when debugging to avoid processing too many entries. + +4. **Check for Expiration Issues**: TTL-related problems are common; verify expiration timing. + +5. **Monitor Memory Usage**: Track memory consumption to identify potential leaks or size issues. + +6. **Test in Isolation**: Create minimal test cases that reproduce the issue. + +7. **Verify Source Functions**: Ensure source functions return properly formatted data and handle errors. + +8. **Check Middleware Order**: The order of middleware can affect behavior. + +9. **Look for Race Conditions**: Concurrent operations can cause unexpected behavior. + +10. **Clean Up Debugging Tools**: Remove or disable debug logging and debugging tools in production to avoid performance impacts. + +## Next Steps + +After mastering debugging and logging in RunCache, explore these related topics: + +- [Performance Optimization](./performance.md) - Learn how to optimize cache performance +- [Resource Management](../advanced/resource-management.md) - Understand memory management and cleanup +- [Best Practices](./best-practices.md) - Explore general best practices for RunCache +- [Middleware](../advanced/middleware.md) - Learn more about middleware capabilities \ No newline at end of file diff --git a/gitbook-versions/v1.7/guides/migration-guide.md b/gitbook-versions/v1.7/guides/migration-guide.md new file mode 100644 index 0000000..39ea861 --- /dev/null +++ b/gitbook-versions/v1.7/guides/migration-guide.md @@ -0,0 +1,476 @@ +# Migration Guide + +This guide helps you upgrade from string-only RunCache usage to the new typed caching features. The migration is designed to be gradual and non-breaking - your existing code will continue to work unchanged. + +## Overview + +RunCache now supports any serializable JavaScript type while maintaining 100% backward compatibility with existing string-based code. You can migrate incrementally, updating different parts of your application at your own pace. + +## Migration Strategy + +### Phase 1: No Changes Required + +Your existing code continues to work without any modifications: + + +```typescript +// This code works exactly as before +await RunCache.set({ key: 'user:name', value: 'John Doe' }); +const name = await RunCache.get('user:name'); // string | undefined + +// JSON stringified objects also work as before +const userData = { id: 1, name: 'John' }; +await RunCache.set({ key: 'user:1', value: JSON.stringify(userData) }); +const userJson = await RunCache.get('user:1'); // string | undefined +const user = userJson ? JSON.parse(userJson) : null; +``` + +### Phase 2: Gradual Type Adoption + +Start using types for new code while keeping existing code unchanged: + +```typescript +// New typed code +interface User { + id: number; + name: string; + email: string; +} + +const user: User = { id: 1, name: 'John', email: 'john@example.com' }; +await RunCache.set({ key: 'typed:user:1', value: user }); + +// Existing string-based code continues to work +await RunCache.set({ key: 'legacy:user:name', value: 'John Doe' }); +``` + +### Phase 3: Convert Existing Code + +Gradually convert existing string-based code to use types: + + +```typescript +// Before: Manual JSON stringification +const userData = { id: 1, name: 'John', email: 'john@example.com' }; +await RunCache.set({ + key: 'user:1', + value: JSON.stringify(userData) +}); +const userJson = await RunCache.get('user:1'); +const user = userJson ? JSON.parse(userJson) : null; + +// After: Automatic serialization with types +interface User { + id: number; + name: string; + email: string; +} + +const userData: User = { id: 1, name: 'John', email: 'john@example.com' }; +await RunCache.set({ key: 'user:1', value: userData }); +const user = await RunCache.get('user:1'); // User | undefined +``` + +## Common Migration Patterns + +### 1. Simple Object Caching + +**Before:** + +```typescript +const config = { theme: 'dark', language: 'en' }; +await RunCache.set({ key: 'config', value: JSON.stringify(config) }); + +const configJson = await RunCache.get('config'); +const parsedConfig = configJson ? JSON.parse(configJson) : null; +``` + +**After:** +```typescript +interface Config { + theme: 'light' | 'dark'; + language: string; +} + +const config: Config = { theme: 'dark', language: 'en' }; +await RunCache.set({ key: 'config', value: config }); + +const parsedConfig = await RunCache.get('config'); // Config | undefined +``` + +### 2. API Response Caching + +**Before:** + +```typescript +async function fetchUserData(userId: number) { + const cacheKey = `user:${userId}`; + + // Check cache + const cached = await RunCache.get(cacheKey); + if (cached) { + return JSON.parse(cached); + } + + // Fetch from API + const response = await fetch(`/api/users/${userId}`); + const userData = await response.json(); + + // Cache the stringified result + await RunCache.set({ + key: cacheKey, + value: JSON.stringify(userData), + ttl: 300000 + }); + + return userData; +} +``` + +**After:** +```typescript +interface User { + id: number; + name: string; + email: string; + profile: { + avatar?: string; + bio?: string; + }; +} + +async function fetchUserData(userId: number): Promise { + const cacheKey = `user:${userId}`; + + // Check cache with type safety + const cached = await RunCache.get(cacheKey); + if (cached) { + return cached; // No parsing needed, already typed + } + + // Fetch from API + const response = await fetch(`/api/users/${userId}`); + const userData: User = await response.json(); + + // Cache with automatic serialization + await RunCache.set({ + key: cacheKey, + value: userData, + ttl: 300000 + }); + + return userData; +} +``` + +### 3. Source Functions with Types + +**Before:** + +```typescript +await RunCache.set({ + key: 'weather:current', + sourceFn: async () => { + const response = await fetch('/api/weather'); + const data = await response.json(); + return JSON.stringify(data); // Manual stringification + }, + ttl: 300000 +}); + +const weatherJson = await RunCache.get('weather:current'); +const weather = weatherJson ? JSON.parse(weatherJson) : null; +``` + +**After:** +```typescript +interface WeatherData { + temperature: number; + humidity: number; + condition: string; + location: string; +} + +await RunCache.set({ + key: 'weather:current', + sourceFn: async (): Promise => { + const response = await fetch('/api/weather'); + return response.json(); // Return typed object directly + }, + ttl: 300000 +}); + +const weather = await RunCache.get('weather:current'); // WeatherData | undefined +``` + +### 4. Array and Collection Caching + +**Before:** + +```typescript +const products = [ + { id: 1, name: 'Laptop', price: 999 }, + { id: 2, name: 'Mouse', price: 29 } +]; + +await RunCache.set({ + key: 'products:featured', + value: JSON.stringify(products) +}); + +const productsJson = await RunCache.get('products:featured'); +const productList = productsJson ? JSON.parse(productsJson) : []; +``` + +**After:** +```typescript +interface Product { + id: number; + name: string; + price: number; +} + +const products: Product[] = [ + { id: 1, name: 'Laptop', price: 999 }, + { id: 2, name: 'Mouse', price: 29 } +]; + +await RunCache.set({ + key: 'products:featured', + value: products +}); + +const productList = await RunCache.get('products:featured'); // Product[] | undefined +``` + +## Benefits of Migration + +### Type Safety +- Compile-time error checking +- IntelliSense and auto-completion +- Reduced runtime errors + +### Developer Experience +- No manual JSON.stringify/parse +- Clear interface definitions +- Better code documentation + +### Maintainability +- Easier refactoring +- Self-documenting code +- Consistent data structures + +## Migration Tools and Utilities + +### Type Detection Utilities + +You can use these utilities to help with migration: + +```typescript +// Migration helper for gradual conversion: entries stored with +// JSON.stringify() come back as strings, so parse and re-store them +async function migrateToTyped(key: string): Promise { + const value = await RunCache.get(key); + if (typeof value === 'string') { + try { + // Try to parse as JSON + const parsed = JSON.parse(value); + // Re-cache as typed value + await RunCache.set({ key, value: parsed }); + return parsed; + } catch { + // It's a plain string, leave as is + return undefined; + } + } + return value as T; +} +``` + +### Batch Migration + +For large-scale migrations, you can use pattern matching: + +```typescript +async function migrateUserCache() { + // Get all user cache keys + const userValues = await RunCache.get('user:*'); + + if (Array.isArray(userValues)) { + for (const value of userValues) { + if (typeof value === 'string') { + try { + const userData = JSON.parse(value); + const key = `user:${userData.id}`; + + // Migrate to typed cache + await RunCache.delete(key); // Remove old entry + await RunCache.set({ key, value: userData }); + } catch (error) { + console.warn(`Failed to migrate user cache: ${error}`); + } + } + } + } +} +``` + +## Mixed Usage Patterns + +You can safely mix string and typed caching in the same application: + +```typescript +// Legacy string caching +await RunCache.set({ key: 'legacy:config', value: 'production' }); + +// Modern typed caching +interface AppSettings { + theme: string; + version: string; +} + +await RunCache.set({ + key: 'modern:settings', + value: { theme: 'dark', version: '2.0.0' } +}); + +// Both work together +const legacyConfig = await RunCache.get('legacy:config'); // string | undefined +const modernSettings = await RunCache.get('modern:settings'); // AppSettings | undefined +``` + +## Testing Migration + +When migrating, ensure your tests cover both legacy and new patterns: + +```typescript +describe('Migration Tests', () => { + it('should support legacy string caching', async () => { + await RunCache.set({ key: 'test:legacy', value: 'string value' }); + const result = await RunCache.get('test:legacy'); + expect(result).toBe('string value'); + }); + + it('should support new typed caching', async () => { + interface TestData { id: number; name: string; } + const data: TestData = { id: 1, name: 'test' }; + + await RunCache.set({ key: 'test:typed', value: data }); + const result = await RunCache.get('test:typed'); + + expect(result).toEqual(data); + expect(typeof result?.id).toBe('number'); + }); + + it('should handle mixed usage', async () => { + await RunCache.set({ key: 'test:string', value: 'legacy' }); + await RunCache.set({ key: 'test:number', value: 42 }); + + const stringResult = await RunCache.get('test:string'); + const numberResult = await RunCache.get('test:number'); + + expect(stringResult).toBe('legacy'); + expect(numberResult).toBe(42); + }); +}); +``` + +## Performance Considerations + +The migration to typed caching has minimal performance impact: + +- **Memory Usage**: Similar to string caching +- **Serialization**: Optimized for common types +- **CPU Overhead**: Less than 5% increase for complex objects +- **Network**: No impact on cache size + +## Common Pitfalls and Solutions + +### 1. Circular References + +**Problem:** +```typescript +const obj: any = { name: 'test' }; +obj.self = obj; // Circular reference + +await RunCache.set({ key: 'circular', value: obj }); // Will fail +``` + +**Solution:** +```typescript +// Use custom serialization or break circular references +const safeObj = { + name: obj.name, + // Don't include circular properties +}; +await RunCache.set({ key: 'safe', value: safeObj }); +``` + +### 2. Date Objects + +**Problem:** +```typescript +const data = { timestamp: new Date() }; +await RunCache.set({ key: 'date', value: data }); +const retrieved = await RunCache.get('date'); +// retrieved.timestamp is now a string, not Date +``` + +**Solution:** +```typescript +// Store dates as ISO strings and convert them back after reading +await RunCache.set({ key: 'date', value: { timestamp: new Date().toISOString() } }); + +const retrieved = (await RunCache.get('date')) as { timestamp: string } | undefined; +const timestamp = retrieved && new Date(retrieved.timestamp); +``` + +### 3. Function Properties + +Functions cannot be serialized and will be lost: + +**Problem:** +```typescript +const obj = { + data: 'value', + method: () => 'hello' // This will be lost +}; +``` + +**Solution:** +```typescript +// Only cache serializable data +const serializableObj = { + data: obj.data + // Don't include functions +}; +``` + +## Timeline Recommendations + +### Week 1: Setup and Planning +- Update to the latest RunCache version +- Identify areas for migration +- Define TypeScript interfaces + +### Week 2-3: New Features +- Use typed caching for all new features +- Create typed cache repositories +- Update documentation + +### Week 4-6: Gradual Migration +- Convert high-traffic cache operations +- Update API response caching +- Migrate critical data structures + +### Week 7+: Complete Migration +- Convert remaining string-based caching +- Remove manual JSON.stringify/parse +- Update tests and documentation + +## Next Steps + +- Read [Value Serialization](../advanced/serialization-adapters.md) for which types round-trip +- Learn about [Type Safety](../advanced/type-validation.md) for runtime checking +- Review [Best Practices](best-practices.md) for typed caching +- Check the [API Reference](../api/run-cache.md) for complete method signatures \ No newline at end of file diff --git a/gitbook-versions/v1.7/guides/performance.md b/gitbook-versions/v1.7/guides/performance.md new file mode 100644 index 0000000..7e25c2e --- /dev/null +++ b/gitbook-versions/v1.7/guides/performance.md @@ -0,0 +1,625 @@ +# Performance Optimization + +This guide provides techniques and strategies for optimizing the performance of RunCache in your applications. By following these recommendations, you can improve cache efficiency, reduce memory usage, and enhance the overall performance of your application. + +## Understanding RunCache Performance + +RunCache is designed to be lightweight and efficient, but like any caching solution, its performance can be affected by: + +- Size of the cache +- Complexity of keys and patterns +- Frequency of operations +- Middleware overhead +- Event listener quantity +- Source function performance +- Storage adapter efficiency + +## Optimizing Cache Configuration + +### Size Limits and Eviction Policies + +Configure appropriate size limits and eviction policies for your use case: + +```typescript +import { RunCache, EvictionPolicy } from 'run-cache'; + +// For most applications +await RunCache.configure({ + maxEntries: 1000, // Limit to 1000 entries + evictionPolicy: EvictionPolicy.LRU +}); +``` + +Choose the right eviction policy: +- **LRU (Least Recently Used)**: Best for most applications +- **LFU (Least Frequently Used)**: Better when access frequency is more important than recency +- **NONE**: Use only when other mechanisms control cache size (like TTL) + +### Determining Optimal Cache Size + +To determine the optimal cache size: + +1. Monitor memory usage with different cache sizes +2. Analyze cache hit/miss rates +3. Balance memory usage against performance gains + +```typescript +// Monitor memory usage periodically +setInterval(() => { + const memUsage = process.memoryUsage(); + const cacheSize = getCacheSize(); // Your function to get current entry count + console.log(`Memory: ${Math.round(memUsage.heapUsed / 1024 / 1024)} MB, Cache entries: ${cacheSize}`); +}, 60000); + +// Monitor hit rate with middleware +let hits = 0; +let misses = 0; + +await RunCache.use(async (value, context, next) => { + if (context.operation === 'get') { + const result = await next(value); + if (result) { + hits++; + } else { + misses++; + } + return result; + } + return next(value); +}); + +// Log hit rate periodically +setInterval(() => { + const hitRate = hits / (hits + misses || 1); + console.log(`Cache hit rate: ${(hitRate * 100).toFixed(2)}%`); + hits = 0; + misses = 0; +}, 60000); +``` + +## Optimizing Cache Keys + +### Key Design for Performance + +Key design significantly impacts performance: + +```typescript +// Less efficient - complex keys +await RunCache.set({ key: `user:${userId}:preferences:theme:color:mode:${mode}:variant:${variant}`, value: '...' }); + +// More efficient - simpler keys with structured data +await RunCache.set({ + key: `user:${userId}:theme-settings`, + value: { mode, variant, color } +}); +``` + +### Key Length + +Shorter keys use less memory and are faster to compare: + +```typescript +// Less efficient - long keys +await RunCache.set({ key: 'very-long-namespace:user-preferences:for-user-with-id:12345:theme-settings', value: '...' }); + +// More efficient - shorter keys +await RunCache.set({ key: 'u:12345:prefs', value: '...' }); +``` + +## Optimizing Source Functions + +### Minimize Processing + +Keep source functions focused and efficient: + +```typescript +// Less efficient - does too much processing +await RunCache.set({ + key: 'data', + sourceFn: async () => { + const rawData = await fetchData(); + const transformed = complexTransformation(rawData); + const filtered = filterData(transformed); + const sorted = sortData(filtered); + return sorted; + } +}); + +// More efficient - only essential processing +await RunCache.set({ + key: 'data', + sourceFn: async () => { + const data = await fetchData(); + return data; + } +}); + +// Process data when needed +const processData = (data) => { + // Do processing only when actually needed + return sortData(filterData(complexTransformation(data))); +}; +``` + +### Use Memoization + +For expensive source functions, consider memoization: + +```typescript +// Create a memoized source function +function createMemoizedSourceFn(fn, maxAge = 60000) { + let cachedResult = null; + let cachedAt = 0; + + return async () => { + const now = Date.now(); + if (!cachedResult || now - cachedAt > maxAge) { + cachedResult = await fn(); + cachedAt = now; + } + return cachedResult; + }; +} + +// Usage +const expensiveDataFetch = createMemoizedSourceFn(async () => { + return fetchExpensiveData(); +}); + +await RunCache.set({ + key: 'expensive-data', + sourceFn: expensiveDataFetch +}); +``` + +## Optimizing Pattern Matching + +### Be Specific with Patterns + +More specific patterns are faster to process: + +```typescript +// Less efficient - very broad pattern +await RunCache.get('*'); + +// More efficient - more specific pattern +await RunCache.get('user:*'); + +// Most efficient - highly specific pattern +await RunCache.get('user:1:*'); +``` + +### Limit Pattern Usage + +Use patterns only when necessary: + +```typescript +// Less efficient - always using patterns +await RunCache.get('user:*'); // Even when you know the exact key + +// More efficient - direct key access when possible +await RunCache.get('user:1'); // Use direct key when known +``` + +## Batch Operations + +### Use Promise.all for Batch Operations + +Process multiple operations concurrently: + +```typescript +// Less efficient - sequential operations +for (const id of userIds) { + await RunCache.set({ key: `user:${id}`, value: userData[id] }); +} + +// More efficient - parallel operations +await Promise.all( + userIds.map(id => RunCache.set({ key: `user:${id}`, value: userData[id] })) +); +``` + +### Implement Custom Batch Methods + +For frequent batch operations, create helper functions: + +```typescript +// Batch get helper +async function batchGet(keys) { + return Promise.all(keys.map(key => RunCache.get(key))); +} + +// Batch set helper +async function batchSet(entries) { + return Promise.all( + entries.map(entry => RunCache.set(entry)) + ); +} + +// Usage +const userIds = ['1', '2', '3']; +const userKeys = userIds.map(id => `user:${id}`); + +// Batch get +const userValues = await batchGet(userKeys); + +// Batch set +const entries = userIds.map(id => ({ + key: `user:${id}`, + value: { name: `User ${id}` } +})); +await batchSet(entries); +``` + +## Optimizing Middleware + +### Limit Middleware Complexity + +Keep middleware functions simple and focused: + +```typescript +// Less efficient - complex middleware +await RunCache.use(async (value, context, next) => { + console.log(`Start ${context.operation} for ${context.key}`); + const start = Date.now(); + try { + const complexMetadata = await fetchAdditionalData(); + const result = await next(value); + if (result) { + await processResult(result); + } + const end = Date.now(); + console.log(`End ${context.operation} for ${context.key}, took ${end - start}ms`); + return result; + } catch (e) { + console.error(e); + const end = Date.now(); + console.log(`Failed ${context.operation} for ${context.key}, took ${end - start}ms`); + throw e; + } +}); + +// More efficient - simpler middleware +await RunCache.use(async (value, context, next) => { + const start = Date.now(); + const result = await next(value); + const duration = Date.now() - start; + + if (duration > 100) { // Only log slow operations + console.log(`Slow operation: ${context.operation} for ${context.key}, took ${duration}ms`); + } + + return result; +}); +``` + +### Optimize Middleware Order + +Order middleware for optimal performance: + +```typescript +// Less efficient - expensive middleware runs first +await RunCache.use(expensiveMiddleware); // Runs for all operations +await RunCache.use(filterMiddleware); // Could have filtered out some operations + +// More efficient - filtering middleware runs first +await RunCache.use(filterMiddleware); // Filters out operations +await RunCache.use(expensiveMiddleware); // Only runs for filtered operations +``` + +## Optimizing Event Listeners + +### Limit Event Listeners + +Use specific event listeners rather than global ones: + +```typescript +// Less efficient - global listener for all events +await RunCache.onExpiry((event) => { + // Process all expiry events, even for keys we don't care about + console.log(`Key expired: ${event.key}`); +}); + +// More efficient - specific listener +await RunCache.onKeyExpiry('important-data', (event) => { + // Only process events for 'important-data' + console.log('Important data expired'); +}); +``` + +### Use Pattern-Based Listeners Wisely + +Be specific with event listener patterns: + +```typescript +// Less efficient - very broad pattern +await RunCache.onKeyExpiry('*', (event) => { + // Triggered for ALL expiry events +}); + +// More efficient - more specific pattern +await RunCache.onKeyExpiry('user:*', (event) => { + // Only triggered for user-related expirations +}); +``` + +## Memory Optimization + +### Value Size Optimization + +Minimize the size of cached values: + +```typescript +// Less efficient - storing large objects +await RunCache.set({ + key: 'large-report', + value: { + fullData: largeDataSet, // Unnecessary complete dataset + processedResults: results, + generatedAt: new Date().toISOString(), + generatedBy: 'system', + version: '1.0', + // ... many more fields + } +}); + +// More efficient - store only essential data +await RunCache.set({ + key: 'report-summary', + value: { + highlights: summaryResults, + timestamp: Date.now() + } +}); + +// Store additional data separately if needed +await RunCache.set({ + key: 'report-details', + value: detailedResults, + ttl: 3600000 // Shorter TTL for detailed data +}); +``` + +### TTL Strategies + +Use appropriate TTL values to prevent memory bloat: + +```typescript +// Strategy: Use shorter TTL for larger data +await RunCache.set({ + key: 'small-config', + value: smallConfig, + ttl: 86400000 // 24 hours for small data +}); + +await RunCache.set({ + key: 'large-dataset', + value: largeDataset, + ttl: 3600000 // 1 hour for large data +}); + +// Strategy: Tiered caching with different TTLs +await RunCache.set({ + key: 'user:summary', + value: userSummary, + ttl: 86400000 // 24 hours for summary +}); + +await RunCache.set({ + key: 'user:details', + value: userDetails, + ttl: 3600000 // 1 hour for details +}); + +await RunCache.set({ + key: 'user:activity', + value: userActivity, + ttl: 300000 // 5 minutes for activity +}); +``` + +## Storage Adapter Optimization + +### Choose the Right Adapter + +Select the most appropriate storage adapter for your needs: + +```typescript +// For browser environments with small data +await RunCache.configure({ + storageAdapter: new LocalStorageAdapter() +}); + +// For browser environments with larger data +await RunCache.configure({ + storageAdapter: new IndexedDBAdapter() +}); + +// For Node.js environments +await RunCache.configure({ + storageAdapter: new FilesystemAdapter() +}); +``` + +### Optimize Save Frequency + +Balance persistence needs with performance: + +```typescript +// Too frequent - performance impact +await RunCache.setupAutoSave(1000); // Save every second + +// More balanced +await RunCache.setupAutoSave(300000); // Save every 5 minutes + +// For mostly read-only data +await RunCache.setupAutoSave(3600000); // Save every hour +``` + +## Advanced Performance Techniques + +### Implement Custom Metrics Tracking + +Track performance metrics to identify bottlenecks: + +```typescript +// Add performance tracking +const metrics = { + operations: { + get: { count: 0, totalTime: 0 }, + set: { count: 0, totalTime: 0 }, + delete: { count: 0, totalTime: 0 } + }, + hits: 0, + misses: 0 +}; + +// Performance middleware +await RunCache.use(async (value, context, next) => { + const start = performance.now(); + const result = await next(value); + const duration = performance.now() - start; + + // Track operation time + if (metrics.operations[context.operation]) { + metrics.operations[context.operation].count++; + metrics.operations[context.operation].totalTime += duration; + } + + // Track hits/misses + if (context.operation === 'get') { + if (result) metrics.hits++; + else metrics.misses++; + } + + return result; +}); + +// Report metrics periodically +setInterval(() => { + const hitRatio = metrics.hits / (metrics.hits + metrics.misses || 1); + + console.log(`Cache Performance Metrics:`); + console.log(`Hit ratio: ${(hitRatio * 100).toFixed(2)}%`); + + for (const [op, data] of Object.entries(metrics.operations)) { + if (data.count > 0) { + const avgTime = data.totalTime / data.count; + console.log(`${op}: ${data.count} operations, avg ${avgTime.toFixed(2)}ms`); + } + } + + // Reset metrics + for (const op in metrics.operations) { + metrics.operations[op] = { count: 0, totalTime: 0 }; + } + metrics.hits = 0; + metrics.misses = 0; +}, 60000); +``` + +### Implement Sharding for Large Caches + +For very large caches, implement a sharding strategy: + +```typescript +// Create a simple sharded cache manager +class ShardedCache { + private shards: Map[] = []; + private shardCount: number; + + constructor(shardCount = 16) { + this.shardCount = shardCount; + + // Initialize shards + for (let i = 0; i < shardCount; i++) { + this.shards.push(new Map()); + } + } + + private getShardIndex(key: string): number { + // Simple hash function for shard selection + let hash = 0; + for (let i = 0; i < key.length; i++) { + hash = ((hash << 5) - hash) + key.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + return Math.abs(hash) % this.shardCount; + } + + async get(key: string): Promise { + const shardIndex = this.getShardIndex(key); + // Implement actual logic to get from the appropriate RunCache instance + // This is a simplified example + return "implementation"; + } + + async set(options: any): Promise { + const shardIndex = this.getShardIndex(options.key); + // Implement actual logic to set in the appropriate RunCache instance + } + + // Additional methods as needed +} + +// Usage +const shardedCache = new ShardedCache(32); // 32 shards +await shardedCache.set({ key: 'user:1', value: 'data' }); +const value = await shardedCache.get('user:1'); +``` + +## Measuring Performance + +### Benchmarking Cache Operations + +Create benchmarks to test different cache configurations: + +```typescript +async function benchmarkCache() { + console.log('Starting cache benchmark...'); + + // Prepare test data + const testData = Array.from({ length: 1000 }, (_, i) => ({ + key: `test:${i}`, + value: { id: i, data: `Test data ${i}` } + })); + + // Benchmark set operations + const setStart = performance.now(); + await Promise.all(testData.map(item => + RunCache.set({ key: item.key, value: item.value }) + )); + const setTime = performance.now() - setStart; + console.log(`Set 1000 items: ${setTime.toFixed(2)}ms (${(setTime / 1000).toFixed(2)}ms per item)`); + + // Benchmark get operations (existing keys) + const getStart = performance.now(); + await Promise.all(testData.map(item => RunCache.get(item.key))); + const getTime = performance.now() - getStart; + console.log(`Get 1000 existing items: ${getTime.toFixed(2)}ms (${(getTime / 1000).toFixed(2)}ms per item)`); + + // Benchmark pattern matching + const patternStart = performance.now(); + await RunCache.get('test:*'); + const patternTime = performance.now() - patternStart; + console.log(`Pattern match 1000 items: ${patternTime.toFixed(2)}ms`); + + // Benchmark delete operations + const deleteStart = performance.now(); + await Promise.all(testData.map(item => RunCache.delete(item.key))); + const deleteTime = performance.now() - deleteStart; + console.log(`Delete 1000 items: ${deleteTime.toFixed(2)}ms (${(deleteTime / 1000).toFixed(2)}ms per item)`); +} + +// Run benchmark +benchmarkCache(); +``` + +## Next Steps + +After implementing these performance optimizations, consider these next steps: + +- [Debugging and Logging](./debugging.md) - Learn how to diagnose performance issues +- [Resource Management](../advanced/resource-management.md) - Understand memory management and cleanup +- [Best Practices](./best-practices.md) - Explore general best practices for RunCache +- [Event System](../advanced/event-system.md) - Learn how to use events efficiently \ No newline at end of file diff --git a/gitbook-versions/v1.7/resources/contributing.md b/gitbook-versions/v1.7/resources/contributing.md new file mode 100644 index 0000000..b55d30c --- /dev/null +++ b/gitbook-versions/v1.7/resources/contributing.md @@ -0,0 +1,9 @@ +# Contributing to RunCache + +Contributions are welcome. The contributor guide lives in the repository, next to the code it describes: + +- [CONTRIBUTING.md](https://github.com/helloscoopa/run-cache/blob/main/CONTRIBUTING.md): setup, the checks a pull request must pass, and how to write docs and code samples +- [CHANGELOG.md](https://github.com/helloscoopa/run-cache/blob/main/CHANGELOG.md): what changed in each release, and what is coming next +- [Issues](https://github.com/helloscoopa/run-cache/issues): bug reports and feature proposals + +In short: open an issue before larger changes, add tests and a changelog entry with your change, and make sure `npm test`, `npm run lint`, `npm run build` and `npm run docs:check` pass. diff --git a/gitbook-versions/v1.7/resources/faq.md b/gitbook-versions/v1.7/resources/faq.md new file mode 100644 index 0000000..35116ce --- /dev/null +++ b/gitbook-versions/v1.7/resources/faq.md @@ -0,0 +1,433 @@ +# Frequently Asked Questions + +This document addresses common questions about RunCache and provides concise answers to help you understand and use the library more effectively. + +## General Questions + +### What is RunCache? + +RunCache is a lightweight, dependency-free runtime caching library for JavaScript and TypeScript applications. It allows you to cache values in memory with configurable time-to-live (TTL) settings and supports automatic value regeneration through source functions. + +### When should I use RunCache? + +RunCache is ideal for: +- Caching API responses to reduce network requests +- Storing computed values to improve performance +- Managing application state with expiration policies +- Implementing complex caching patterns with dependencies and tags +- Any scenario where you need a flexible in-memory cache with automatic invalidation + +### Is RunCache suitable for production use? + +Yes, RunCache is designed for production use with a focus on performance, reliability, and memory efficiency. It includes features like eviction policies, resource management, and comprehensive error handling. + +### Does RunCache work in both browser and Node.js environments? + +Yes, RunCache works in both browser and Node.js environments. It has no external dependencies and is designed to be platform-agnostic. + +## Technical Questions + +### How does RunCache compare to other caching libraries? + +RunCache differentiates itself with: +- Zero dependencies +- Comprehensive event system +- Dependency tracking between cache entries +- Tag-based invalidation +- Advanced pattern matching +- TypeScript support +- Automatic refetching capabilities +- Persistent storage options + +### Does RunCache support server-side rendering (SSR)? + +Yes, RunCache works with server-side rendering. For optimal use in SSR environments: +1. Use separate cache instances for each request +2. Configure appropriate TTL values +3. Clear sensitive data before sending responses +4. Consider using the `shutdown()` method when a request completes + +### How does automatic refetching work? + +When you set a cache entry with `autoRefetch: true`: +1. The cache entry is created with a normal TTL +2. When the TTL expires, the next `get()` call will: + - Return the stale value immediately + - Trigger a background refresh using the source function + - Update the cache with the fresh value when available +3. Subsequent calls will get the refreshed value + +This prevents cache stampedes and ensures your application remains responsive. + +### Is RunCache thread-safe? + +In Node.js, RunCache is designed to work within a single thread/process. If you're using multiple processes (like with PM2 or worker threads), each process will have its own separate cache instance. + +For multi-process scenarios, consider using: +- External shared caching (like Redis) +- The storage adapters feature to maintain some persistence + +### Does RunCache support distributed caching? + +RunCache is primarily designed for local in-memory caching. For distributed scenarios: +1. Use RunCache as a local cache layer in front of a distributed cache +2. Implement custom storage adapters that connect to distributed cache systems +3. Use the event system to coordinate cache invalidation across instances + +## Performance Questions + +### How much memory does RunCache use? + +RunCache's memory usage depends on: +- The number of cache entries +- The size of cached values +- Metadata associated with entries (TTL, tags, etc.) + +To control memory usage: +1. Configure an appropriate `maxEntries` limit +2. Set eviction policies (LRU or LFU) +3. Use appropriate TTL values +4. Optimize value serialization + +### Will RunCache cause memory leaks? + +RunCache is designed to prevent memory leaks by: +- Cleaning up expired entries +- Providing eviction policies to limit cache size +- Properly managing timers and event listeners +- Including a `shutdown()` method for complete cleanup + +For long-running applications, it's recommended to: +1. Configure appropriate TTL values +2. Set a maximum cache size +3. Monitor memory usage +4. Call `shutdown()` when the application terminates + +### How does the eviction policy impact performance? + +The eviction policy affects how entries are removed when the cache reaches its maximum size: + +- **LRU (Least Recently Used)**: Removes the entries that haven't been accessed for the longest time. This is fast and works well for most use cases. +- **LFU (Least Frequently Used)**: Removes the entries that have been accessed the least number of times. This has slightly more overhead but can be better for certain access patterns. +- **NONE**: No automatic eviction, which means you must manage cache size manually through TTL or explicit deletion. + +## Feature-Specific Questions + +### How do cache dependencies work? + +Dependencies establish relationships between cache entries: + +```typescript +// Set up dependencies +await RunCache.set({ key: 'user:1', value: '...' }); +await RunCache.set({ + key: 'user:1:dashboard', + value: '...', + dependencies: ['user:1'] +}); + +// When the primary entry changes +await RunCache.set({ key: 'user:1', value: 'new value' }); +// The dependent entry is automatically invalidated + +// Or invalidate the dependents explicitly, keeping 'user:1' itself +await RunCache.invalidateByDependency('user:1'); +``` + +When a cache entry is updated, refetched, deleted, evicted, invalidated by tag or expires, all entries that depend on it are also invalidated, creating a cascading effect through the dependency chain. Invalidated dependents are removed, not refetched. + +### How does tag-based invalidation differ from dependencies? + +- **Tags** are used to group related cache entries for batch invalidation. Multiple entries can have the same tag, and invalidating a tag affects all entries with that tag. +- **Dependencies** establish direct relationships between entries. When one entry changes, all dependent entries are invalidated. + +Use tags for broader grouping and dependencies for direct relationships. + +### Can I use RunCache with React/Vue/Angular? + +Yes, RunCache works well with all major frontend frameworks: + +**React Example:** +```typescript +import { useState, useEffect } from 'react'; +import { RunCache } from 'run-cache'; + +function UserProfile({ userId }) { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let active = true; + + async function loadUser() { + setLoading(true); + const cacheKey = `user:${userId}`; + + // Try to get from cache (objects come back parsed) + let userData = await RunCache.get(cacheKey); + + if (userData === undefined) { + // Cache miss, fetch from API + const response = await fetch(`/api/users/${userId}`); + userData = await response.json(); + + // Store in cache + await RunCache.set({ + key: cacheKey, + value: userData, + ttl: 300000 // 5 minutes + }); + } + + if (!active) return; // the effect was cleaned up while loading + setUser(userData); + setLoading(false); + } + + // subscribeToRefetch() is the shared-listener helper from the Events guide + // ("UI Updates" in advanced/event-system.md). Do not call clearEventListeners() here: + // it removes every refetch listener for the key, including one registered by a + // newer effect run or another component showing the same user. + const unsubscribe = subscribeToRefetch(`user:${userId}`, () => { + loadUser().catch(console.error); + }); + loadUser().catch(console.error); + + return () => { + active = false; + unsubscribe(); + }; + }, [userId]); + + if (loading) return
Loading...
; + return
{user.name}
; +} +``` + +### How do I implement cache prefetching/warming? + +```typescript +// Cache warming function +async function warmCache() { + console.log('Warming cache...'); + + // Check if data already exists in cache + const hasConfig = await RunCache.has('app:config'); + const hasGlobalData = await RunCache.has('app:global-data'); + + // Only fetch what's missing + if (!hasConfig) { + const config = await fetchAppConfig(); + await RunCache.set({ key: 'app:config', value: config }); + } + + if (!hasGlobalData) { + const globalData = await fetchGlobalData(); + await RunCache.set({ key: 'app:global-data', value: globalData }); + } + + console.log('Cache warming complete'); +} + +// Call on application startup +warmCache(); +``` + +### Can I encrypt cached data? + +Yes, using middleware: + +```typescript +import { RunCache } from 'run-cache'; +import { encrypt, decrypt } from './your-crypto-lib'; + +// Add encryption middleware +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + // Encrypt value before storing in cache + return next(encrypt(value)); + } else if (context.operation === 'get') { + // Decrypt value after retrieving from cache + const encrypted = await next(value); + return encrypted ? decrypt(encrypted) : undefined; + } + return next(value); +}); +``` + +## Troubleshooting + +### Why is my cache entry not being stored? + +Common issues include: +1. Not providing a required parameter (key or value/sourceFn) +2. Exception in source function +3. A value that cannot be serialized (values must be strings or JSON-serializable; `BigInt` and circular structures throw) +4. Exceeding maximum cache size with eviction policy + +Solution: +```typescript +// Enable debug logging +await RunCache.configure({ debug: true }); + +// Check for errors in source function +try { + await RunCache.set({ + key: 'data', + sourceFn: async () => { + const data = await fetchData(); + return data; // Return a string or a JSON-serializable value + } + }); +} catch (error) { + console.error('Error setting cache:', error); +} +``` + +### Why is my cache entry expiring too soon? + +Common causes: +1. TTL value in wrong units (seconds vs milliseconds) +2. Clock drift in distributed systems +3. Incorrect calculation of TTL value + +Solution: +```typescript +// Ensure TTL is in milliseconds +const ONE_HOUR_MS = 60 * 60 * 1000; // 3,600,000 ms + +await RunCache.set({ + key: 'data', + value: 'value', + ttl: ONE_HOUR_MS // Clearly in milliseconds +}); + +// Monitor expiration +await RunCache.onKeyExpiry('data', (event) => { + console.log(`Data expired at ${new Date().toISOString()}`); + console.log(`TTL was ${event.ttl}ms, set at ${new Date(event.updatedAt).toISOString()}`); +}); +``` + +### Why aren't my event listeners firing? + +Common issues: +1. Using incorrect event name +2. Listener registered after the event occurred +3. Pattern matching typo +4. Event listener was cleared + +Solution: +```typescript +import { RunCache, EVENT } from 'run-cache'; + +// Use the correct event type +await RunCache.onExpiry((event) => { + console.log(`Key expired: ${event.key}`); +}); + +// For specific key patterns, ensure correct syntax +await RunCache.onKeyExpiry('user:*', (event) => { + console.log(`User data expired: ${event.key}`); +}); + +// Keep reference to handler for manual removal +const handler = (event) => console.log(event); +await RunCache.onRefetch(handler); + +// Later, if needed: +await RunCache.clearEventListeners({ + event: EVENT.REFETCH, + handler: handler +}); +``` + +## Best Practices + +### What's the best way to structure cache keys? + +Follow these guidelines: +1. Use consistent naming conventions +2. Use hierarchical structures with delimiters +3. Include entity type and identifier +4. Avoid special characters that might conflict with pattern matching + +Recommended format: `entityType:identifier:attribute` + +Examples: +- `user:1234:profile` +- `product:xyz:details` +- `api:users:list:page=1` + +### How should I handle errors in source functions? + +Best practices: +1. Always include try/catch in source functions +2. Log errors with context +3. Return fallback values when appropriate +4. Register refetch failure listeners + +```typescript +// Good source function with error handling +await RunCache.set({ + key: 'api-data', + sourceFn: async () => { + try { + const response = await fetch('https://api.example.com/data'); + if (!response.ok) { + throw new Error(`API returned ${response.status}`); + } + return await response.text(); + } catch (error) { + console.error('Failed to fetch API data:', error); + throw error; // Rethrow to trigger refetch failure event + } + }, + ttl: 300000 +}); + +// Handle refetch failures +await RunCache.onKeyRefetchFailure('api-data', (event) => { + console.error('API data refresh failed:', event.error); + notifyAdmins('API data refresh failed'); +}); +``` + +### Should I use RunCache for session data? + +RunCache can be appropriate for session data with some considerations: +1. Set appropriate TTL values that align with session timeouts +2. Use tags to group session data for easy invalidation +3. Consider security implications of storing sensitive data +4. Use middleware for encryption if needed +5. Implement proper cleanup on logout + +```typescript +// Store session data +await RunCache.set({ + key: `session:${sessionId}:user`, + value: userData, + ttl: 30 * 60 * 1000, // 30 minutes + tags: [`session:${sessionId}`, 'user-sessions'] +}); + +// On logout, invalidate all session data +await RunCache.invalidateByTag(`session:${sessionId}`); +``` + +## More Help + +### Where can I get support? + +- GitHub Issues: [RunCache GitHub Repository](https://github.com/example/run-cache/issues) +- Documentation: [RunCache Documentation](https://example.github.io/run-cache) +- Community Discussions: [RunCache Discussions](https://github.com/example/run-cache/discussions) + +### How can I contribute to RunCache? + +We welcome contributions! Check our [Contributing Guide](./contributing.md) for details on: +- Setting up the development environment +- Coding standards +- Pull request process +- Feature request guidelines +- Bug reporting \ No newline at end of file diff --git a/gitbook-versions/v1.7/resources/license.md b/gitbook-versions/v1.7/resources/license.md new file mode 100644 index 0000000..3ed2910 --- /dev/null +++ b/gitbook-versions/v1.7/resources/license.md @@ -0,0 +1,80 @@ +# License Information + +RunCache is released under the MIT License, which is a permissive open source license that allows for maximum flexibility in using the library. + +## MIT License + +``` +MIT License + +Copyright (c) 2024 Dilshan Madushanka + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +## What This Means + +The MIT License allows you to: + +- **Use** RunCache in your commercial projects +- **Modify** the code to suit your needs +- **Distribute** your own version of the library +- **Include** RunCache in your own open source or proprietary projects + +The only requirement is that you include the original copyright notice and license text in any copy of the software/source. + +## No Warranty + +RunCache is provided "as is" without warranty of any kind. The authors or copyright holders cannot be held liable for any damages arising from the use of the library. + +## Dependencies + +RunCache has zero dependencies, which simplifies licensing considerations. You don't need to worry about complex license compatibility issues with other libraries. + +## Using RunCache in Your Projects + +When using RunCache in your projects, you should: + +1. Include a copy of the MIT License in your project (typically in a file named LICENSE or in your documentation) +2. Acknowledge the use of RunCache in your documentation or credits + +Example attribution text: + +``` +This project uses RunCache (https://github.com/example/run-cache), +licensed under the MIT License. +``` + +## Contributing to RunCache + +By contributing to RunCache, you agree that your contributions will be licensed under the project's MIT License. This is common for open source projects and ensures that the codebase maintains a consistent licensing model. + +## Questions + +If you have any questions about licensing or how you can use RunCache in your specific project, please: + +- Open a discussion in the GitHub repository +- Contact the project maintainers +- Consult with your legal team if necessary + +## License Updates + +The license terms may be updated in future versions of RunCache. Any changes to the license will be clearly communicated in the project's release notes and documentation. + +The canonical version of the license is always the one included in the repository's LICENSE file. \ No newline at end of file