diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4c1ac6a..0456686 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,6 +29,9 @@ jobs: - name: Test run: npm test -- --coverage --coverageReporters=text --coverageReporters=json-summary + - name: Check doc code samples + run: npm run docs:check + # Writes coverage.json (a shields.io endpoint) to the `badges` branch, which the # README coverage badge reads. Runs on main only, so pull requests never write. - name: Publish coverage badge diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..43ba257 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,102 @@ +# Changelog + +All notable changes to RunCache are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). + +Add an entry under **Unreleased** in the same pull request as the change. When a version is tagged, rename that section to the version and date, add a new empty `## [Unreleased]` section above it, and update the links at the bottom: point `[Unreleased]` at `compare/vX.Y.Z...HEAD` and add a `[X.Y.Z]` link comparing the previous tag with the new one. + +## [Unreleased] + +### Added +- Values of any JSON-serializable type can be cached; strings are stored as-is and other values are serialized on `set()` and parsed again by `get()`. `RunCache.createTypedCache()` returns a typed wrapper ([#39](https://github.com/helloscoopa/run-cache/pull/39), [#67](https://github.com/helloscoopa/run-cache/pull/67)). +- `RunCacheError`, `SourceFnError` and `MiddlewareError` are exported; they keep the original error as `cause`, and `refetch_failure` events carry it as `error` ([#80](https://github.com/helloscoopa/run-cache/pull/80)). +- Storage adapters honour `autoSaveInterval` and `autoLoadOnInit` when attached ([#79](https://github.com/helloscoopa/run-cache/pull/79)). +- `handleProcessSignals` option to shut down (and save) on `SIGINT`/`SIGTERM` or page unload; off by default ([#70](https://github.com/helloscoopa/run-cache/pull/70)). +- `onListenerError` option; event listener errors no longer affect cache operations ([#76](https://github.com/helloscoopa/run-cache/pull/76)). +- Versioned GitBook docs with a version switcher ([#81](https://github.com/helloscoopa/run-cache/pull/81)). +- `CONTRIBUTING.md`, this changelog, and `npm run docs:check`, which checks the code samples in the docs against the exported API in CI ([#56](https://github.com/helloscoopa/run-cache/issues/56)). + +### Changed +- Dependents are invalidated automatically when the entry they depend on is updated, refetched, deleted, evicted, invalidated by tag or expires; circular dependencies are rejected ([#78](https://github.com/helloscoopa/run-cache/pull/78)). +- Loading from storage merges into the cache, re-arms TTL timers for the time remaining, and no longer writes source function code or applies the stored configuration ([#79](https://github.com/helloscoopa/run-cache/pull/79)). +- LRU eviction orders by recency and counts writes as a use ([#77](https://github.com/helloscoopa/run-cache/pull/77)). +- Empty strings are valid values ([#80](https://github.com/helloscoopa/run-cache/pull/80)). +- `CacheConfig.defaultTTL` is marked deprecated: it was never applied. + +### Fixed +- Storage adapters passed to `configure()` are attached ([#66](https://github.com/helloscoopa/run-cache/pull/66)). +- TTLs longer than the `setTimeout` limit work ([#68](https://github.com/helloscoopa/run-cache/pull/68)). +- Entries changed while a refetch is in flight are not resurrected ([#69](https://github.com/helloscoopa/run-cache/pull/69)). +- The package bundles and runs in browsers ([#71](https://github.com/helloscoopa/run-cache/pull/71)). +- Expired entries are removed when their TTL fires, and timers do not keep Node.js alive ([#73](https://github.com/helloscoopa/run-cache/pull/73)). +- A failed `set()` leaves the existing entry and its timer untouched ([#74](https://github.com/helloscoopa/run-cache/pull/74)). +- `clearEventListeners()` clears only the requested event's listeners ([#75](https://github.com/helloscoopa/run-cache/pull/75)). +- Documentation: removed APIs that do not exist (runtime validators, serialization adapters, `validator`/`metadata` options, `getInternalCache()`), awaited every async call in samples, stopped stringifying values by hand, and removed the duplicated GitBook/Mintlify tooling files ([#56](https://github.com/helloscoopa/run-cache/issues/56)). + +## [1.6.1] - 2025-05-26 + +### Fixed +- Build the minified bundle (`dist/index.min.js`). + +## [1.6.0] - 2025-05-13 + +### Added +- Middleware support with `use()` and `clearMiddleware()` ([#35](https://github.com/helloscoopa/run-cache/pull/35)). +- Tag-based invalidation ([#36](https://github.com/helloscoopa/run-cache/pull/36)). +- Storage adapters for localStorage, IndexedDB and the filesystem ([#37](https://github.com/helloscoopa/run-cache/pull/37)). + +### Changed +- Internal refactor for modularity ([#27](https://github.com/helloscoopa/run-cache/pull/27)); linting enabled ([#38](https://github.com/helloscoopa/run-cache/pull/38)). + +## [1.5.0] - 2025-05-12 + +### Added +- Wildcard key patterns ([#23](https://github.com/helloscoopa/run-cache/pull/23)). +- Configurable eviction policies ([#24](https://github.com/helloscoopa/run-cache/pull/24)). +- Graceful shutdown ([#25](https://github.com/helloscoopa/run-cache/pull/25)). +- Logging ([#26](https://github.com/helloscoopa/run-cache/pull/26)). + +## [1.4.1] - 2024-09-29 + +### Fixed +- Use `setInterval` instead of `setTimeout` for auto-refetch ([#18](https://github.com/helloscoopa/run-cache/pull/18)). + +## [1.4.0] - 2024-09-19 + +### Added +- Event listeners `onExpiry`, `onKeyExpiry`, `onRefetch`, `onKeyRefetch` and `clearEventListeners()`, built on an event emitter ([#16](https://github.com/helloscoopa/run-cache/pull/16)). + +## [1.3.2] - 2024-09-15 + +### Added +- Events/triggers ([#9](https://github.com/helloscoopa/run-cache/pull/9)). + +### Fixed +- No concurrent `sourceFn` calls between refetches ([#11](https://github.com/helloscoopa/run-cache/pull/11)). + +## [1.2.2] - 2024-09-13 + +### Fixed +- Ship `.d.ts` type declarations ([#5](https://github.com/helloscoopa/run-cache/pull/5)). + +## [1.2.0] - 2024-09-13 + +### Added +- Auto-refetch on expiry ([#4](https://github.com/helloscoopa/run-cache/pull/4)). + +### Changed +- `set()` and `setWithSourceFn()` merged into `set()` ([#2](https://github.com/helloscoopa/run-cache/pull/2)). + +## [1.0.5] - 2024-09-09 + +- Initial release. + +[Unreleased]: https://github.com/helloscoopa/run-cache/compare/v1.6.1...HEAD +[1.6.1]: https://github.com/helloscoopa/run-cache/compare/v1.6.0...v1.6.1 +[1.6.0]: https://github.com/helloscoopa/run-cache/compare/v1.5.0...v1.6.0 +[1.5.0]: https://github.com/helloscoopa/run-cache/compare/v1.4.1...v1.5.0 +[1.4.1]: https://github.com/helloscoopa/run-cache/compare/v1.4.0...v1.4.1 +[1.4.0]: https://github.com/helloscoopa/run-cache/compare/v1.3.2...v1.4.0 +[1.3.2]: https://github.com/helloscoopa/run-cache/compare/v1.2.2...v1.3.2 +[1.2.2]: https://github.com/helloscoopa/run-cache/compare/v1.2.0...v1.2.2 +[1.2.0]: https://github.com/helloscoopa/run-cache/compare/v1.0.5...v1.2.0 +[1.0.5]: https://github.com/helloscoopa/run-cache/releases/tag/v1.0.5 diff --git a/CLAUDE.md b/CLAUDE.md index 4cfa59e..28c7dbc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,6 +49,9 @@ npm run build:min # Minified build only # Linting npm run lint # Check for issues npm run lint:fix # Auto-fix issues + +# Docs +npm run docs:check # Check doc code samples against the exported API ``` ## Architecture @@ -103,13 +106,13 @@ await RunCache.set({ }); // Tag-based invalidation -RunCache.invalidateByTag("user"); +await RunCache.invalidateByTag("user"); // Dependency-based invalidation -RunCache.invalidateByDependency("user:session"); +await RunCache.invalidateByDependency("user:session"); // Middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`${context.operation} on ${context.key}`); return next(value); }); @@ -119,7 +122,7 @@ RunCache.use(async (value, context, next) => { ```typescript import { EvictionPolicy, LocalStorageAdapter } from 'run-cache'; -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU, debug: true, @@ -130,12 +133,12 @@ RunCache.configure({ ### Event Handling ```typescript // Global events -RunCache.onExpiry((event) => console.log(`Expired: ${event.key}`)); -RunCache.onRefetch((event) => console.log(`Refetched: ${event.key}`)); -RunCache.onRefetchFailure((event) => console.error(`Failed: ${event.key}`)); +await RunCache.onExpiry((event) => console.log(`Expired: ${event.key}`)); +await RunCache.onRefetch((event) => console.log(`Refetched: ${event.key}`)); +await RunCache.onRefetchFailure((event) => console.error(`Failed: ${event.key}`)); // Key-specific events (supports wildcards) -RunCache.onKeyExpiry("user:*", (event) => { +await RunCache.onKeyExpiry("user:*", (event) => { console.log(`User cache expired: ${event.key}`); }); ``` @@ -147,7 +150,7 @@ RunCache.onKeyExpiry("user:*", (event) => { 2. Implement core logic in `src/core/cache-store.ts` 3. Add static wrapper methods in `src/run-cache.ts` 4. Add comprehensive tests in `.test.ts` files -5. Update documentation in `gitbook/` (see [Documentation & Versioning](#documentation--versioning)) +5. Update documentation in `gitbook/` (see [Documentation & Versioning](#documentation--versioning)) and add an entry under `Unreleased` in `CHANGELOG.md` ### Testing Strategy - Unit tests for each component (`.unit.test.ts`) @@ -195,7 +198,7 @@ The docs are published on GitBook with a version menu above the sidebar, so read - Pushing a tag `vX.Y.Z` runs the **Docs version** workflow: it freezes `gitbook/` at that tag into `gitbook-versions/vX.Y/`, regenerates `gitbook-docs.yaml`, and opens a PR (`docs/version-vX.Y.Z`). Merging it makes vX.Y the new default. - A patch tag (`vX.Y.Z+1`) replaces `gitbook-versions/vX.Y/` in place; there is one version per minor line. - Manual equivalent: `node scripts/docs-version.mjs snapshot vX.Y.Z`. The workflow can also be run by hand (workflow_dispatch) with a `tag` input. -- The snapshot drops legacy tooling files (`book.json`, `mint.json`, `setup-gitbook.sh`, `README_GITBOOK.md`, `README_MAIN.md`, `DOCUMENTATION_SUMMARY.md`, `styles/`), strips live shields.io badges, and adds a version hint under the README's first heading. +- The snapshot drops legacy tooling files that older tags still contain (`book.json`, `mint.json`, `setup-gitbook.sh`, `README_GITBOOK.md`, `README_MAIN.md`, `DOCUMENTATION_SUMMARY.md`, `styles/`; GitBook Git Sync is the only docs toolchain, so `gitbook/` no longer has them), strips live shields.io badges, and adds a version hint under the README's first heading. - Running the snapshot rewrites the whole version directory, so hand fixes made in `gitbook-versions/vX.Y/` are lost if that line is snapshotted again. Fix them in `gitbook/` before tagging, or re-apply after. ### `gitbook-docs.yaml` rules @@ -205,6 +208,7 @@ The docs are published on GitBook with a version menu above the sidebar, so read - Version URL paths use hyphens (`v1-6`, `next`). ### Checks before committing doc changes +- `npm run docs:check` passes. It reads the fenced js/ts blocks in `README.md`, `CLAUDE.md` and `gitbook/`, plus `examples/`, and flags imports the package does not export, `RunCache` methods that do not exist, async calls without `await`, and known-stale patterns. Put `` above a block that breaks a rule on purpose. - `node scripts/docs-version.mjs config` leaves no diff (`git status` is clean for `gitbook-docs.yaml`). - Every relative `.md` link in the changed space resolves to a file in that space. - No new pages are missing from the space's `SUMMARY.md`. @@ -217,7 +221,7 @@ The docs are published on GitBook with a version menu above the sidebar, so read ### Debug Mode ```typescript -RunCache.configure({ debug: true }); +await RunCache.configure({ debug: true }); ``` ### Common Issues diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b7dafb3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,62 @@ +# Contributing to RunCache + +Thanks for helping improve RunCache. This guide covers setting up the project, the checks a pull request must pass, and how to keep the documentation accurate. + +## Setup + +You need Node.js 18 or later (CI runs on Node 18) and npm. + +```bash +git clone https://github.com/YOUR-USERNAME/run-cache.git +cd run-cache +npm install +git checkout -b fix/short-description +``` + +## Commands + +| Command | What it does | +| --- | --- | +| `npm test` | Run the Jest test suite | +| `npm run test:watch` | Run tests in watch mode | +| `npm run test:coverage` | Run tests with a coverage report | +| `npm run lint` / `npm run lint:fix` | Check (or fix) `src/` with ESLint | +| `npm run build` | Compile with `tsc`, then build the ESM and minified bundles with esbuild | +| `npm run docs:check` | Check the code samples in the docs against the exported API | + +After `npm run build`, you can run the JavaScript example with `node examples/middleware-example.js`. + +## Making a change + +1. **Open an issue first** for features or behaviour changes, so the approach can be agreed before you write code. Small fixes can go straight to a pull request. +2. **Keep zero dependencies.** RunCache has no runtime dependencies; do not add one. +3. **Add tests.** New behaviour needs tests, and a bug fix needs a test that fails without the fix. Keep coverage above 90%. +4. **Update the docs** in the same pull request (see below). +5. **Add a changelog entry** under `Unreleased` in [CHANGELOG.md](CHANGELOG.md). +6. **Use [Conventional Commits](https://www.conventionalcommits.org/)** for commit messages and PR titles, for example `fix: keep TTL timers when set() fails` or `docs: correct storage adapter options`. + +Before opening the pull request, make sure `npm test`, `npm run lint`, `npm run build` and `npm run docs:check` all pass. CI runs them on every pull request. + +## Documentation + +The docs are published on GitBook from this repository. [CLAUDE.md](CLAUDE.md#documentation--versioning) and [gitbook-versions/README.md](gitbook-versions/README.md) describe the layout in full; the short version: + +- `gitbook/` holds the docs for the next release. Edit pages there, and list any new page in `gitbook/SUMMARY.md`. +- `gitbook-versions/vX.Y/` holds frozen docs for released versions. Only fix errors there; never add unreleased features. +- `README.md` is the npm landing page; keep its examples in step with `gitbook/`. + +When writing code samples: + +- Import only what `src/index.ts` exports, and call only methods that exist on `RunCache`. +- `await` every async `RunCache` call (all of them except `createTypedCache()`), or explicitly return or chain the promise. +- Pass objects directly as `value`; RunCache serializes non-string values itself, and `get()` returns them parsed. + +`npm run docs:check` enforces these rules on `README.md`, `CLAUDE.md`, `gitbook/` and `examples/`. If a sample deliberately breaks a rule, for example to show the legacy string-based pattern, put `` on the line above its code fence. + +## Reporting a bug + +Include the RunCache version, your runtime (Node.js version or browser), a minimal code sample that reproduces the problem, and what you expected to happen instead. + +## Releases + +Maintainers release by bumping the version in `package.json`, moving the `Unreleased` changelog entries under the new version, and pushing a `vX.Y.Z` tag. The tag triggers the **Docs version** workflow, which freezes `gitbook/` into `gitbook-versions/vX.Y/`. diff --git a/README.md b/README.md index 1f84580..5150c72 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ # RunCache -A dependency-free, lightweight runtime caching library for JavaScript and TypeScript applications. RunCache allows you to cache string values with configurable time-to-live (TTL) settings and supports automatic value regeneration through source functions. +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. ## Key Features @@ -49,20 +49,20 @@ For use without a bundler, a minified ES module build is available from a CDN: import { RunCache } from "run-cache"; // Basic caching -await RunCache.set({ key: "user-profile", value: JSON.stringify({ name: "John Doe" }) }); +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: JSON.stringify({ data: [1, 2, 3] }), +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 () => JSON.stringify(await fetchWeatherData()), + sourceFn: async () => await fetchWeatherData(), ttl: 300000, // 5 minutes autoRefetch: true }); @@ -89,7 +89,7 @@ RunCache supports configurable cache eviction policies to manage memory usage by import { RunCache, EvictionPolicy } from "run-cache"; // Configure the cache with a max size of 100 entries and LRU eviction policy -RunCache.configure({ +await RunCache.configure({ maxEntries: 100, evictionPolicy: EvictionPolicy.LRU }); @@ -103,12 +103,12 @@ for (let i = 0; i < 150; i++) { // The oldest 50 entries will be automatically evicted // Change to LFU eviction policy -RunCache.configure({ +await RunCache.configure({ evictionPolicy: EvictionPolicy.LFU }); // Get the current configuration -const config = RunCache.getConfig(); +const config = await RunCache.getConfig(); console.log(config); // { maxEntries: 100, evictionPolicy: "lfu" } ``` @@ -118,31 +118,31 @@ RunCache supports tagging cache entries and invalidating groups of related entri ```typescript // Set entries with tags -await RunCache.set({ - key: "user:123:profile", - value: JSON.stringify({ name: "John Doe" }), +await RunCache.set({ + key: "user:123:profile", + value: { name: "John Doe" }, tags: ["user:123", "profile"] }); -await RunCache.set({ - key: "user:123:settings", - value: JSON.stringify({ theme: "dark" }), +await RunCache.set({ + key: "user:123:settings", + value: { theme: "dark" }, tags: ["user:123", "settings"] }); -await RunCache.set({ - key: "user:123:posts", - value: JSON.stringify([{ id: 1, title: "Hello" }]), +await RunCache.set({ + key: "user:123:posts", + value: [{ id: 1, title: "Hello" }], tags: ["user:123", "posts"] }); // Later, when user data changes, invalidate all related cache entries with a single call -RunCache.invalidateByTag("user:123"); +await RunCache.invalidateByTag("user:123"); // This removes all three entries with the "user:123" tag // You can also listen for tag invalidation events -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`Cache entry ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -153,28 +153,28 @@ RunCache enables establishing dependency relationships between cache entries wit ```typescript // Set the primary data cache -await RunCache.set({ - key: "user:123:profile", - value: JSON.stringify({ name: "John Doe" }) +await RunCache.set({ + key: "user:123:profile", + value: { name: "John Doe" } }); // Set dependent caches that rely on the profile data -await RunCache.set({ - key: "user:123:dashboard", - value: JSON.stringify({ widgets: [...] }), +await RunCache.set({ + key: "user:123:dashboard", + value: { widgets: [...] }, dependencies: ["user:123:profile"] }); -await RunCache.set({ - key: "user:123:recommendations", - value: JSON.stringify([...]), +await RunCache.set({ + key: "user:123:recommendations", + value: [...], dependencies: ["user:123:profile"] }); // Create multi-level dependencies -await RunCache.set({ - key: "home:feed", - value: JSON.stringify([...]), +await RunCache.set({ + key: "home:feed", + value: [...], dependencies: ["user:123:recommendations"] }); @@ -183,7 +183,7 @@ const isDependency = await RunCache.isDependencyOf("home:feed", "user:123:profil console.log(isDependency); // true // When the primary data changes, invalidate dependent entries with cascading effect -RunCache.invalidateByDependency("user:123:profile"); +await RunCache.invalidateByDependency("user:123:profile"); // This will invalidate all dependent entries, including nested dependencies: // - user:123:dashboard @@ -191,7 +191,7 @@ RunCache.invalidateByDependency("user:123:profile"); // - home:feed (because it depends on user:123:recommendations) // You can also listen for dependency invalidation events -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`Cache entry ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -242,23 +242,23 @@ await RunCache.refetch("api-data-*"); ```typescript // Remove a specific entry -RunCache.delete("cache-key"); +await RunCache.delete("cache-key"); // Remove multiple entries using wildcards -RunCache.delete("temp-*"); +await RunCache.delete("temp-*"); // Remove all cache entries -RunCache.flush(); +await RunCache.flush(); ``` #### Tag and Dependency Management ```typescript // Invalidate all entries with a specific tag -RunCache.invalidateByTag("user:123"); +await RunCache.invalidateByTag("user:123"); // Invalidate all entries dependent on a specific key -RunCache.invalidateByDependency("user:123:profile"); +await RunCache.invalidateByDependency("user:123:profile"); // Check if one key depends on another const isDependency = await RunCache.isDependencyOf("dashboard:123", "user:123"); @@ -278,13 +278,13 @@ const hasItems = await RunCache.has("session-*"); ```typescript // Configure cache settings -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, // Maximum number of entries before eviction evictionPolicy: EvictionPolicy.LRU // Eviction policy to use }); // Get current configuration -const config = RunCache.getConfig(); +const config = await RunCache.getConfig(); ``` ### Event System @@ -297,17 +297,17 @@ Listeners are isolated from cache operations: if a listener throws or rejects, t ```typescript // Global expiry event -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); }); // Specific key expiry -RunCache.onKeyExpiry("api-data", (event) => { +await RunCache.onKeyExpiry("api-data", (event) => { console.log(`API data cache expired`); }); // Pattern-based expiry events -RunCache.onKeyExpiry("user-*", (event) => { +await RunCache.onKeyExpiry("user-*", (event) => { console.log(`User cache ${event.key} expired`); }); ``` @@ -318,17 +318,17 @@ Expiry events carry the entry's stored `value`, `ttl`, `createdAt` and `updatedA ```typescript // Global refetch event -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache key ${event.key} was refreshed`); }); // Specific key refetch -RunCache.onKeyRefetch("weather-data", (event) => { +await RunCache.onKeyRefetch("weather-data", (event) => { console.log(`Weather data was refreshed`); }); // Pattern-based refetch events -RunCache.onKeyRefetch("stats-*", (event) => { +await RunCache.onKeyRefetch("stats-*", (event) => { console.log(`Statistics for ${event.key} were refreshed`); }); ``` @@ -337,17 +337,17 @@ RunCache.onKeyRefetch("stats-*", (event) => { ```typescript // Global refetch failure event -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`Failed to refresh cache key ${event.key}`); }); // Specific key refetch failure -RunCache.onKeyRefetchFailure("api-data", (event) => { +await RunCache.onKeyRefetchFailure("api-data", (event) => { console.error(`API data refresh failed`); }); // Pattern-based refetch failure events -RunCache.onKeyRefetchFailure("external-*", (event) => { +await RunCache.onKeyRefetchFailure("external-*", (event) => { console.error(`External data refresh failed for ${event.key}`); }); ``` @@ -356,12 +356,12 @@ RunCache.onKeyRefetchFailure("external-*", (event) => { ```typescript // Global tag invalidation event -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); }); // Specific key tag invalidation -RunCache.onKeyTagInvalidation("user:profile:*", (event) => { +await RunCache.onKeyTagInvalidation("user:profile:*", (event) => { console.log(`User profile cache was invalidated by tag: ${event.tag}`); }); ``` @@ -370,12 +370,12 @@ RunCache.onKeyTagInvalidation("user:profile:*", (event) => { ```typescript // Global dependency invalidation event -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); // Specific key dependency invalidation -RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { +await RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { console.log(`Dashboard cache was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -384,27 +384,27 @@ RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { ```typescript // Remove all event listeners -RunCache.clearEventListeners(); +await RunCache.clearEventListeners(); // Remove listeners for a specific event type -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); // Remove listeners for a specific key -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: "api-data" }); // Remove listeners using wildcard patterns -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH_FAILURE, key: "external-*" }); // Remove all listeners for a key, across every event type -RunCache.clearEventListeners({ key: "api-data" }); +await RunCache.clearEventListeners({ key: "api-data" }); ``` `clearEventListeners()` resolves to `true` if at least one listener was removed and `false` otherwise. Clearing one event type never affects another; for example, clearing `EVENT.REFETCH` keeps `EVENT.REFETCH_FAILURE` listeners. @@ -419,7 +419,7 @@ RunCache supports middleware functions that can intercept and transform cache op import { RunCache } from "run-cache"; // Add a simple logging middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`${context.operation} operation for key: ${context.key}`); return next(value); }); @@ -432,11 +432,11 @@ import { RunCache } from "run-cache"; import { encrypt, decrypt } from "./your-crypto-lib"; // Add encryption middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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' || context.operation === 'refetch') { + } else if (context.operation === 'get') { // Decrypt value after retrieving from cache const encrypted = await next(value); return encrypted ? decrypt(encrypted) : undefined; @@ -455,7 +455,7 @@ Middleware functions are executed in the order they are added: ```typescript // First middleware validates input -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { if (context.operation === 'set' && (!value || value.length < 3)) { throw new Error("Value must be at least 3 characters"); } @@ -463,8 +463,8 @@ RunCache.use(async (value, context, next) => { }); // Second middleware adds a timestamp -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { return next(`${value}|${Date.now()}`); } else if (context.operation === 'get' && value) { const result = await next(value); @@ -478,7 +478,7 @@ RunCache.use(async (value, context, next) => { ```typescript // Remove all middleware -RunCache.clearMiddleware(); +await RunCache.clearMiddleware(); ``` For more detailed information on middleware, see the [middleware documentation](./docs/middleware.md). @@ -503,7 +503,7 @@ const profiles = await RunCache.get("user:*:profile"); const user1Data = await RunCache.get("user:1:*"); // Delete all preference data -RunCache.delete("user:*:preferences"); +await RunCache.delete("user:*:preferences"); // Check if any user 2 data exists const hasUser2Data = await RunCache.has("user:2:*"); @@ -542,7 +542,7 @@ You can also manually trigger a complete shutdown of the cache: ```typescript // Manually shut down the cache, clearing all entries, intervals, and event listeners -RunCache.shutdown(); +await RunCache.shutdown(); ``` The `shutdown` method performs the following cleanup: @@ -562,7 +562,7 @@ Enable debug logging to see detailed information about all cache operations: ```typescript // Enable debug logging when configuring the cache -RunCache.configure({ +await RunCache.configure({ debug: true }); ``` @@ -577,14 +577,14 @@ All logs include timestamps and log levels for easy filtering. ```typescript // Example of enabling debug logging for debugging -RunCache.configure({ debug: true }); +await RunCache.configure({ debug: true }); // Perform some cache operations await RunCache.set({ key: "user-1", value: "Alice" }); await RunCache.get("user-1"); // Disable debug logging when done debugging -RunCache.configure({ debug: false }); +await RunCache.configure({ debug: false }); ``` ### Log Levels @@ -632,10 +632,10 @@ You can configure automatic saving at regular intervals: ```typescript // Save cache to storage every 5 minutes (300,000 ms) -RunCache.setupAutoSave(300000); +await RunCache.setupAutoSave(300000); // Disable auto-saving -RunCache.setupAutoSave(0); +await RunCache.setupAutoSave(0); ``` You can also manually control when to save and load: @@ -650,16 +650,16 @@ await RunCache.loadFromStorage(); ### Adapter Configuration Options -Each adapter accepts the following common options: +Each adapter accepts the following options: ```typescript interface StorageAdapterConfig { // Storage key/filename to use storageKey?: string; // Default: "run-cache-data" - + // Auto-save interval in milliseconds, applied when the adapter is attached autoSaveInterval?: number; // Default: 0 (disabled) - + // Whether to load existing data when the adapter is attached autoLoadOnInit?: boolean; // Default: true } @@ -693,22 +693,22 @@ The FilesystemAdapter writes atomically (temporary file plus rename), so an inte ### Example: Full Cache Persistence Setup ```typescript -import { RunCache, LocalStorageAdapter } from 'run-cache'; +import { RunCache, EvictionPolicy, LocalStorageAdapter } from 'run-cache'; -// Configure RunCache with persistence -RunCache.configure({ +// Configure RunCache with persistence; this also loads the saved entries +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU, storageAdapter: new LocalStorageAdapter({ - storageKey: 'my-app-cache' - }) + storageKey: 'my-app-cache', + autoSaveInterval: 60000 // save every minute + }), + // Save via RunCache.shutdown() on SIGINT/SIGTERM (Node.js) or page unload (browser) + handleProcessSignals: true }); -// Set up auto-save every minute -RunCache.setupAutoSave(60000); - -// When the app shuts down, the cache will be saved automatically -// When the app starts up, the cache will be loaded automatically +// Or save explicitly before your app exits +await RunCache.shutdown(); ``` ## License diff --git a/examples/middleware-example.js b/examples/middleware-example.js index 2d0d833..f308d9f 100644 --- a/examples/middleware-example.js +++ b/examples/middleware-example.js @@ -5,37 +5,37 @@ const { RunCache } = require('../dist'); -// Create a simple logging middleware -RunCache.use(async (value, context, next) => { - console.log(`[Middleware] ${context.operation} operation for key: ${context.key}`); - return next(value); -}); +(async () => { + // Create a simple logging middleware + await RunCache.use(async (value, context, next) => { + console.log(`[Middleware] ${context.operation} operation for key: ${context.key}`); + return next(value); + }); -// Add an encryption middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { - // Simple "encryption" for demonstration (base64 encoding) - console.log(`[Encryption] Encoding value for key: ${context.key}`); - const encodedValue = Buffer.from(value).toString('base64'); - return next(encodedValue); - } else if (context.operation === 'get' && value) { - // Get the encrypted value and decrypt it - const encryptedValue = await next(value); - if (encryptedValue) { - console.log(`[Encryption] Decoding value for key: ${context.key}`); - return Buffer.from(encryptedValue, 'base64').toString('utf-8'); + // Add an encryption middleware. + // Middleware sees values after serialization, so `value` is always a string here. + await RunCache.use(async (value, context, next) => { + if ((context.operation === 'set' || context.operation === 'refetch') && value) { + // Simple "encryption" for demonstration (base64 encoding) + console.log(`[Encryption] Encoding value for key: ${context.key}`); + const encodedValue = Buffer.from(value).toString('base64'); + return next(encodedValue); + } else if (context.operation === 'get' && value) { + // Get the encrypted value and decrypt it + const encryptedValue = await next(value); + if (encryptedValue) { + console.log(`[Encryption] Decoding value for key: ${context.key}`); + return Buffer.from(encryptedValue, 'base64').toString('utf-8'); + } + return encryptedValue; } - return encryptedValue; - } - return next(value); -}); + return next(value); + }); -// Set a value in the cache -(async () => { // Cache some data await RunCache.set({ key: 'user:123', - value: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }), + value: { name: 'John Doe', email: 'john@example.com' }, ttl: 10000 // 10 seconds }); @@ -48,7 +48,7 @@ RunCache.use(async (value, context, next) => { // Clear middleware to demonstrate how middleware works console.log('\nClearing middleware to show the difference:'); - RunCache.clearMiddleware(); + await RunCache.clearMiddleware(); // Now retrieve the data without decryption middleware const encryptedData = await RunCache.get('user:123'); @@ -57,4 +57,4 @@ RunCache.use(async (value, context, next) => { // Manually decode to show it's the same data const decodedData = Buffer.from(encryptedData, 'base64').toString('utf-8'); console.log('Manually decoded:', decodedData); -})(); \ No newline at end of file +})(); diff --git a/examples/persistent-storage.ts b/examples/persistent-storage.ts index ff80341..169b1ef 100644 --- a/examples/persistent-storage.ts +++ b/examples/persistent-storage.ts @@ -5,7 +5,7 @@ async function localStorageExample() { console.log('Running localStorage persistence example...'); // Configure RunCache with localStorage adapter - RunCache.configure({ + await RunCache.configure({ maxEntries: 100, evictionPolicy: EvictionPolicy.LRU, storageAdapter: new LocalStorageAdapter({ @@ -14,11 +14,11 @@ async function localStorageExample() { }); // Set up auto-save every 30 seconds - RunCache.setupAutoSave(30000); + await RunCache.setupAutoSave(30000); // Set some data in the cache - await RunCache.set({ key: 'user:1', value: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }) }); - await RunCache.set({ key: 'settings', value: JSON.stringify({ theme: 'dark', notifications: true }) }); + await RunCache.set({ key: 'user:1', value: { name: 'John Doe', email: 'john@example.com' } }); + await RunCache.set({ key: 'settings', value: { theme: 'dark', notifications: true } }); console.log('Cache data set and persisted to localStorage'); console.log('Manually saving to storage...'); @@ -37,7 +37,7 @@ async function indexedDBExample() { console.log('Running IndexedDB persistence example...'); // Configure RunCache with IndexedDB adapter - RunCache.configure({ + await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LFU, storageAdapter: new IndexedDBAdapter({ @@ -46,11 +46,11 @@ async function indexedDBExample() { }); // Set some data in the cache - await RunCache.set({ key: 'products', value: JSON.stringify([ + await RunCache.set({ key: 'products', value: [ { id: 1, name: 'Product 1', price: 10.99 }, { id: 2, name: 'Product 2', price: 19.99 }, { id: 3, name: 'Product 3', price: 5.99 } - ])}); + ]}); console.log('Cache data set and persisted to IndexedDB'); console.log('Manually saving to storage...'); @@ -69,7 +69,7 @@ async function filesystemExample() { console.log('Running filesystem persistence example...'); // Configure RunCache with filesystem adapter - RunCache.configure({ + await RunCache.configure({ maxEntries: 500, evictionPolicy: EvictionPolicy.LRU, storageAdapter: new FilesystemAdapter({ @@ -78,15 +78,15 @@ async function filesystemExample() { }); // Set some data in the cache - await RunCache.set({ key: 'logs', value: JSON.stringify([ + await RunCache.set({ key: 'logs', value: [ { timestamp: Date.now(), message: 'Application started' }, { timestamp: Date.now() + 1000, message: 'User logged in' } - ])}); + ]}); // Set data with TTL (will be restored with correct TTL) await RunCache.set({ key: 'session', - value: JSON.stringify({ token: 'abc123', user: 'admin' }), + value: { token: 'abc123', user: 'admin' }, ttl: 3600000 // 1 hour }); diff --git a/gitbook/DOCUMENTATION_SUMMARY.md b/gitbook/DOCUMENTATION_SUMMARY.md deleted file mode 100644 index 399fb1d..0000000 --- a/gitbook/DOCUMENTATION_SUMMARY.md +++ /dev/null @@ -1,71 +0,0 @@ -# RunCache GitBook Documentation Summary - -## Overview - -This GitBook documentation provides comprehensive information about the RunCache library, a dependency-free, lightweight runtime caching library for JavaScript and TypeScript applications. The documentation is structured to be user-friendly and accessible for both beginners and advanced users. - -## Documentation Contents - -### Getting Started -- **Installation**: Instructions for installing RunCache in different environments -- **Basic Usage**: Common patterns and fundamental concepts - -### Core Features -- **Cache Management**: Basic cache operations (set, get, delete) -- **TTL and Expiration**: Working with time-to-live functionality -- **Automatic Refetching**: Setting up auto-refresh for cache entries -- **Source Functions**: Using functions to generate cache values -- **Eviction Policies**: LRU and LFU policies for managing cache size -- **Pattern Matching**: Using wildcards to work with groups of cache keys - -### Advanced Features -- **Tag-based Invalidation**: Grouping and invalidating related cache entries -- **Dependency Tracking**: Creating relationships between cache entries -- **Event System**: Subscribing to cache events -- **Middleware**: Intercepting and transforming cache operations -- **Persistent Storage**: Saving cache data across application restarts -- **Resource Management**: Optimizing memory usage and cleanup - -### API Reference -- **RunCache**: Complete API documentation for the main class -- **Storage Adapters**: Documentation for built-in storage adapters -- **Events**: Reference for all event types and handlers -- **Types**: TypeScript type definitions - -### Guides -- **Best Practices**: Recommendations for effective cache usage -- **Performance Optimization**: Tips for maximizing performance -- **Debugging and Logging**: Troubleshooting and monitoring - -### Resources -- **FAQ**: Frequently asked questions -- **Contributing**: Guidelines for contributing to the project -- **License**: License information - -## Documentation Features - -The GitBook documentation includes: - -- **Comprehensive API Reference**: Detailed documentation of all methods and parameters -- **Code Examples**: Practical examples for all features -- **Custom Styling**: Enhanced readability with custom CSS -- **Navigation**: Well-organized table of contents -- **Search Functionality**: Built-in search for quick access to information - -## Usage - -The documentation can be: -- Served locally for development -- Built for production deployment -- Customized with additional plugins or styles -- Extended with new sections as the library evolves - -## Future Improvements - -Potential future enhancements for the documentation: - -- Interactive examples -- Version-specific documentation -- Integration with automated API documentation tools -- Multi-language support -- Video tutorials and walkthroughs \ No newline at end of file diff --git a/gitbook/README.md b/gitbook/README.md index e2810a0..cb5aa0d 100644 --- a/gitbook/README.md +++ b/gitbook/README.md @@ -8,7 +8,7 @@ [![ci-tests](https://img.shields.io/github/actions/workflow/status/helloscoopa/run-cache/tests.yml?label=tests)](https://github.com/helloscoopa/run-cache/actions/workflows/tests.yml) [![coverage](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fhelloscoopa%2Frun-cache%2Fbadges%2Fcoverage.json)](https://github.com/helloscoopa/run-cache/actions/workflows/tests.yml) -RunCache allows you to cache string 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. +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 @@ -31,20 +31,20 @@ RunCache allows you to cache string values with configurable time-to-live (TTL) import { RunCache } from "run-cache"; // Basic caching -await RunCache.set({ key: "user-profile", value: JSON.stringify({ name: "John Doe" }) }); +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: JSON.stringify({ data: [1, 2, 3] }), +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 () => JSON.stringify(await fetchWeatherData()), + sourceFn: async () => await fetchWeatherData(), ttl: 300000, // 5 minutes autoRefetch: true }); diff --git a/gitbook/README_GITBOOK.md b/gitbook/README_GITBOOK.md deleted file mode 100644 index 71aa736..0000000 --- a/gitbook/README_GITBOOK.md +++ /dev/null @@ -1,79 +0,0 @@ -# RunCache Documentation - -This directory contains the GitBook documentation for the RunCache project. The documentation is structured to provide comprehensive information about the library's features, API, and usage patterns. - -## Structure - -The documentation is organized into the following sections: - -- **Getting Started**: Installation and basic usage guides -- **Core Features**: Documentation for fundamental features -- **Advanced Features**: Documentation for more complex features -- **API Reference**: Detailed API documentation -- **Guides**: Best practices and optimization tips -- **Resources**: FAQ and additional resources - -## Using with GitBook - -To use this documentation with GitBook: - -1. Install GitBook CLI (if you haven't already): - ```bash - npm install -g gitbook-cli - ``` - -2. Navigate to the gitbook directory: - ```bash - cd gitbook - ``` - -3. Initialize GitBook: - ```bash - gitbook init - ``` - -4. Serve the documentation locally: - ```bash - gitbook serve - ``` - -5. Build the documentation for production: - ```bash - gitbook build - ``` - -## Customization - -You can customize the GitBook configuration by editing the `book.json` file. For example: - -```json -{ - "title": "RunCache Documentation", - "description": "Documentation for the RunCache library", - "author": "Your Name", - "plugins": ["search", "github", "edit-link"], - "pluginsConfig": { - "github": { - "url": "https://github.com/helloscoopa/run-cache" - }, - "edit-link": { - "base": "https://github.com/helloscoopa/run-cache/edit/main/gitbook", - "label": "Edit This Page" - } - } -} -``` - -## Contributing - -To contribute to the documentation: - -1. Fork the repository -2. Make your changes -3. Submit a pull request - -Please ensure your documentation is clear, concise, and includes examples where appropriate. - -## License - -The documentation is licensed under the same MIT license as the RunCache project. \ No newline at end of file diff --git a/gitbook/README_MAIN.md b/gitbook/README_MAIN.md deleted file mode 100644 index c72e5f5..0000000 --- a/gitbook/README_MAIN.md +++ /dev/null @@ -1,63 +0,0 @@ -# RunCache GitBook Documentation - -This directory contains the GitBook documentation for the RunCache project. The documentation is designed to be comprehensive and user-friendly, covering all aspects of the library. - -## Directory Structure - -``` -gitbook/ -├── README.md # Introduction page -├── SUMMARY.md # Table of contents -├── book.json # GitBook configuration -├── getting-started/ # Getting started guides -├── features/ # Core features documentation -├── advanced/ # Advanced features documentation -├── api/ # API reference -├── guides/ # Best practices and guides -├── resources/ # FAQ and resources -└── styles/ # Custom CSS styles -``` - -## Setting Up the Documentation - -To set up and serve the GitBook documentation: - -1. Make sure you have Node.js and npm installed -2. Run the setup script: - ```bash - ./setup-gitbook.sh - ``` - - Or manually: - ```bash - npm install -g gitbook-cli - cd gitbook - gitbook install - gitbook serve - ``` - -3. Open your browser and navigate to `http://localhost:4000` to view the documentation - -## Building for Production - -To build the documentation for production: - -```bash -cd gitbook -gitbook build -``` - -The built documentation will be available in the `_book` directory. - -## Contributing to the Documentation - -Contributions to the documentation are welcome! Please follow these guidelines: - -1. Make sure your changes are accurate and well-written -2. Follow the existing style and structure -3. Add examples where appropriate -4. Test any code examples to ensure they work correctly - -## License - -The documentation is licensed under the MIT License, the same as the RunCache project itself. \ No newline at end of file diff --git a/gitbook/SUMMARY.md b/gitbook/SUMMARY.md index 23bc33c..3e6a650 100644 --- a/gitbook/SUMMARY.md +++ b/gitbook/SUMMARY.md @@ -22,8 +22,8 @@ * [Middleware](advanced/middleware.md) * [Persistent Storage](advanced/persistent-storage.md) * [Resource Management](advanced/resource-management.md) -* [Serialization Adapters](advanced/serialization-adapters.md) -* [Type Validation](advanced/type-validation.md) +* [Value Serialization](advanced/serialization-adapters.md) +* [Type Safety](advanced/type-validation.md) ## API Reference * [RunCache](api/run-cache.md) @@ -31,7 +31,6 @@ * [Events](api/events.md) * [Types](api/types.md) * [Typed Cache Interface](api/typed-cache-interface.md) -* [Serialization System](api/serialization-system.md) ## Guides * [Best Practices](guides/best-practices.md) diff --git a/gitbook/advanced/dependency-tracking.md b/gitbook/advanced/dependency-tracking.md index cd11592..135f2f8 100644 --- a/gitbook/advanced/dependency-tracking.md +++ b/gitbook/advanced/dependency-tracking.md @@ -24,13 +24,13 @@ To establish a dependency relationship, use the `dependencies` parameter when se // Primary data await RunCache.set({ key: 'user:1:profile', - value: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }) + value: { name: 'John Doe', email: 'john@example.com' } }); // Dependent data await RunCache.set({ key: 'user:1:dashboard', - value: JSON.stringify({ widgets: [...] }), + value: { widgets: [...] }, dependencies: ['user:1:profile'] // This entry depends on the profile }); ``` @@ -60,20 +60,20 @@ RunCache supports multi-level dependency chains: // Primary data await RunCache.set({ key: 'user:1:profile', - value: JSON.stringify({ name: 'John Doe' }) + value: { name: 'John Doe' } }); // First-level dependent data await RunCache.set({ key: 'user:1:recommendations', - value: JSON.stringify([...]), + value: [...], dependencies: ['user:1:profile'] }); // Second-level dependent data await RunCache.set({ key: 'home:feed', - value: JSON.stringify([...]), + value: [...], dependencies: ['user:1:recommendations'] }); ``` @@ -89,14 +89,14 @@ A cache entry can depend on multiple other entries: ```typescript // Primary data sources -await RunCache.set({ key: 'products', value: JSON.stringify([...]) }); -await RunCache.set({ key: 'categories', value: JSON.stringify([...]) }); -await RunCache.set({ key: 'user:1:preferences', value: JSON.stringify({...}) }); +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: JSON.stringify([...]), + value: [...], dependencies: ['products', 'categories', 'user:1:preferences'] }); ``` @@ -121,18 +121,19 @@ console.log(isNotDependency); // false (no dependency relationship) ## Manual Dependency Invalidation -You can manually invalidate a cache entry and all its dependents using the `invalidateByDependency` method: +You can invalidate an entry's dependents without changing the entry itself using the `invalidateByDependency` method: ```typescript -// Invalidate an entry and all its dependents -RunCache.invalidateByDependency('user:1:profile'); +// Invalidate everything that depends on the profile +await RunCache.invalidateByDependency('user:1:profile'); ``` This will: -1. Invalidate the specified entry (`user:1:profile`) -2. Invalidate all entries that directly depend on it (`user:1:recommendations`) -3. Invalidate all entries that depend on those entries (`home:feed`) -4. And so on, following the dependency chain +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 @@ -140,17 +141,17 @@ RunCache provides events to monitor dependency invalidations: ```typescript // Global dependency invalidation event -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`Cache entry ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); // Specific key dependency invalidation -RunCache.onKeyDependencyInvalidation("user:1:dashboard", (event) => { +await RunCache.onKeyDependencyInvalidation("user:1:dashboard", (event) => { console.log(`Dashboard cache was invalidated due to dependency on: ${event.dependencyKey}`); }); // Pattern-based dependency invalidation events -RunCache.onKeyDependencyInvalidation("home:*", (event) => { +await RunCache.onKeyDependencyInvalidation("home:*", (event) => { console.log(`Home page component ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -171,25 +172,26 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/users/1'); const data = await response.json(); - return JSON.stringify(data); + 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: async () => { - // Get the user profile from cache - const profileJson = await RunCache.get('user:1:profile'); - const profile = JSON.parse(profileJson); - - // 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 JSON.stringify(recommendations); - }, + sourceFn: fetchRecommendations, dependencies: ['user:1:profile'], ttl: 600000, // 10 minutes autoRefetch: true @@ -197,11 +199,21 @@ await RunCache.set({ ``` In this example: -1. When `user:1:profile` is refreshed (automatically or manually), its dependents are invalidated -2. When `user:1:recommendations` is next accessed, its source function will be called -3. The source function will use the fresh profile data to generate new recommendations +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 -This creates a powerful pattern for maintaining consistency while still benefiting from caching. +```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 @@ -243,16 +255,16 @@ Define dependencies as specifically as possible: ```typescript // Too broad - invalidates too much -await RunCache.set({ - key: 'user:1:dashboard', - value: '...', +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: '...', +await RunCache.set({ + key: 'user:1:dashboard', + value: '...', dependencies: ['user:1:profile', 'user:1:preferences'] // Only what's needed }); ``` @@ -273,9 +285,9 @@ await RunCache.set({ // Different invalidation options: // 1. Invalidate when profile changes (automatic via dependency) // 2. Invalidate all user:1 data (via tag) -RunCache.invalidateByTag('user:1'); +await RunCache.invalidateByTag('user:1'); // 3. Invalidate all feeds (via tag) -RunCache.invalidateByTag('feed'); +await RunCache.invalidateByTag('feed'); ``` ### 5. Monitor Invalidation Patterns @@ -284,7 +296,7 @@ Use events to monitor and understand how your dependencies behave: ```typescript // Track dependency invalidations -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`${event.key} invalidated due to ${event.dependencyKey}`); // Track metrics about invalidation frequency trackMetric('cache.dependency.invalidation', { @@ -306,18 +318,18 @@ async function cacheArticleWithRelatedContent(articleId) { const article = await fetchArticle(articleId); await RunCache.set({ key: `article:${articleId}`, - value: JSON.stringify(article) + 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: JSON.stringify(relatedArticle), + value: relatedArticle, dependencies: [`article:${articleId}`] // Dynamic dependency }); } @@ -326,30 +338,51 @@ async function cacheArticleWithRelatedContent(articleId) { ### 2. Dependency-Aware Refresh -Implement smart refreshing that considers dependencies: +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 -async function smartRefresh(key) { - // First, check if this key has dependencies - const allKeys = await RunCache.get('*'); // Get all cache keys - const dependencyKeys = []; - - for (const cacheKey of allKeys) { - if (await RunCache.isDependencyOf(key, cacheKey)) { - dependencyKeys.push(cacheKey); - } +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 dependencies first (from furthest to closest) - for (const depKey of dependencyKeys.reverse()) { - await RunCache.refetch(depKey); + + // Refresh the parents first. Each one removes `key` and its other dependents. + for (const parent of definition.dependencies ?? []) { + await smartRefresh(parent, refreshed); } - - // Then refresh the target key - await RunCache.refetch(key); + + // 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: diff --git a/gitbook/advanced/event-system.md b/gitbook/advanced/event-system.md index 4a16767..1315ca7 100644 --- a/gitbook/advanced/event-system.md +++ b/gitbook/advanced/event-system.md @@ -20,11 +20,13 @@ RunCache provides several event types you can subscribe to: | Event Type | Description | Event Object Properties | |------------|-------------|------------------------| -| `EXPIRE` | Triggered when a cache entry expires | `key`, `ttl`, `updatedAt` | -| `REFETCH` | Triggered when a cache entry is refreshed | `key`, `metadata` | -| `REFETCH_FAILURE` | Triggered when a cache refresh fails | `key`, `error`, `metadata` | -| `TAG_INVALIDATION` | Triggered when a cache entry is invalidated by tag | `key`, `tag` | -| `DEPENDENCY_INVALIDATION` | Triggered when a cache entry is invalidated by dependency | `key`, `dependencyKey` | +| `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 @@ -34,7 +36,7 @@ Global event listeners are triggered for all cache entries that match the specif ```typescript // Listen for all expiry events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); }); ``` @@ -43,13 +45,13 @@ RunCache.onExpiry((event) => { ```typescript // Listen for all successful refetch events -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); }); // Listen for all refetch failure events -RunCache.onRefetchFailure((event) => { - console.error(`Failed to refresh cache key ${event.key}:`, event.error.message); +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}:`, event.error); }); ``` @@ -57,7 +59,7 @@ RunCache.onRefetchFailure((event) => { ```typescript // Listen for all tag invalidation events -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -66,7 +68,7 @@ RunCache.onTagInvalidation((event) => { ```typescript // Listen for all dependency invalidation events -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -79,12 +81,12 @@ Key-specific event listeners are triggered only for cache entries with keys that ```typescript // Listen for expiry of a specific key -RunCache.onKeyExpiry("api-data", (event) => { +await RunCache.onKeyExpiry("api-data", (event) => { console.log(`API data cache expired`); }); // Listen for expiry of keys matching a pattern -RunCache.onKeyExpiry("user:*:profile", (event) => { +await RunCache.onKeyExpiry("user:*:profile", (event) => { console.log(`User profile ${event.key} expired`); }); ``` @@ -93,13 +95,13 @@ RunCache.onKeyExpiry("user:*:profile", (event) => { ```typescript // Listen for refetch of a specific key -RunCache.onKeyRefetch("weather-data", (event) => { +await RunCache.onKeyRefetch("weather-data", (event) => { console.log(`Weather data was refreshed`); }); // Listen for refetch failures of keys matching a pattern -RunCache.onKeyRefetchFailure("api:*", (event) => { - console.error(`API data ${event.key} refresh failed:`, event.error.message); +await RunCache.onKeyRefetchFailure("api:*", (event) => { + console.error(`API data ${event.key} refresh failed:`, event.error); }); ``` @@ -107,7 +109,7 @@ RunCache.onKeyRefetchFailure("api:*", (event) => { ```typescript // Listen for tag invalidation of keys matching a pattern -RunCache.onKeyTagInvalidation("user:*:profile", (event) => { +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -116,7 +118,7 @@ RunCache.onKeyTagInvalidation("user:*:profile", (event) => { ```typescript // Listen for dependency invalidation of a specific key -RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { +await RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { console.log(`Main dashboard was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -129,7 +131,7 @@ To remove all event listeners: ```typescript // Remove all event listeners -RunCache.clearEventListeners(); +await RunCache.clearEventListeners(); ``` ### Removing Specific Event Listeners @@ -138,7 +140,7 @@ To remove listeners for a specific event type: ```typescript // Remove all expiry event listeners -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); ``` @@ -149,13 +151,13 @@ To remove listeners for a specific key or pattern: ```typescript // Remove refetch listeners for a specific key -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: "api-data" }); // Remove refetch failure listeners for keys matching a pattern -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH_FAILURE, key: "api:*" }); @@ -169,23 +171,23 @@ Use events to implement comprehensive logging: ```typescript // Set up logging for all major events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { logger.info(`Cache expired: ${event.key}`); }); -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { logger.info(`Cache refreshed: ${event.key}`); }); -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { logger.error(`Cache refresh failed: ${event.key}`, event.error); }); -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { logger.info(`Cache invalidated by tag: ${event.key} (tag: ${event.tag})`); }); -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { logger.info(`Cache invalidated by dependency: ${event.key} (depends on: ${event.dependencyKey})`); }); ``` @@ -196,22 +198,31 @@ Use events to implement retry logic for failed refetches: ```typescript // Set up retry logic with exponential backoff -RunCache.onRefetchFailure((event) => { - const retryCount = (event.metadata?.retryCount || 0) + 1; - +// 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, { - metadata: { retryCount } - }); + 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 @@ -219,31 +230,54 @@ RunCache.onRefetchFailure((event) => { 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(() => { - // Set up event listener for cache refreshes - RunCache.onKeyRefetch(`user:${userId}:profile`, () => { - // Update UI when profile is refreshed - RunCache.get(`user:${userId}:profile`) - .then(data => data && setProfile(JSON.parse(data))); - }); - - // Initial data fetch - RunCache.get(`user:${userId}:profile`) - .then(data => data && setProfile(JSON.parse(data))); - - // Clean up listener on unmount + 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 () => { - RunCache.clearEventListeners({ - event: EVENT.REFETCH, - key: `user:${userId}:profile` - }); + active = false; // ignore a load that finishes after cleanup + unsubscribe(); }; }, [userId]); - + // Render profile... } ``` @@ -262,18 +296,18 @@ let metrics = { dependencyInvalidationCount: 0 }; -RunCache.onExpiry(() => metrics.expiryCount++); -RunCache.onRefetch(() => metrics.refetchCount++); -RunCache.onRefetchFailure(() => metrics.refetchFailureCount++); -RunCache.onTagInvalidation(() => metrics.tagInvalidationCount++); -RunCache.onDependencyInvalidation(() => metrics.dependencyInvalidationCount++); +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, @@ -291,9 +325,9 @@ Use events to implement custom cascading update logic: ```typescript // When user data is refreshed, also refresh related data -RunCache.onKeyRefetch('user:*:profile', async (event) => { +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`); @@ -302,23 +336,17 @@ RunCache.onKeyRefetch('user:*:profile', async (event) => { ## Event Metadata -You can attach custom metadata to cache entries, which will be included in event objects: +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 -// Set cache entry with metadata -await RunCache.set({ - key: 'api-data', - value: JSON.stringify({ results: [...] }), - metadata: { - source: 'external-api', - version: '1.0', - timestamp: Date.now() - } -}); +const entryInfo = new Map(); -// Access metadata in event handlers -RunCache.onKeyExpiry('api-data', (event) => { - console.log(`API data expired. Source: ${event.metadata.source}, Version: ${event.metadata.version}`); +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}`); }); ``` @@ -330,12 +358,12 @@ Event handlers should be fast and non-blocking: ```typescript // Good - lightweight handler -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache expired: ${event.key}`); }); // Avoid - heavy processing in handler -RunCache.onExpiry(async (event) => { +await RunCache.onExpiry(async (event) => { // DON'T do this - blocks the event loop await heavyProcessing(); await networkRequest(); @@ -358,7 +386,7 @@ To react to errors inside a specific listener, handle them there: ```typescript // Good - error handling -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { try { processRefetchEvent(event); } catch (error) { @@ -373,12 +401,12 @@ Use specific key patterns to minimize unnecessary event processing: ```typescript // Too broad - triggers for all keys -RunCache.onKeyExpiry('*', (event) => { +await RunCache.onKeyExpiry('*', (event) => { // This will run for EVERY expiry }); // Better - more specific pattern -RunCache.onKeyExpiry('api:*', (event) => { +await RunCache.onKeyExpiry('api:*', (event) => { // This will only run for API-related expirations }); ``` @@ -389,23 +417,22 @@ Remove event listeners when they're no longer needed: ```typescript // In a component or module initialization -function initializeModule() { +async function initializeModule() { // Set up event listeners - RunCache.onKeyRefetch('module-data', handleRefetch); - + await RunCache.onKeyRefetch('module-data', handleRefetch); + // Return cleanup function - return () => { + return () => RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'module-data' }); - }; } // Later, when shutting down -const cleanup = initializeModule(); +const cleanup = await initializeModule(); // When module is unloaded -cleanup(); +await cleanup(); ``` ### 5. Avoid Circular Event Handling @@ -414,12 +441,12 @@ Be careful not to create circular event handling patterns: ```typescript // Dangerous - potential circular handling -RunCache.onKeyRefetch('data-a', () => { - RunCache.refetch('data-b'); +await RunCache.onKeyRefetch('data-a', async () => { + await RunCache.refetch('data-b'); }); -RunCache.onKeyRefetch('data-b', () => { - RunCache.refetch('data-a'); // Creates a loop! +await RunCache.onKeyRefetch('data-b', async () => { + await RunCache.refetch('data-a'); // Creates a loop! }); ``` diff --git a/gitbook/advanced/middleware.md b/gitbook/advanced/middleware.md index 5164b6d..9f7d4b8 100644 --- a/gitbook/advanced/middleware.md +++ b/gitbook/advanced/middleware.md @@ -16,7 +16,7 @@ Middleware functions are added to the RunCache using the `use()` method: import { RunCache } from 'run-cache'; // Add a simple middleware that logs all cache operations -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`Cache operation: ${context.operation} for key: ${context.key}`); return next(value); }); @@ -32,7 +32,7 @@ Middleware functions have the following signature: Where: -- `value`: The current value being processed +- `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 @@ -49,6 +49,18 @@ interface MiddlewareContext { } ``` +### 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 @@ -58,11 +70,11 @@ import { RunCache } from 'run-cache'; import { encrypt, decrypt } from './your-crypto-lib'; // Add encryption middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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' || context.operation === 'refetch') { + } else if (context.operation === 'get') { // Decrypt the value after retrieval const encrypted = await next(value); return encrypted ? decrypt(encrypted) : undefined; @@ -81,7 +93,7 @@ const value = await RunCache.get('sensitive-data'); // Returns decrypted 'secret import { RunCache } from 'run-cache'; // Add validation middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { if (context.operation === 'set') { if (!value || value.length < 3) { // Reject invalid values @@ -105,40 +117,17 @@ try { } ``` -### JSON Serialization Middleware +### Objects and Middleware -```javascript -import { RunCache } from 'run-cache'; +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: -// Add JSON serialization middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value && typeof value === 'object') { - // Serialize objects to JSON strings - return next(JSON.stringify(value)); - } else if ((context.operation === 'get' || context.operation === 'refetch') && value) { - const result = await next(value); - if (result) { - try { - // Try to parse the result as JSON - return JSON.parse(result); - } catch (e) { - // If parsing fails, return the raw string - return result; - } - } - return result; - } - return next(value); -}); - -// Store complex objects directly -await RunCache.set({ - key: 'user', - value: { id: 123, name: 'John Doe', email: 'john@example.com' } +```javascript +await RunCache.set({ + key: 'user', + value: { id: 123, name: 'John Doe', email: 'john@example.com' } }); -// Retrieve the object -const user = await RunCache.get('user'); // Returns the parsed object: { id: 123, name: 'John Doe', ... } +const user = await RunCache.get('user'); // { id: 123, name: 'John Doe', ... } ``` ## Chaining Multiple Middleware @@ -147,8 +136,8 @@ Middleware functions are executed in the order they are added. Each middleware c ```javascript // First middleware compresses the data -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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); @@ -158,8 +147,8 @@ RunCache.use(async (value, context, next) => { }); // Second middleware encrypts the data -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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); @@ -185,13 +174,13 @@ When getting a value: To remove all middleware functions: ```javascript -RunCache.clearMiddleware(); +await RunCache.clearMiddleware(); ``` ## Best Practices 1. **Keep middleware functions focused**: Each middleware should have a single responsibility. -2. **Handle all operations**: Make sure to handle all relevant operations (get, set, refetch) for consistency. +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. diff --git a/gitbook/advanced/persistent-storage.md b/gitbook/advanced/persistent-storage.md index 9b0e773..c2f0fb3 100644 --- a/gitbook/advanced/persistent-storage.md +++ b/gitbook/advanced/persistent-storage.md @@ -1,794 +1,303 @@ # Persistent Storage -RunCache provides robust persistent storage capabilities that allow your cache data to survive application restarts or browser refreshes. This guide explains how to use persistent storage effectively in your applications. - -## Understanding Persistent Storage - -By default, RunCache stores all data in memory, which means cache entries are lost when: -- Your Node.js application restarts -- The user refreshes or closes their browser -- The device loses power - -Persistent storage solves this problem by saving cache data to a more durable medium: -- File system (for Node.js applications) -- localStorage or IndexedDB (for browser applications) -- Custom storage backends (for specialized needs) +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 -RunCache uses storage adapters to abstract the details of different storage mechanisms. Three built-in adapters are provided: +Three adapters are built in: -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 +| 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` | -## Basic Setup +Each adapter throws from its constructor when used in the wrong environment. -### Configuring a Storage Adapter +### Options -To enable persistent storage, configure RunCache with a storage adapter: +All three accept these options. `FilesystemAdapter` also accepts `filePath`, which overrides the file location. -```typescript -import { RunCache, FilesystemAdapter } from 'run-cache'; +| 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 | -// For Node.js applications -RunCache.configure({ - storageAdapter: new FilesystemAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 300000 // 5 minutes - }) -}); - -// For browser applications with small data -RunCache.configure({ - storageAdapter: new LocalStorageAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 300000 // 5 minutes - }) -}); +```typescript +import { FilesystemAdapter, LocalStorageAdapter, IndexedDBAdapter } from 'run-cache'; -// For browser applications with larger data -RunCache.configure({ - storageAdapter: new IndexedDBAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 300000 // 5 minutes - }) -}); +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 }); ``` -Configuring an adapter immediately loads the data it already holds. `RunCache.configure()` returns a promise, so `await` it before reading from the cache: +## Attaching an Adapter ```typescript +import { RunCache, FilesystemAdapter } from 'run-cache'; + await RunCache.configure({ storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }) }); -// Entries persisted by a previous run are available now +// Entries saved by a previous run are available now const user = await RunCache.get('user:1'); ``` -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; `RunCache.shutdown()` also detaches the adapter after saving to it. - -### Manual Save and Load +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. -You can manually trigger save and load operations: +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. -```typescript -// Manually save cache state -await RunCache.saveToStorage(); - -// Manually load cache state -await RunCache.loadFromStorage(); -``` +## Saving -### Auto-Save Configuration +Nothing is saved unless you ask for it, in one of these ways. -Configure automatic saving at regular intervals: +### Manually ```typescript -// Save cache to storage every 5 minutes -RunCache.setupAutoSave(300000); - -// Disable auto-saving -RunCache.setupAutoSave(0); +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 ``` -## Storage Adapters in Detail - -### FilesystemAdapter +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. -The `FilesystemAdapter` stores cache data in the filesystem. This adapter is suitable for Node.js applications. +### Auto-save -#### Constructor Options +Either give the adapter an `autoSaveInterval`, which applies while that adapter is attached, or start an interval yourself: ```typescript -interface FilesystemAdapterConfig { - // Storage key/filename to use (default: "run-cache-data") - storageKey?: string; - - // Auto-save interval in milliseconds (default: 0, disabled) - autoSaveInterval?: number; - - // Whether to load cache automatically when adapter is initialized (default: true) - autoLoadOnInit?: boolean; - - // Custom file path (default: current working directory) - filePath?: string; -} +// Save every 5 minutes +await RunCache.setupAutoSave(300000); + +// Stop auto-saving +await RunCache.setupAutoSave(0); ``` -#### Example Usage +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. -```typescript -import { RunCache, FilesystemAdapter } from 'run-cache'; -import path from 'path'; +### On shutdown -// Basic usage -RunCache.configure({ - storageAdapter: new FilesystemAdapter() -}); +`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: -// With custom options -RunCache.configure({ - storageAdapter: new FilesystemAdapter({ - storageKey: 'my-app-cache', - filePath: path.join(process.cwd(), 'cache'), - autoSaveInterval: 300000, // 5 minutes - autoLoadOnInit: true - }) +```typescript +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }), + handleProcessSignals: true }); ``` -#### Storage Format - -All adapters store the same JSON document. The FilesystemAdapter writes it to a file with the following structure: - -```json -{ - "version": 1, - "timestamp": 1635789600000, - "entries": { - "key1": { - "value": "serialized-value-1", - "createdAt": 1635789000000, - "updatedAt": 1635789600000, - "ttl": 3600000, - "autoRefetch": false, - "accessCount": 4, - "lastAccessed": 1635789650000, - "tags": ["tag1", "tag2"], - "dependencies": ["dep1"] - } - }, - "config": { - "maxEntries": 1000, - "evictionPolicy": "LRU" - } -} -``` - -- Entries that have already expired are not written. -- Source functions are never written to storage. Their code is not persisted, and restored entries have no `sourceFn` (see [Restoring Data](#restoring-data)). -- 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. +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 +## 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.** +- **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.** Restored entries hold their last value but no `sourceFn`, so they cannot be refetched or auto-refetched until you call `set()` with a source function for them. - -### 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. +- **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. -#### Constructor Options +Values keep their type (see [Value Serialization](serialization-adapters.md)), and tags, dependencies, `autoRefetch` flags and access statistics are restored too. ```typescript -interface StorageAdapterConfig { - // Key to use in localStorage (default: "run-cache-data") - storageKey?: string; - - // Auto-save interval in milliseconds (default: 0, disabled) - autoSaveInterval?: number; - - // Whether to load cache automatically when adapter is initialized (default: true) - autoLoadOnInit?: boolean; -} -``` - -#### Example Usage - -```typescript -import { RunCache, LocalStorageAdapter } from 'run-cache'; - -// Basic usage -RunCache.configure({ - storageAdapter: new LocalStorageAdapter() -}); - -// With custom options -RunCache.configure({ - storageAdapter: new LocalStorageAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 60000, // 1 minute - autoLoadOnInit: true - }) +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 }); ``` -#### 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 +## Storage Format -The `IndexedDBAdapter` uses the browser's IndexedDB API to persist cache data. This adapter is suitable for larger datasets in web applications. +Every adapter stores the same JSON string: -#### Constructor Options - -```typescript -interface StorageAdapterConfig { - // Database and store name (default: "run-cache-data") - storageKey?: string; - - // Auto-save interval in milliseconds (default: 0, disabled) - autoSaveInterval?: number; - - // Whether to load cache automatically when adapter is initialized (default: true) - autoLoadOnInit?: boolean; +```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" } } ``` -#### Example Usage +`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. -```typescript -import { RunCache, IndexedDBAdapter } from 'run-cache'; - -// Basic usage -RunCache.configure({ - storageAdapter: new IndexedDBAdapter() -}); - -// With custom options -RunCache.configure({ - storageAdapter: new IndexedDBAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 300000, // 5 minutes - autoLoadOnInit: true - }) -}); -``` - -#### 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) +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 -You can create your own storage adapter by implementing the `StorageAdapter` interface: +Implement the `StorageAdapter` interface to store the cache anywhere: ```typescript interface StorageAdapter { save(data: string): Promise; - load(): 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 Storage Adapter - -Here's an example of a custom adapter that uses Redis for storage: +### Example: Redis ```typescript -import { StorageAdapter } from 'run-cache'; +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 }) { + constructor(options: { redisUrl: string; key?: string }) { this.redis = new Redis(options.redisUrl); - this.key = options.key || 'run-cache-data'; + this.key = options.key ?? 'run-cache-data'; } async save(data: string): Promise { - try { - await this.redis.set(this.key, data); - } catch (error) { - console.error('Failed to save cache to Redis:', error); - throw error; - } + await this.redis.set(this.key, data); } async load(): Promise { - try { - const data = await this.redis.get(this.key); - return data; - } catch (error) { - console.error('Failed to load cache from Redis:', error); - return null; - } + return this.redis.get(this.key); } - async close(): Promise { - await this.redis.quit(); + async clear(): Promise { + await this.redis.del(this.key); } } -// Usage -RunCache.configure({ - storageAdapter: new RedisStorageAdapter({ - redisUrl: 'redis://localhost:6379', - key: 'my-app-cache' - }) +await RunCache.configure({ + storageAdapter: new RedisStorageAdapter({ redisUrl: 'redis://localhost:6379', key: 'my-app-cache' }) }); ``` -### Example: S3 Storage Adapter +### Wrapping an adapter -Here's an example of a custom adapter that uses AWS S3 for storage: +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 { StorageAdapter } from 'run-cache'; -import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; +import { type StorageAdapter, LocalStorageAdapter } from 'run-cache'; -class S3StorageAdapter implements StorageAdapter { - private s3: S3Client; - private bucket: string; - private key: string; - - constructor(options: { bucket: string, key?: string, region?: string }) { - this.s3 = new S3Client({ region: options.region || 'us-east-1' }); - this.bucket = options.bucket; - this.key = options.key || 'run-cache-data.json'; - } +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 { - try { - const command = new PutObjectCommand({ - Bucket: this.bucket, - Key: this.key, - Body: data, - ContentType: 'application/json' - }); - - await this.s3.send(command); - } catch (error) { - console.error('Failed to save cache to S3:', error); - throw error; - } + await this.inner.save(await this.encode(data)); } async load(): Promise { - try { - const command = new GetObjectCommand({ - Bucket: this.bucket, - Key: this.key - }); - - const response = await this.s3.send(command); - const body = await response.Body?.transformToString(); - return body || null; - } catch (error) { - // If the object doesn't exist, return null instead of throwing - if ((error as any).name === 'NoSuchKey') { - return null; - } - - console.error('Failed to load cache from S3:', error); - return null; - } - } -} - -// Usage -RunCache.configure({ - storageAdapter: new S3StorageAdapter({ - bucket: 'my-cache-bucket', - key: 'my-app-cache.json', - region: 'us-west-2' - }) -}); -``` - -## Advanced Usage - -### Selective Persistence - -You might want to persist only certain types of cache entries. You can achieve this using middleware: - -```typescript -// Add middleware to control what gets persisted -RunCache.use(async (value, context, next) => { - // First, pass through to the actual cache operation - const result = await next(value); - - // For set operations, check if we should persist this entry - if (context.operation === 'set' && context.key.startsWith('temp:')) { - // Mark this entry as non-persistent - context.metadata = { - ...context.metadata, - persistent: false - }; - } - - return result; -}); - -// Add middleware to filter out non-persistent entries during save -RunCache.use(async (value, context, next) => { - if (context.operation === 'save' && value) { - // Parse the cache state - const cacheState = JSON.parse(value); - - // Filter out non-persistent entries - const filteredEntries = {}; - for (const [key, entry] of Object.entries(cacheState.entries)) { - if (entry.metadata?.persistent !== false) { - filteredEntries[key] = entry; - } - } - - // Update the cache state - cacheState.entries = filteredEntries; - - // Pass the filtered state to the next middleware - return next(JSON.stringify(cacheState)); - } - - return next(value); -}); -``` - -### Encryption - -You might want to encrypt sensitive data before persisting it: - -```typescript -import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; - -// Encryption key and IV (in a real app, store these securely) -const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || randomBytes(32); -const IV = process.env.ENCRYPTION_IV || randomBytes(16); - -// Add middleware for encryption -RunCache.use(async (value, context, next) => { - if (context.operation === 'save' && value) { - // Encrypt the data before saving - const cipher = createCipheriv('aes-256-cbc', ENCRYPTION_KEY, IV); - let encrypted = cipher.update(value, 'utf8', 'hex'); - encrypted += cipher.final('hex'); - - // Pass the encrypted data to the next middleware - return next(encrypted); - } else if (context.operation === 'load' && value) { - // Decrypt the data after loading - try { - const decipher = createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, IV); - let decrypted = decipher.update(value, 'hex', 'utf8'); - decrypted += decipher.final('utf8'); - - // Pass the decrypted data to the next middleware - return next(decrypted); - } catch (error) { - console.error('Failed to decrypt cache data:', error); - return next(null); - } + const data = await this.inner.load(); + return data === null ? null : this.decode(data); } - - return next(value); -}); -``` - -### Compression -For large cache data, you might want to compress it before persisting: - -```typescript -import { gzip, gunzip } from 'zlib'; -import { promisify } from 'util'; - -const gzipAsync = promisify(gzip); -const gunzipAsync = promisify(gunzip); - -// Add middleware for compression -RunCache.use(async (value, context, next) => { - if (context.operation === 'save' && value) { - // Compress the data before saving - const compressed = await gzipAsync(Buffer.from(value, 'utf8')); - - // Pass the compressed data to the next middleware - return next(compressed.toString('base64')); - } else if (context.operation === 'load' && value) { - // Decompress the data after loading - try { - const decompressed = await gunzipAsync(Buffer.from(value, 'base64')); - - // Pass the decompressed data to the next middleware - return next(decompressed.toString('utf8')); - } catch (error) { - console.error('Failed to decompress cache data:', error); - return next(null); - } + clear(): Promise { + return this.inner.clear(); } - - return next(value); -}); -``` - -## Best Practices - -### 1. Choose the Right 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 -- **Custom Adapter**: For specialized needs (Redis, S3, etc.) - -### 2. Set Appropriate Save Intervals - -Balance between data freshness and performance: - -```typescript -// For frequently changing data, save more often -RunCache.setupAutoSave(60000); // 1 minute - -// For relatively stable data, save less frequently -RunCache.setupAutoSave(3600000); // 1 hour -``` -### 3. 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 + // Pass the wrapped adapter's options through + get autoSaveInterval() { return this.inner.autoSaveInterval; } + get autoLoadOnInit() { return this.inner.autoLoadOnInit; } } -``` - -### 4. Implement Graceful Shutdown - -For Node.js applications, ensure cache is saved before shutting down. The simplest option is to let RunCache handle termination signals. It awaits `RunCache.shutdown()`, which saves to the storage adapter, and then lets the process exit as usual: -```typescript -await RunCache.configure({ handleProcessSignals: true }); -``` - -If your application already handles these signals, keep the option off and save from your own handlers: - -```typescript -// Handle process termination signals -process.on('SIGTERM', async () => { - console.log('Received SIGTERM, saving cache...'); - try { - await RunCache.saveToStorage(); - console.log('Cache saved successfully'); - process.exit(0); - } catch (error) { - console.error('Failed to save cache:', error); - process.exit(1); - } -}); - -process.on('SIGINT', async () => { - console.log('Received SIGINT, saving cache...'); - try { - await RunCache.saveToStorage(); - console.log('Cache saved successfully'); - process.exit(0); - } catch (error) { - console.error('Failed to save cache:', error); - process.exit(1); - } -}); -``` - -### 5. Consider Storage Size Limits - -Be mindful of storage limits, especially in browsers: - -```typescript -// Configure cache with size limits -RunCache.configure({ - maxEntries: 1000, // Limit to 1000 entries - evictionPolicy: EvictionPolicy.LRU, - storageAdapter: new LocalStorageAdapter() +// encryptString/decryptString are your own functions +await RunCache.configure({ + storageAdapter: new TransformingAdapter(new LocalStorageAdapter(), encryptString, decryptString) }); ``` -### 6. Implement Version Migration +The same wrapper can drop entries you do not want persisted: parse the JSON in `encode`, delete keys from `entries`, and stringify it again. -Handle version migrations gracefully: +## Best Practices -```typescript -// Add middleware for version migration -RunCache.use(async (value, context, next) => { - if (context.operation === 'load' && value) { - try { - const data = JSON.parse(value); - - // Check version and migrate if needed - if (data.version === '1.0.0') { - console.log('Migrating cache data from v1.0.0 to v1.1.0'); - - // Perform migration - // ... - - // Update version - data.version = '1.1.0'; - - // Return migrated data - return next(JSON.stringify(data)); - } - - // No migration needed - return next(value); - } catch (error) { - console.error('Failed to parse or migrate cache data:', error); - return next(null); - } - } - - return next(value); -}); -``` +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 -### 1. Browser Application with User-specific Data +### Browser application with per-user data ```typescript import { RunCache, LocalStorageAdapter } from 'run-cache'; -// Initialize with user-specific storage key -function initializeCache(userId) { - RunCache.configure({ +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 // 1 minute + autoSaveInterval: 60000 }) }); - - // Load data from storage - return RunCache.loadFromStorage(); -} -// Usage -async function onUserLogin(userId) { - await initializeCache(userId); - - // Cache is now loaded with user-specific data - const userData = await RunCache.get('user:profile'); - if (userData) { - // Use cached data - displayUserProfile(JSON.parse(userData)); - } else { - // Fetch and cache data - const profile = await fetchUserProfile(userId); - await RunCache.set({ - key: 'user:profile', - value: JSON.stringify(profile) - }); - displayUserProfile(profile); + const profile = await RunCache.get('user:profile'); + if (profile === undefined) { + await RunCache.set({ key: 'user:profile', value: await fetchUserProfile(userId), ttl: 3600000 }); } } - -// Handle logout -async function onUserLogout() { - // Save any pending changes - await RunCache.saveToStorage(); - - // Clear the cache - await RunCache.flush(); -} ``` -### 2. Node.js Application with Filesystem Storage +### Node.js service ```typescript -import { RunCache, FilesystemAdapter } from 'run-cache'; -import path from 'path'; - -// Initialize cache with filesystem storage -async function initializeCache() { - const cacheDir = path.join(process.cwd(), 'cache'); - - RunCache.configure({ - maxEntries: 10000, - evictionPolicy: EvictionPolicy.LRU, - storageAdapter: new FilesystemAdapter({ - storageKey: 'app-cache', - filePath: cacheDir, - autoSaveInterval: 300000 // 5 minutes - }) - }); - - try { - await RunCache.loadFromStorage(); - console.log('Cache loaded successfully'); - } catch (error) { - console.error('Failed to load cache:', error); - // Continue with empty cache - } -} +import { RunCache, FilesystemAdapter, EvictionPolicy } from 'run-cache'; -// Usage -async function startApplication() { - await initializeCache(); - - // Application startup logic - // ... -} - -startApplication(); +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 +}); ``` -### 3. Multi-environment Application +### Choosing an adapter by environment ```typescript -import { RunCache, LocalStorageAdapter, FilesystemAdapter } from 'run-cache'; - -// Initialize cache based on environment -async function initializeCache() { - const isBrowser = typeof window !== 'undefined'; - - if (isBrowser) { - // Browser environment - RunCache.configure({ - storageAdapter: new LocalStorageAdapter({ - storageKey: 'app-cache', - autoSaveInterval: 60000 // 1 minute - }) - }); - } else { - // Node.js environment - RunCache.configure({ - storageAdapter: new FilesystemAdapter({ - storageKey: 'app-cache', - autoSaveInterval: 300000 // 5 minutes - }) - }); - } - - try { - await RunCache.loadFromStorage(); - console.log('Cache loaded successfully'); - } catch (error) { - console.error('Failed to load cache:', error); - // Continue with empty cache - } -} +import { RunCache, FilesystemAdapter, IndexedDBAdapter, type StorageAdapter } from 'run-cache'; -// Usage -initializeCache(); +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 -Now that you understand persistent storage, explore these related topics: - -- [Storage Adapters](../api/storage-adapters.md) - Learn more about the built-in storage adapters -- [Middleware](./middleware.md) - Understand how to intercept and transform cache operations -- [Resource Management](./resource-management.md) - Learn about memory management and cleanup -- [Event System](./event-system.md) - Explore how to use events to monitor cache operations \ No newline at end of file +- [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/advanced/resource-management.md b/gitbook/advanced/resource-management.md index aeb0532..db7ef1e 100644 --- a/gitbook/advanced/resource-management.md +++ b/gitbook/advanced/resource-management.md @@ -21,7 +21,7 @@ You can limit the maximum number of entries in the cache using the `maxEntries` import { RunCache, EvictionPolicy } from 'run-cache'; // Configure cache with a maximum size of 1000 entries -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU // Least Recently Used }); @@ -41,13 +41,13 @@ RunCache supports three eviction policies: ```typescript // Configure with LRU policy -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU }); // Configure with LFU policy -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LFU }); @@ -59,7 +59,7 @@ You can monitor evictions by setting up a custom middleware: ```typescript // Add middleware to track evictions -RunCache.use(async (value, context, next) => { +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 @@ -82,7 +82,7 @@ Set appropriate TTL (Time-to-Live) values to automatically remove entries that a // Set cache entry with TTL await RunCache.set({ key: 'temporary-data', - value: JSON.stringify(largeDataObject), + value: largeDataObject, ttl: 3600000 // 1 hour }); ``` @@ -93,13 +93,13 @@ For immediate cleanup of specific entries or groups of entries: ```typescript // Delete specific entries -RunCache.delete('large-data-key'); +await RunCache.delete('large-data-key'); // Delete groups of entries using patterns -RunCache.delete('temp:*'); +await RunCache.delete('temp:*'); // Clear the entire cache -RunCache.flush(); +await RunCache.flush(); ``` ### Optimizing Value Size @@ -110,30 +110,30 @@ Minimize the size of cached values: // Bad - storing unnecessary data await RunCache.set({ key: 'user-profile', - value: JSON.stringify({ + 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: JSON.stringify({ + 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: JSON.stringify(completeUserHistory), + value: completeUserHistory, ttl: 3600000 // With shorter TTL }); ``` @@ -156,10 +156,10 @@ When you delete a cache entry or flush the cache, RunCache automatically cleans ```typescript // This automatically cleans up any timers for this entry -RunCache.delete('api-data'); +await RunCache.delete('api-data'); // This cleans up all timers for all entries -RunCache.flush(); +await RunCache.flush(); ``` ## Event Listener Management @@ -170,15 +170,15 @@ As your application grows, you might accumulate many event listeners. It's impor ```typescript // Remove all event listeners -RunCache.clearEventListeners(); +await RunCache.clearEventListeners(); // Remove listeners for a specific event type -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); // Remove listeners for a specific key -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'api-data' }); @@ -188,24 +188,23 @@ RunCache.clearEventListeners({ ```typescript // In a component or module -function initializeComponent() { +async function initializeComponent() { // Set up event listeners - RunCache.onKeyRefetch('component-data', handleRefetch); - + await RunCache.onKeyRefetch('component-data', handleRefetch); + // Return cleanup function - return () => { + return () => RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'component-data' }); - }; } // When component mounts -const cleanup = initializeComponent(); +const cleanup = await initializeComponent(); // When component unmounts -cleanup(); +await cleanup(); ``` ## Middleware Management @@ -214,7 +213,7 @@ Middleware functions can accumulate over time and impact performance. Clean them ```typescript // Remove all middleware -RunCache.clearMiddleware(); +await RunCache.clearMiddleware(); ``` ## Application Lifecycle Management @@ -249,7 +248,7 @@ You can also manually trigger a complete shutdown of RunCache: ```typescript // Manually shut down the cache -RunCache.shutdown(); +await RunCache.shutdown(); ``` The `shutdown` method: @@ -268,13 +267,13 @@ When using persistent storage adapters, it's important to manage storage resourc import { RunCache, FilesystemAdapter } from 'run-cache'; // Configure with storage adapter -RunCache.configure({ - storageAdapter: new FilesystemAdapter({ - storageKey: 'my-app-cache', - autoSaveInterval: 300000 // Save every 5 minutes - }) +await RunCache.configure({ + storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache' }) }); +// Save every 5 minutes +await RunCache.setupAutoSave(300000); + // Manual save await RunCache.saveToStorage(); @@ -282,7 +281,7 @@ await RunCache.saveToStorage(); await RunCache.loadFromStorage(); // Disable auto-save -RunCache.setupAutoSave(0); +await RunCache.setupAutoSave(0); ``` ### Storage Cleanup @@ -291,7 +290,7 @@ To clean up persistent storage: ```typescript // Clear cache and save empty state to storage -RunCache.flush(); +await RunCache.flush(); await RunCache.saveToStorage(); ``` @@ -305,21 +304,21 @@ Match TTL values to data volatility: // Frequently changing data await RunCache.set({ key: 'stock-prices', - value: JSON.stringify(prices), + value: prices, ttl: 60000 // 1 minute }); // Relatively stable data await RunCache.set({ key: 'product-catalog', - value: JSON.stringify(catalog), + value: catalog, ttl: 3600000 // 1 hour }); // Very stable data await RunCache.set({ key: 'app-configuration', - value: JSON.stringify(config), + value: config, ttl: 86400000 // 1 day }); ``` @@ -356,7 +355,7 @@ for (const id of userIds) { // More efficient - batch processing async function batchSetProfiles(profiles) { - const operations = Object.entries(profiles).map(([id, profile]) => + const operations = Object.entries(profiles).map(([id, profile]) => RunCache.set({ key: `user:${id}:profile`, value: profile }) ); await Promise.all(operations); @@ -387,22 +386,22 @@ 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: JSON.stringify(config) }); + await RunCache.set({ key: 'app:config', value: config }); } - + if (!hasGlobalData) { const globalData = await fetchGlobalData(); - await RunCache.set({ key: 'app:global-data', value: JSON.stringify(globalData) }); + await RunCache.set({ key: 'app:global-data', value: globalData }); } - + console.log('Cache warming complete'); } @@ -420,10 +419,10 @@ const handleRefetch = (event) => { console.log(`Refreshed: ${event.key}`); }; -RunCache.onRefetch(handleRefetch); +await RunCache.onRefetch(handleRefetch); // Later, when no longer needed -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, handler: handleRefetch // Remove specific handler }); @@ -434,21 +433,16 @@ RunCache.clearEventListeners({ Be careful with metadata that might create reference cycles: ```typescript -// Potentially problematic - circular reference +// Fails - non-string values are stored as JSON, which cannot represent cycles const obj = {}; obj.self = obj; -await RunCache.set({ - key: 'data', - value: 'value', - metadata: { circular: obj } // Creates a reference cycle -}); +await RunCache.set({ key: 'data', value: obj }); // throws: circular structure -// Better - avoid circular references +// Better - cache plain data without back-references await RunCache.set({ key: 'data', - value: 'value', - metadata: { id: 123, type: 'example' } // Simple metadata + value: { id: 123, type: 'example' } }); ``` @@ -458,15 +452,15 @@ Implement memory usage monitoring: ```typescript // Periodically check memory usage -setInterval(() => { +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'); - RunCache.delete('temp:*'); + await RunCache.delete('temp:*'); } } }, 60000); // Check every minute diff --git a/gitbook/advanced/serialization-adapters.md b/gitbook/advanced/serialization-adapters.md index f4e0d7e..d0905ae 100644 --- a/gitbook/advanced/serialization-adapters.md +++ b/gitbook/advanced/serialization-adapters.md @@ -1,579 +1,80 @@ -# Serialization Adapters +# Value Serialization -RunCache's serialization system allows you to cache complex JavaScript types that go beyond basic JSON serialization. This includes Date objects, Maps, Sets, RegExp, BigInt, class instances, and more. - -## Overview - -The serialization system consists of: - -- **Default Serialization**: Automatic JSON serialization for basic types -- **Custom Adapters**: Specialized serialization for complex types -- **Adapter Management**: Priority-based adapter selection -- **Extensibility**: Create your own adapters for custom types - -## Built-in Adapters - -RunCache includes adapters for common JavaScript types that aren't natively JSON serializable: - -### Date Serialization - -```typescript -import { DateSerializationAdapter } from 'run-cache'; - -// Add the Date adapter -RunCache.addSerializationAdapter(new DateSerializationAdapter()); - -// Cache Date objects directly -const event = { - id: 1, - name: 'Conference 2024', - startDate: new Date('2024-06-15T09:00:00Z'), - endDate: new Date('2024-06-17T17:00:00Z') -}; - -await RunCache.set({ key: 'event:1', value: event }); -const retrievedEvent = await RunCache.get('event:1'); - -// Dates are properly restored as Date objects -console.log(retrievedEvent.startDate instanceof Date); // true -console.log(retrievedEvent.startDate.getFullYear()); // 2024 -``` - -### Map Serialization - -```typescript -import { MapSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new MapSerializationAdapter()); - -// Cache Map objects -const userPreferences = new Map([ - ['theme', 'dark'], - ['language', 'en'], - ['notifications', { email: true, push: false }], - ['lastLogin', new Date()] -]); - -await RunCache.set({ key: 'preferences:123', value: userPreferences }); -const retrieved = await RunCache.get('preferences:123'); - -console.log(retrieved instanceof Map); // true -console.log(retrieved.get('theme')); // 'dark' -``` - -### Set Serialization - -```typescript -import { SetSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new SetSerializationAdapter()); - -// Cache Set objects -const userRoles = new Set(['user', 'editor', 'admin']); -const permissions = new Set([ - { action: 'read', resource: 'posts' }, - { action: 'write', resource: 'posts' }, - { action: 'delete', resource: 'posts' } -]); - -await RunCache.set({ key: 'roles:123', value: userRoles }); -await RunCache.set({ key: 'permissions:123', value: permissions }); - -const retrievedRoles = await RunCache.get('roles:123'); -console.log(retrievedRoles.has('admin')); // true -``` - -### RegExp Serialization - -```typescript -import { RegExpSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new RegExpSerializationAdapter()); - -// Cache RegExp objects -const validationRules = { - email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/i, - phone: /^\+?[\d\s\-\(\)]+$/, - username: /^[a-zA-Z0-9_]{3,20}$/ -}; - -await RunCache.set({ key: 'validation:rules', value: validationRules }); -const retrieved = await RunCache.get('validation:rules'); - -console.log(retrieved.email instanceof RegExp); // true -console.log(retrieved.email.test('user@example.com')); // true -``` - -### BigInt Serialization - -```typescript -import { BigIntSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new BigIntSerializationAdapter()); - -// Cache BigInt values -const largeNumbers = { - maxSafeInteger: BigInt(Number.MAX_SAFE_INTEGER), - customLarge: BigInt('123456789012345678901234567890'), - calculation: BigInt(2) ** BigInt(100) -}; - -await RunCache.set({ key: 'large:numbers', value: largeNumbers }); -const retrieved = await RunCache.get('large:numbers'); - -console.log(typeof retrieved.maxSafeInteger); // 'bigint' -console.log(retrieved.calculation > BigInt(2) ** BigInt(99)); // true -``` - -### URL Serialization - -```typescript -import { URLSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new URLSerializationAdapter()); - -// Cache URL objects -const endpoints = { - api: new URL('https://api.example.com/v1/users'), - cdn: new URL('https://cdn.example.com/assets'), - webhook: new URL('https://webhooks.example.com/callback?token=abc') -}; - -await RunCache.set({ key: 'endpoints', value: endpoints }); -const retrieved = await RunCache.get('endpoints'); - -console.log(retrieved.api instanceof URL); // true -console.log(retrieved.api.hostname); // 'api.example.com' -``` - -## Composite Serialization - -Use the composite adapter to handle multiple types automatically: - -```typescript -import { - CompositeSerializationAdapter, - DateSerializationAdapter, - MapSerializationAdapter, - SetSerializationAdapter, - RegExpSerializationAdapter, - createStandardSerializationAdapter -} from 'run-cache'; - -// Option 1: Manual composition -const composite = new CompositeSerializationAdapter(); -composite.addAdapter(new DateSerializationAdapter()); -composite.addAdapter(new MapSerializationAdapter()); -composite.addAdapter(new SetSerializationAdapter()); -composite.addAdapter(new RegExpSerializationAdapter()); - -RunCache.setSerializationAdapter(composite); - -// Option 2: Use the standard adapter (includes common types) -const standardAdapter = createStandardSerializationAdapter(); -RunCache.setSerializationAdapter(standardAdapter); - -// Now cache complex objects with mixed types -const complexData = { - createdAt: new Date(), - patterns: { - email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, - phone: /^\+?[\d\s\-\(\)]+$/ - }, - userRoles: new Set(['admin', 'editor']), - metadata: new Map([ - ['version', '1.0'], - ['lastModified', new Date()] - ]), - bigNumber: BigInt('999999999999999999999') -}; - -await RunCache.set({ key: 'complex:data', value: complexData }); -const retrieved = await RunCache.get('complex:data'); - -// All types are properly restored -console.log(retrieved.createdAt instanceof Date); -console.log(retrieved.patterns.email instanceof RegExp); -console.log(retrieved.userRoles instanceof Set); -console.log(retrieved.metadata instanceof Map); -console.log(typeof retrieved.bigNumber === 'bigint'); -``` - -## TypedArray Support - -Cache typed arrays like Int32Array, Float64Array, etc.: - -```typescript -import { createTypedArrayAdapters } from 'run-cache'; - -// Add all typed array adapters -const typedArrayAdapters = createTypedArrayAdapters(); -typedArrayAdapters.forEach(adapter => { - RunCache.addSerializationAdapter(adapter); -}); - -// Cache typed arrays -const audioData = new Float32Array([0.1, 0.2, 0.3, 0.4, 0.5]); -const imagePixels = new Uint8Array([255, 128, 64, 0, 255, 255]); -const bigInts = new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)]); - -await RunCache.set({ key: 'audio:sample', value: audioData }); -await RunCache.set({ key: 'image:pixels', value: imagePixels }); -await RunCache.set({ key: 'big:ints', value: bigInts }); - -const retrievedAudio = await RunCache.get('audio:sample'); -console.log(retrievedAudio instanceof Float32Array); // true -console.log(Array.from(retrievedAudio)); // [0.1, 0.2, 0.3, 0.4, 0.5] -``` - -## Custom Class Instances - -Serialize and deserialize custom class instances: +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 -// Define a class -class User { - constructor( - public id: number, - public name: string, - public email: string - ) {} - - greet(): string { - return `Hello, I'm ${this.name}`; - } - - isAdmin(): boolean { - return this.email.endsWith('@admin.com'); - } -} +import { RunCache } from 'run-cache'; -// Create a custom adapter for the User class -import { ClassInstanceSerializationAdapter } from 'run-cache'; +await RunCache.set({ key: 'user:1', value: { name: 'Ada', roles: ['admin'] } }); -const userAdapter = new ClassInstanceSerializationAdapter( - User, - 'User', - // Custom constructor function - (data: any) => new User(data.id, data.name, data.email) -); - -RunCache.addSerializationAdapter(userAdapter); - -// Cache User instances -const user = new User(1, 'John Doe', 'john@admin.com'); -await RunCache.set({ key: 'user:1', value: user }); - -const retrievedUser = await RunCache.get('user:1'); -console.log(retrievedUser instanceof User); // true -console.log(retrievedUser.greet()); // "Hello, I'm John Doe" -console.log(retrievedUser.isAdmin()); // true +const user = await RunCache.get<{ name: string; roles: string[] }>('user:1'); +console.log(user); // { name: 'Ada', roles: ['admin'] }, an object, not a string ``` -## Buffer Support (Node.js) +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). -For Node.js environments, cache Buffer objects: +## What round-trips -```typescript -import { BufferSerializationAdapter } from 'run-cache'; +Because the conversion is plain JSON, a value comes back exactly as it went in only if JSON can represent it: -if (typeof Buffer !== 'undefined') { - RunCache.addSerializationAdapter(new BufferSerializationAdapter()); -} +| 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 | -// Cache binary data -const imageBuffer = Buffer.from('binary image data', 'base64'); -const textBuffer = Buffer.from('Hello, World!', 'utf8'); +Setting `value: undefined` is the same as not passing a value, so `set()` then needs a `sourceFn`. -await RunCache.set({ key: 'image:thumbnail', value: imageBuffer }); -await RunCache.set({ key: 'text:content', value: textBuffer }); +## Storing types JSON cannot represent -const retrievedImage = await RunCache.get('image:thumbnail'); -console.log(Buffer.isBuffer(retrievedImage)); // true -``` - -## Creating Custom Adapters - -Create your own serialization adapters for custom types: +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 -import { SerializationAdapter } from 'run-cache'; +// Date +await RunCache.set({ key: 'last-sync', value: new Date().toISOString() }); +const lastSync = new Date((await RunCache.get('last-sync')) as string); -// Example: Adapter for a custom Money class -class Money { - constructor( - public amount: number, - public currency: 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][]); - toString(): string { - return `${this.amount} ${this.currency}`; - } -} - -class MoneySerializationAdapter implements SerializationAdapter { - serialize(value: Money): string { - return JSON.stringify({ - __type__: 'Money', - amount: value.amount, - currency: value.currency - }); - } - - deserialize(serialized: string): Money { - try { - const parsed = JSON.parse(serialized); - if (parsed.__type__ === 'Money') { - return new Money(parsed.amount, parsed.currency); - } - } catch (error) { - // Handle parsing errors - } - throw new Error('Invalid Money serialization'); - } - - canHandle(value: any): boolean { - return value instanceof Money; - } -} - -// Register the custom adapter -RunCache.addSerializationAdapter(new MoneySerializationAdapter()); - -// Use the custom type -const price = new Money(99.99, 'USD'); -await RunCache.set({ key: 'product:price', value: price }); - -const retrievedPrice = await RunCache.get('product:price'); -console.log(retrievedPrice instanceof Money); // true -console.log(retrievedPrice.toString()); // "99.99 USD" +// BigInt +await RunCache.set({ key: 'balance', value: (10n ** 20n).toString() }); +const balance = BigInt((await RunCache.get('balance')) as string); ``` -## Advanced Adapter Patterns - -### Generic Adapters - -Create adapters that work with multiple related types: +A small helper keeps the conversion in one place: ```typescript -class DateTimeAdapter implements SerializationAdapter { - serialize(value: Date | string): string { - const dateValue = value instanceof Date ? value : new Date(value); - return JSON.stringify({ - __type__: 'DateTime', - iso: dateValue.toISOString(), - timestamp: dateValue.getTime() - }); - } - - deserialize(serialized: string): Date { - const parsed = JSON.parse(serialized); - if (parsed.__type__ === 'DateTime') { - return new Date(parsed.iso); - } - throw new Error('Invalid DateTime serialization'); - } - - canHandle(value: any): boolean { - return value instanceof Date || - (typeof value === 'string' && !isNaN(Date.parse(value))); - } +interface Session { + userId: string; + expiresAt: Date; } -``` - -### Conditional Serialization - -Adapters that apply different strategies based on data: - -```typescript -class SmartObjectAdapter implements SerializationAdapter { - serialize(value: any): string { - // Detect the type and apply appropriate serialization - if (value instanceof Date) { - return this.serializeDate(value); - } else if (value instanceof Map) { - return this.serializeMap(value); - } else { - return JSON.stringify(value); - } - } - - deserialize(serialized: string): any { - const parsed = JSON.parse(serialized); - - switch (parsed.__type__) { - case 'Date': - return new Date(parsed.value); - case 'Map': - return new Map(parsed.entries); - default: - return parsed; - } - } - canHandle(value: any): boolean { - return value !== null && typeof value === 'object'; - } - - private serializeDate(date: Date): string { - return JSON.stringify({ __type__: 'Date', value: date.toISOString() }); - } - - private serializeMap(map: Map): string { - return JSON.stringify({ __type__: 'Map', entries: Array.from(map.entries()) }); - } +async function setSession(key: string, session: Session) { + await RunCache.set({ key, value: { ...session, expiresAt: session.expiresAt.toISOString() } }); } -``` - -## Adapter Priority and Management - -Adapters are processed in the order they're added (most recent first): - -```typescript -// Higher priority adapters are added last -RunCache.addSerializationAdapter(new GenericObjectAdapter()); // Lower priority -RunCache.addSerializationAdapter(new DateSerializationAdapter()); // Higher priority -RunCache.addSerializationAdapter(new CustomUserAdapter()); // Highest priority - -// The most specific adapter that can handle the type will be used -``` - -### Managing Adapters - -```typescript -// Clear all custom adapters -RunCache.clearSerializationAdapters(); - -// Add a new set of adapters -const adapters = [ - new DateSerializationAdapter(), - new MapSerializationAdapter(), - new CustomUserAdapter() -]; - -adapters.forEach(adapter => RunCache.addSerializationAdapter(adapter)); -``` - -## Performance Considerations - -### Serialization Overhead -- Simple adapters (Date, RegExp): < 5% overhead -- Complex adapters (Map, Set): < 15% overhead -- Custom class instances: 10-25% overhead depending on complexity - -### Best Practices - -1. **Use Specific Adapters**: More specific adapters are generally faster -2. **Minimize Adapter Chain**: Don't add unnecessary adapters -3. **Cache Adapter Results**: For frequently serialized types -4. **Test Performance**: Benchmark critical paths with your specific data - -```typescript -// Performance testing example -async function benchmarkSerialization( - key: string, - value: T, - iterations: number = 1000 -): Promise { - const start = performance.now(); - - for (let i = 0; i < iterations; i++) { - await RunCache.set({ key: `${key}:${i}`, value }); - await RunCache.get(`${key}:${i}`); - } - - const end = performance.now(); - return end - start; +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) }; } - -// Test different serialization approaches -const simpleObject = { id: 1, name: 'test' }; -const complexObject = { - date: new Date(), - map: new Map([['key', 'value']]), - regex: /test/g -}; - -const simpleTime = await benchmarkSerialization('simple', simpleObject); -const complexTime = await benchmarkSerialization('complex', complexObject); - -console.log(`Simple: ${simpleTime}ms, Complex: ${complexTime}ms`); ``` -## Error Handling +## Serialization and middleware -Handle serialization failures gracefully: - -```typescript -class SafeSerializationAdapter implements SerializationAdapter { - serialize(value: any): string { - try { - return JSON.stringify({ - __type__: 'Safe', - data: this.deepSerialize(value) - }); - } catch (error) { - console.warn('Serialization failed:', error); - return JSON.stringify({ - __type__: 'Safe', - data: null, - error: error.message - }); - } - } - - deserialize(serialized: string): any { - try { - const parsed = JSON.parse(serialized); - if (parsed.__type__ === 'Safe') { - if (parsed.error) { - console.warn('Cached value had serialization error:', parsed.error); - return null; - } - return parsed.data; - } - } catch (error) { - console.warn('Deserialization failed:', error); - return null; - } - } - - canHandle(value: any): boolean { - return true; // Fallback adapter - } - - private deepSerialize(obj: any): any { - // Custom serialization logic with error handling - if (obj === null || typeof obj !== 'object') { - return obj; - } - - if (obj instanceof Date) { - return { __date__: obj.toISOString() }; - } - - if (Array.isArray(obj)) { - return obj.map(item => this.deepSerialize(item)); - } - - const result: any = {}; - for (const [key, value] of Object.entries(obj)) { - try { - result[key] = this.deepSerialize(value); - } catch (error) { - console.warn(`Failed to serialize property ${key}:`, error); - result[key] = null; - } - } - return result; - } -} -``` +[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 -- Learn about [Type Validation](type-validation.md) for runtime type checking -- Explore [Performance Optimization](../guides/performance.md) for caching strategies -- See the [API Reference](../api/serialization-system.md) for complete adapter interfaces -- Check out [Best Practices](../guides/best-practices.md) for serialization patterns \ No newline at end of file +- [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/advanced/tag-invalidation.md b/gitbook/advanced/tag-invalidation.md index f0fe351..f7692d6 100644 --- a/gitbook/advanced/tag-invalidation.md +++ b/gitbook/advanced/tag-invalidation.md @@ -20,21 +20,21 @@ When setting a cache entry, you can assign one or more tags to it: // Set a cache entry with tags await RunCache.set({ key: 'user:1:profile', - value: JSON.stringify({ name: 'John Doe', email: 'john@example.com' }), + 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: JSON.stringify({ theme: 'dark', notifications: true }), + value: { theme: 'dark', notifications: true }, tags: ['user:1', 'settings'] }); // Entry for a different user await RunCache.set({ key: 'user:2:profile', - value: JSON.stringify({ name: 'Jane Smith', email: 'jane@example.com' }), + value: { name: 'Jane Smith', email: 'jane@example.com' }, tags: ['user:2', 'profile'] }); ``` @@ -50,7 +50,7 @@ To invalidate all cache entries with a specific tag: ```typescript // Invalidate all entries tagged with 'user:1' -RunCache.invalidateByTag('user:1'); +await RunCache.invalidateByTag('user:1'); ``` This would invalidate both `user:1:profile` and `user:1:settings`, but not `user:2:profile`. @@ -59,7 +59,7 @@ Similarly: ```typescript // Invalidate all profile entries -RunCache.invalidateByTag('profile'); +await RunCache.invalidateByTag('profile'); ``` This would invalidate both `user:1:profile` and `user:2:profile`, but not `user:1:settings`. @@ -74,19 +74,19 @@ You can create hierarchical relationships using tag naming conventions: // Set cache entries with hierarchical tags await RunCache.set({ key: 'product:1:details', - value: JSON.stringify({ name: 'Product 1', price: 99.99 }), + value: { name: 'Product 1', price: 99.99 }, tags: ['product', 'product:1', 'product:details'] }); await RunCache.set({ key: 'product:1:reviews', - value: JSON.stringify([{ rating: 5, text: 'Great product!' }]), + value: [{ rating: 5, text: 'Great product!' }], tags: ['product', 'product:1', 'product:reviews'] }); await RunCache.set({ key: 'product:2:details', - value: JSON.stringify({ name: 'Product 2', price: 149.99 }), + value: { name: 'Product 2', price: 149.99 }, tags: ['product', 'product:2', 'product:details'] }); ``` @@ -95,13 +95,13 @@ This allows for flexible invalidation: ```typescript // Invalidate all product data -RunCache.invalidateByTag('product'); +await RunCache.invalidateByTag('product'); // Invalidate all data for product 1 -RunCache.invalidateByTag('product:1'); +await RunCache.invalidateByTag('product:1'); // Invalidate details for all products -RunCache.invalidateByTag('product:details'); +await RunCache.invalidateByTag('product:details'); ``` ### Role-based Tags @@ -112,19 +112,19 @@ Tags can represent roles or categories: // Set cache entries with role-based tags await RunCache.set({ key: 'user:1:dashboard', - value: JSON.stringify({ widgets: [...] }), + value: { widgets: [...] }, tags: ['user:1', 'dashboard', 'admin-view'] }); await RunCache.set({ key: 'user:2:dashboard', - value: JSON.stringify({ widgets: [...] }), + value: { widgets: [...] }, tags: ['user:2', 'dashboard', 'customer-view'] }); await RunCache.set({ key: 'global:admin-settings', - value: JSON.stringify({ settings: [...] }), + value: { settings: [...] }, tags: ['global', 'admin-view'] }); ``` @@ -133,10 +133,10 @@ This allows for role-based invalidation: ```typescript // Invalidate all admin views when admin settings change -RunCache.invalidateByTag('admin-view'); +await RunCache.invalidateByTag('admin-view'); // Invalidate all dashboards -RunCache.invalidateByTag('dashboard'); +await RunCache.invalidateByTag('dashboard'); ``` ### Version Tags @@ -147,13 +147,13 @@ Tags can be used for version-based invalidation: // Set cache entries with version tags await RunCache.set({ key: 'app:config', - value: JSON.stringify({ theme: 'light', features: [...] }), + value: { theme: 'light', features: [...] }, tags: ['config', 'v1.2.3'] }); await RunCache.set({ key: 'app:translations', - value: JSON.stringify({ en: {...}, es: {...} }), + value: { en: {...}, es: {...} }, tags: ['translations', 'v1.2.3'] }); ``` @@ -162,12 +162,12 @@ When a new version is deployed: ```typescript // Invalidate all cache entries from the previous version -RunCache.invalidateByTag('v1.2.3'); +await RunCache.invalidateByTag('v1.2.3'); // Set new cache entries with the new version tag await RunCache.set({ key: 'app:config', - value: JSON.stringify({ theme: 'dark', features: [...] }), + value: { theme: 'dark', features: [...] }, tags: ['config', 'v1.3.0'] }); ``` @@ -178,17 +178,17 @@ RunCache provides events to monitor tag invalidations: ```typescript // Global tag invalidation event -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); }); // Specific key tag invalidation -RunCache.onKeyTagInvalidation("user:1:profile", (event) => { +await RunCache.onKeyTagInvalidation("user:1:profile", (event) => { console.log(`User profile was invalidated by tag: ${event.tag}`); }); // Pattern-based tag invalidation events -RunCache.onKeyTagInvalidation("user:*:profile", (event) => { +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -205,7 +205,7 @@ Combine tags with TTL for time-based invalidation: // Set cache entry with tags and TTL await RunCache.set({ key: 'weather:nyc', - value: JSON.stringify({ temp: 72, conditions: 'sunny' }), + value: { temp: 72, conditions: 'sunny' }, tags: ['weather', 'location:nyc'], ttl: 3600000 // 1 hour }); @@ -213,7 +213,7 @@ await RunCache.set({ // Set cache entry with tags and TTL await RunCache.set({ key: 'weather:la', - value: JSON.stringify({ temp: 85, conditions: 'clear' }), + value: { temp: 85, conditions: 'clear' }, tags: ['weather', 'location:la'], ttl: 3600000 // 1 hour }); @@ -223,10 +223,10 @@ This allows for both time-based expiration and manual invalidation: ```typescript // Invalidate all weather data regardless of TTL -RunCache.invalidateByTag('weather'); +await RunCache.invalidateByTag('weather'); // Invalidate just NYC weather data -RunCache.invalidateByTag('location:nyc'); +await RunCache.invalidateByTag('location:nyc'); ``` ### Tags with Source Functions @@ -240,7 +240,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/stocks/AAPL'); const data = await response.json(); - return JSON.stringify(data); + return data; }, tags: ['stock', 'tech-stock'], ttl: 60000, // 1 minute @@ -252,7 +252,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/stocks/MSFT'); const data = await response.json(); - return JSON.stringify(data); + return data; }, tags: ['stock', 'tech-stock'], ttl: 60000, // 1 minute @@ -264,7 +264,7 @@ This allows for both automatic refreshing and manual invalidation: ```typescript // Force refresh all tech stock data immediately -RunCache.invalidateByTag('tech-stock'); +await RunCache.invalidateByTag('tech-stock'); ``` ### Tags with Dependencies @@ -275,21 +275,21 @@ Combine tags with dependencies for complex invalidation strategies: // Primary data with tags await RunCache.set({ key: 'products', - value: JSON.stringify([...]), + value: [...], tags: ['product-data', 'catalog'] }); // Dependent data with tags await RunCache.set({ key: 'featured-products', - value: JSON.stringify([...]), + value: [...], dependencies: ['products'], tags: ['product-data', 'featured'] }); await RunCache.set({ key: 'product-recommendations', - value: JSON.stringify([...]), + value: [...], dependencies: ['products', 'user-preferences'], tags: ['product-data', 'personalized'] }); @@ -299,13 +299,13 @@ This provides multiple ways to invalidate: ```typescript // Option 1: Invalidate by dependency (cascades to dependents) -RunCache.invalidateByDependency('products'); +await RunCache.invalidateByDependency('products'); // Option 2: Invalidate by tag (direct invalidation) -RunCache.invalidateByTag('product-data'); +await RunCache.invalidateByTag('product-data'); // Option 3: Invalidate just personalized content -RunCache.invalidateByTag('personalized'); +await RunCache.invalidateByTag('personalized'); ``` ## Advanced Tag Patterns @@ -317,19 +317,19 @@ 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; } @@ -337,7 +337,7 @@ function generateUserTags(user) { const user = await fetchUser(1); await RunCache.set({ key: `user:${user.id}:profile`, - value: JSON.stringify(user), + value: user, tags: generateUserTags(user) }); ``` @@ -348,7 +348,7 @@ Use tags to implement prefetching strategies: ```typescript // Listen for tag invalidations -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { if (event.tag === 'product-data') { // Prefetch related data that might be needed soon prefetchRelatedData(); @@ -360,7 +360,7 @@ async function prefetchRelatedData() { const relatedData = await fetchRelatedData(); await RunCache.set({ key: 'related-products', - value: JSON.stringify(relatedData), + value: relatedData, tags: ['product-data', 'related'] }); } @@ -374,7 +374,7 @@ Implement conditional tag invalidation logic: async function conditionalInvalidate(tag, condition) { if (await condition()) { console.log(`Invalidating tag: ${tag}`); - RunCache.invalidateByTag(tag); + await RunCache.invalidateByTag(tag); return true; } console.log(`Condition not met, tag ${tag} not invalidated`); @@ -471,26 +471,26 @@ Cache and invalidate user-specific data: // Store user data with tags await RunCache.set({ key: `user:${userId}:profile`, - value: JSON.stringify(profile), + value: profile, tags: [`user:${userId}`] }); await RunCache.set({ key: `user:${userId}:preferences`, - value: JSON.stringify(preferences), + value: preferences, tags: [`user:${userId}`] }); await RunCache.set({ key: `user:${userId}:activity`, - value: JSON.stringify(activity), + value: activity, tags: [`user:${userId}`] }); // When user data changes -function handleUserDataChange(userId) { +async function handleUserDataChange(userId) { // Invalidate all data for this user - RunCache.invalidateByTag(`user:${userId}`); + await RunCache.invalidateByTag(`user:${userId}`); } ``` @@ -502,24 +502,24 @@ Cache and invalidate content by category: // Store content with category tags await RunCache.set({ key: `article:${articleId}`, - value: JSON.stringify(article), + value: article, tags: ['content', `category:${article.category}`, `author:${article.authorId}`] }); // Invalidation scenarios -function handleCategoryUpdate(category) { +async function handleCategoryUpdate(category) { // Invalidate all content in this category - RunCache.invalidateByTag(`category:${category}`); + await RunCache.invalidateByTag(`category:${category}`); } -function handleAuthorUpdate(authorId) { +async function handleAuthorUpdate(authorId) { // Invalidate all content by this author - RunCache.invalidateByTag(`author:${authorId}`); + await RunCache.invalidateByTag(`author:${authorId}`); } -function handleGlobalContentUpdate() { +async function handleGlobalContentUpdate() { // Invalidate all content - RunCache.invalidateByTag('content'); + await RunCache.invalidateByTag('content'); } ``` @@ -531,42 +531,42 @@ Cache API responses with appropriate tags: 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) { - return JSON.parse(cachedResponse); + 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: JSON.stringify(data), + value: data, tags, ttl: options.ttl || 300000 // 5 minutes default }); - + return data; } @@ -574,8 +574,8 @@ async function cachedApiRequest(endpoint, params = {}, options = {}) { const userData = await cachedApiRequest('users/profile', { userId: 123 }); // When user data changes -function invalidateUserApiCache(userId) { - RunCache.invalidateByTag(`user:${userId}`); +async function invalidateUserApiCache(userId) { + await RunCache.invalidateByTag(`user:${userId}`); } ``` @@ -587,7 +587,7 @@ Implement multi-level caching with tags: // L1 cache (short TTL, frequently accessed) await RunCache.set({ key: 'dashboard:summary', - value: JSON.stringify(summary), + value: summary, tags: ['dashboard', 'summary', 'l1-cache'], ttl: 60000 // 1 minute }); @@ -595,18 +595,18 @@ await RunCache.set({ // L2 cache (longer TTL, less frequently accessed) await RunCache.set({ key: 'dashboard:details', - value: JSON.stringify(details), + value: details, tags: ['dashboard', 'details', 'l2-cache'], ttl: 3600000 // 1 hour }); // Selective invalidation -function invalidateL1Cache() { - RunCache.invalidateByTag('l1-cache'); +async function invalidateL1Cache() { + await RunCache.invalidateByTag('l1-cache'); } -function invalidateDashboard() { - RunCache.invalidateByTag('dashboard'); +async function invalidateDashboard() { + await RunCache.invalidateByTag('dashboard'); } ``` diff --git a/gitbook/advanced/type-validation.md b/gitbook/advanced/type-validation.md index d540af8..c17e9f5 100644 --- a/gitbook/advanced/type-validation.md +++ b/gitbook/advanced/type-validation.md @@ -1,627 +1,79 @@ -# Type Validation +# Type Safety -RunCache provides a comprehensive type validation system that allows you to enforce data integrity through runtime type checking. This ensures that cached values match expected types and schemas. +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. -## Overview - -The type validation system includes: - -- **Built-in Validators**: Common primitive and complex type validators -- **Schema Validation**: Object structure and property type validation -- **Custom Validators**: Create validators for your specific types -- **Runtime Checking**: Validate data on cache operations -- **Type Guards**: TypeScript type narrowing support - -## Basic Validators - -### Primitive Type Validators - -```typescript -import { - StringValidator, - NumberValidator, - BooleanValidator, - ArrayValidator -} from 'run-cache'; - -// Validate primitive types -console.log(StringValidator.validate('hello')); // true -console.log(StringValidator.validate(123)); // false - -console.log(NumberValidator.validate(42)); // true -console.log(NumberValidator.validate('42')); // false - -console.log(BooleanValidator.validate(true)); // true -console.log(BooleanValidator.validate(1)); // false - -console.log(ArrayValidator.validate([1, 2, 3])); // true -console.log(ArrayValidator.validate('not array')); // false -``` - -### Date and Special Type Validators - -```typescript -import { DateValidator, RegExpValidator } from 'run-cache'; - -console.log(DateValidator.validate(new Date())); // true -console.log(DateValidator.validate('2023-12-25')); // false - -console.log(RegExpValidator.validate(/pattern/g)); // true -console.log(RegExpValidator.validate('pattern')); // false -``` - -## Schema Validation - -### Object Schema Validation - -Create complex validators for object structures: +## What the types guarantee ```typescript -import { ValidatorUtils, SchemaValidator } from 'run-cache'; +import { RunCache } from 'run-cache'; interface User { id: number; name: string; - email: string; - age?: number; - active: boolean; } -// Create a schema validator for User -const userValidator = ValidatorUtils.object({ - id: NumberValidator, - name: StringValidator, - email: ValidatorUtils.string(email => email.includes('@')), // Custom string validator - age: ValidatorUtils.optional(NumberValidator), // Optional property - active: BooleanValidator -}); - -// Test validation -const validUser = { - id: 1, - name: 'John Doe', - email: 'john@example.com', - age: 30, - active: true -}; - -const invalidUser = { - id: '1', // Wrong type (string instead of number) - name: 'John Doe', - email: 'invalid-email', // Invalid email format - active: true - // Missing required fields -}; +// The value is checked against User when you set it +await RunCache.set({ key: 'user:1', value: { id: 1, name: 'Ada' } }); -console.log(userValidator.validate(validUser)); // true -console.log(userValidator.validate(invalidUser)); // false +// 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; ``` -### Nested Object Validation - -Validate complex nested structures: - -```typescript -interface Address { - street: string; - city: string; - zipCode: string; - country: string; -} - -interface UserProfile { - user: User; - address: Address; - preferences: { - theme: 'light' | 'dark'; - notifications: boolean; - language: string; - }; -} - -const addressValidator = ValidatorUtils.object({ - street: StringValidator, - city: StringValidator, - zipCode: ValidatorUtils.string(zip => /^\d{5}(-\d{4})?$/.test(zip)), - country: StringValidator -}); +`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). -const preferencesValidator = ValidatorUtils.object({ - theme: ValidatorUtils.union(['light', 'dark']), - notifications: BooleanValidator, - language: ValidatorUtils.string(lang => lang.length === 2) -}); +What the types do **not** guarantee: -const userProfileValidator = ValidatorUtils.object({ - user: userValidator, - address: addressValidator, - preferences: preferencesValidator -}); +- 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). -// Use with caching -await RunCache.set({ - key: 'profile:123', - value: userProfile, - validator: userProfileValidator -}); -``` - -### Array Validation - -Validate arrays and their contents: - -```typescript -// Array of specific type -const numberArrayValidator = ValidatorUtils.array(NumberValidator); -const userArrayValidator = ValidatorUtils.array(userValidator); - -console.log(numberArrayValidator.validate([1, 2, 3])); // true -console.log(numberArrayValidator.validate([1, '2', 3])); // false - -// Mixed array validation -const mixedArrayValidator = ValidatorUtils.array( - ValidatorUtils.union([StringValidator, NumberValidator]) -); - -console.log(mixedArrayValidator.validate(['hello', 123, 'world'])); // true -console.log(mixedArrayValidator.validate(['hello', true])); // false -``` +RunCache does not export runtime validators, and no cache method accepts a validator option. -## Union and Conditional Types +## Adding a runtime check -### Union Type Validation +When a value may come from outside your control, check it after reading. A type guard keeps the check and the type together: ```typescript -// Union of primitive types -type Status = 'pending' | 'approved' | 'rejected'; -const statusValidator = ValidatorUtils.union(['pending', 'approved', 'rejected']); - -// Union of complex types -interface SuccessResponse { - success: true; - data: any; -} - -interface ErrorResponse { - success: false; - error: string; -} - -type ApiResponse = SuccessResponse | ErrorResponse; - -const successValidator = ValidatorUtils.object({ - success: ValidatorUtils.literal(true), - data: ValidatorUtils.any() -}); - -const errorValidator = ValidatorUtils.object({ - success: ValidatorUtils.literal(false), - error: StringValidator -}); - -const apiResponseValidator = ValidatorUtils.union([successValidator, errorValidator]); - -// Test union validation -const successResponse: SuccessResponse = { success: true, data: { users: [] } }; -const errorResponse: ErrorResponse = { success: false, error: 'Not found' }; - -console.log(apiResponseValidator.validate(successResponse)); // true -console.log(apiResponseValidator.validate(errorResponse)); // true -console.log(apiResponseValidator.validate({ success: true })); // false (missing data) -``` - -### Conditional Validation - -Create validators that depend on other properties: - -```typescript -const conditionalValidator = new SchemaValidator( - (value): value is any => { - if (!value || typeof value !== 'object') return false; - - // If type is 'user', require name and email - if (value.type === 'user') { - return typeof value.name === 'string' && - typeof value.email === 'string' && - value.email.includes('@'); - } - - // If type is 'product', require name and price - if (value.type === 'product') { - return typeof value.name === 'string' && - typeof value.price === 'number' && - value.price > 0; - } - - return false; - }, - 'ConditionalEntity' -); - -// Test conditional validation -console.log(conditionalValidator.validate({ - type: 'user', - name: 'John', - email: 'john@example.com' -})); // true - -console.log(conditionalValidator.validate({ - type: 'product', - name: 'Laptop', - price: 999.99 -})); // true - -console.log(conditionalValidator.validate({ - type: 'user', - name: 'John' - // Missing email -})); // false -``` - -## Custom Validators - -### Creating Custom Validators - -```typescript -import { TypeValidator, SchemaValidator } from 'run-cache'; - -// Custom validator for email addresses -const emailValidator = new SchemaValidator( - (value): value is string => { - return typeof value === 'string' && - /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); - }, - 'Email' -); - -// Custom validator for positive numbers -const positiveNumberValidator = new SchemaValidator( - (value): value is number => { - return typeof value === 'number' && value > 0; - }, - 'PositiveNumber' -); - -// Custom validator for non-empty arrays -function createNonEmptyArrayValidator(itemValidator: TypeValidator): TypeValidator { - return new SchemaValidator( - (value): value is T[] => { - return Array.isArray(value) && - value.length > 0 && - value.every(item => itemValidator.validate(item)); - }, - `NonEmptyArray<${itemValidator.name}>` - ); -} - -const nonEmptyStringArrayValidator = createNonEmptyArrayValidator(StringValidator); -``` - -### Generic Validators - -Create reusable validators for generic types: - -```typescript -// Generic API response validator -function createApiResponseValidator(dataValidator: TypeValidator): TypeValidator<{ - success: boolean; - data: T; - message: string; -}> { - return ValidatorUtils.object({ - success: BooleanValidator, - data: dataValidator, - message: StringValidator - }); -} - -// Usage -const userApiResponseValidator = createApiResponseValidator(userValidator); -const productApiResponseValidator = createApiResponseValidator( - ValidatorUtils.array(ValidatorUtils.object({ - id: NumberValidator, - name: StringValidator, - price: positiveNumberValidator - })) -); -``` - -## Integration with Caching - -### Validation on Set Operations - -```typescript -// Configure cache with validation -await RunCache.set({ - key: 'user:123', - value: userData, - validator: userValidator, - validateOnSet: true // Validate before caching -}); - -// This will throw an error if userData doesn't match the schema -``` - -### Validation on Get Operations - -```typescript -// Configure global validation -RunCache.configure({ - validateOnGet: true, - validationFailureAction: 'warn' // 'throw', 'warn', or 'ignore' -}); - -// Validate when retrieving from cache -const user = await RunCache.get('user:123'); -// If cached data is invalid, action depends on validationFailureAction setting -``` - -### Type-Safe Cache Operations - -```typescript -// Create a typed cache with validation -class ValidatedCache { - constructor( - private prefix: string, - private validator: TypeValidator - ) {} - - async set(id: string, value: T): Promise { - if (!this.validator.validate(value)) { - throw new Error(`Invalid ${this.validator.name}: ${JSON.stringify(value)}`); - } - - await RunCache.set({ - key: `${this.prefix}:${id}`, - value, - validator: this.validator - }); - } - - async get(id: string): Promise { - const value = await RunCache.get(`${this.prefix}:${id}`); - - if (value !== undefined && !this.validator.validate(value)) { - console.warn(`Cached ${this.validator.name} failed validation:`, value); - return undefined; - } - - return value as T; - } -} - -// Usage -const userCache = new ValidatedCache('users', userValidator); -const productCache = new ValidatedCache('products', productValidator); - -await userCache.set('123', validUser); -const retrievedUser = await userCache.get('123'); // Guaranteed to be valid or undefined -``` - -## Advanced Validation Patterns - -### Transformation Validators - -Validators that can transform data during validation: - -```typescript -class TransformingValidator implements TypeValidator { - constructor( - public name: string, - private transformFn: (input: TInput) => TOutput | null, - private baseValidator: TypeValidator - ) {} - - validate(value: any): value is TOutput { - if (!this.baseValidator.validate(value)) { - return false; - } - - const transformed = this.transformFn(value); - return transformed !== null; - } - - apply(value: TInput): TOutput | null { - return this.transformFn(value); - } -} - -// Example: String to Date transformer -const dateStringValidator = new TransformingValidator( - 'DateString', - (str: string) => { - const date = new Date(str); - return isNaN(date.getTime()) ? null : date; - }, - StringValidator -); -``` - -### Async Validators - -Validators that perform asynchronous checks: - -```typescript -class AsyncValidator { - constructor( - public name: string, - private asyncCheck: (value: T) => Promise - ) {} - - async validate(value: any): Promise { - try { - return await this.asyncCheck(value); - } catch (error) { - console.warn(`Async validation failed for ${this.name}:`, error); - return false; - } - } -} - -// Example: Validate user exists in database -const userExistsValidator = new AsyncValidator<{ id: number }>( - 'UserExists', - async (user) => { - // Check if user exists in database - const exists = await checkUserExists(user.id); - return exists; - } -); - -// Usage with caching -async function setUserWithValidation(user: User) { - const isValid = await userExistsValidator.validate(user); - if (!isValid) { - throw new Error('User does not exist in database'); - } - - await RunCache.set({ key: `user:${user.id}`, value: user }); +interface User { + id: number; + name: string; } -``` - -## Performance Considerations - -### Validation Overhead - -- Simple validators: < 1ms per validation -- Complex object validators: 1-5ms depending on structure -- Array validators: Linear with array size -- Async validators: Depends on async operation -### Optimization Strategies - -```typescript -// Cache validation results for expensive checks -const validationCache = new Map(); - -function createCachedValidator( - baseValidator: TypeValidator, - keyFn: (value: T) => string -): TypeValidator { - return new SchemaValidator( - (value): value is T => { - const key = keyFn(value); - - if (validationCache.has(key)) { - return validationCache.get(key)!; - } - - const isValid = baseValidator.validate(value); - validationCache.set(key, isValid); - return isValid; - }, - `Cached${baseValidator.name}` +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' ); } -// Usage -const cachedUserValidator = createCachedValidator( - userValidator, - (user) => `user:${user.id}:${JSON.stringify(user)}` -); -``` - -### Selective Validation - -Only validate when necessary: - -```typescript -// Validate only in development or for critical data -const shouldValidate = process.env.NODE_ENV === 'development' || isCriticalData; - -if (shouldValidate) { - if (!validator.validate(data)) { - throw new Error('Validation failed'); +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; } - -await RunCache.set({ key, value: data }); ``` -## Error Handling and Debugging - -### Detailed Validation Errors - -```typescript -class DetailedValidator implements TypeValidator { - constructor( - public name: string, - private checks: Array<{ - name: string; - validate: (value: any) => boolean; - }> - ) {} - - validate(value: any): value is T { - const errors: string[] = []; - - for (const check of this.checks) { - if (!check.validate(value)) { - errors.push(check.name); - } - } - - if (errors.length > 0) { - console.warn(`Validation failed for ${this.name}:`, errors); - return false; - } - - return true; - } -} +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. -// Usage -const detailedUserValidator = new DetailedValidator('User', [ - { name: 'has id', validate: (v) => typeof v?.id === 'number' }, - { name: 'has name', validate: (v) => typeof v?.name === 'string' }, - { name: 'has valid email', validate: (v) => typeof v?.email === 'string' && v.email.includes('@') }, - { name: 'has active status', validate: (v) => typeof v?.active === 'boolean' } -]); -``` +## Wildcard reads -### Validation Debugging +A key containing `*` returns an array of every matching value, so narrow the result before treating it as a single value: ```typescript -// Debug validation failures -function debugValidation(validator: TypeValidator, value: any): void { - console.group(`Validating ${validator.name}`); - console.log('Value:', value); - console.log('Type:', typeof value); - console.log('Is Array:', Array.isArray(value)); - console.log('Constructor:', value?.constructor?.name); - - const isValid = validator.validate(value); - console.log('Result:', isValid ? '✅ Valid' : '❌ Invalid'); - - if (!isValid && typeof value === 'object' && value !== null) { - console.log('Properties:', Object.keys(value)); - console.log('Property types:', - Object.fromEntries( - Object.entries(value).map(([k, v]) => [k, typeof v]) - ) - ); - } - - console.groupEnd(); -} - -// Usage -debugValidation(userValidator, suspiciousUserData); +const result = await RunCache.get('user:*'); +const users = Array.isArray(result) ? result.filter(isUser) : []; ``` -## Best Practices - -1. **Start Simple**: Begin with basic validators and gradually add complexity -2. **Compose Validators**: Build complex validators from simpler ones -3. **Cache Results**: Cache expensive validation results when possible -4. **Fail Fast**: Validate early to catch errors quickly -5. **Provide Clear Errors**: Use descriptive validation error messages -6. **Test Validators**: Write tests for your custom validators -7. **Document Schemas**: Document your data structures and validation rules - ## Next Steps -- Learn about [Serialization Adapters](serialization-adapters.md) for custom types -- Explore [Best Practices](../guides/best-practices.md) for validation patterns -- See the [API Reference](../api/serialization-system.md) for complete validator interfaces -- Check out [Performance Optimization](../guides/performance.md) for validation performance \ No newline at end of file +- [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/api/events.md b/gitbook/api/events.md index 1234ac1..cd2687d 100644 --- a/gitbook/api/events.md +++ b/gitbook/api/events.md @@ -24,7 +24,7 @@ import { RunCache, EVENT } from 'run-cache'; ## Event Objects -Each event type has a corresponding event object with specific properties: +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 @@ -114,7 +114,7 @@ Global event listeners are triggered for all cache entries that match the specif Registers a callback for all expiry events. ```typescript -RunCache.onExpiry(callback: (event: ExpiryEvent) => void): void +await RunCache.onExpiry(callback: (event: ExpiryEvent) => void): Promise ``` **Parameters:** @@ -123,7 +123,7 @@ RunCache.onExpiry(callback: (event: ExpiryEvent) => void): void **Example:** ```typescript -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); }); ``` @@ -133,7 +133,7 @@ RunCache.onExpiry((event) => { Registers a callback for all refetch events. ```typescript -RunCache.onRefetch(callback: (event: RefetchEvent) => void): void +await RunCache.onRefetch(callback: (event: RefetchEvent) => void): Promise ``` **Parameters:** @@ -142,7 +142,7 @@ RunCache.onRefetch(callback: (event: RefetchEvent) => void): void **Example:** ```typescript -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); }); ``` @@ -152,7 +152,7 @@ RunCache.onRefetch((event) => { Registers a callback for all refetch failure events. ```typescript -RunCache.onRefetchFailure(callback: (event: RefetchFailureEvent) => void): void +await RunCache.onRefetchFailure(callback: (event: RefetchFailureEvent) => void): Promise ``` **Parameters:** @@ -161,8 +161,8 @@ RunCache.onRefetchFailure(callback: (event: RefetchFailureEvent) => void): void **Example:** ```typescript -RunCache.onRefetchFailure((event) => { - console.error(`Failed to refresh cache key ${event.key}:`, event.error.message); +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}:`, event.error); }); ``` @@ -171,7 +171,7 @@ RunCache.onRefetchFailure((event) => { Registers a callback for all tag invalidation events. ```typescript -RunCache.onTagInvalidation(callback: (event: TagInvalidationEvent) => void): void +await RunCache.onTagInvalidation(callback: (event: TagInvalidationEvent) => void): Promise ``` **Parameters:** @@ -180,7 +180,7 @@ RunCache.onTagInvalidation(callback: (event: TagInvalidationEvent) => void): voi **Example:** ```typescript -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -190,7 +190,7 @@ RunCache.onTagInvalidation((event) => { Registers a callback for all dependency invalidation events. ```typescript -RunCache.onDependencyInvalidation(callback: (event: DependencyInvalidationEvent) => void): void +await RunCache.onDependencyInvalidation(callback: (event: DependencyInvalidationEvent) => void): Promise ``` **Parameters:** @@ -199,7 +199,7 @@ RunCache.onDependencyInvalidation(callback: (event: DependencyInvalidationEvent) **Example:** ```typescript -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`Cache key ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -213,7 +213,7 @@ Key-specific event listeners are triggered only for cache entries with keys that Registers a callback for expiry events for a specific key or pattern. ```typescript -RunCache.onKeyExpiry(key: string, callback: (event: ExpiryEvent) => void): void +await RunCache.onKeyExpiry(key: string, callback: (event: ExpiryEvent) => void): Promise ``` **Parameters:** @@ -224,12 +224,12 @@ RunCache.onKeyExpiry(key: string, callback: (event: ExpiryEvent) => void): void ```typescript // Specific key -RunCache.onKeyExpiry("api-data", (event) => { +await RunCache.onKeyExpiry("api-data", (event) => { console.log(`API data cache expired`); }); // Pattern matching -RunCache.onKeyExpiry("user:*:profile", (event) => { +await RunCache.onKeyExpiry("user:*:profile", (event) => { console.log(`User profile ${event.key} expired`); }); ``` @@ -239,7 +239,7 @@ RunCache.onKeyExpiry("user:*:profile", (event) => { Registers a callback for refetch events for a specific key or pattern. ```typescript -RunCache.onKeyRefetch(key: string, callback: (event: RefetchEvent) => void): void +await RunCache.onKeyRefetch(key: string, callback: (event: RefetchEvent) => void): Promise ``` **Parameters:** @@ -250,12 +250,12 @@ RunCache.onKeyRefetch(key: string, callback: (event: RefetchEvent) => void): voi ```typescript // Specific key -RunCache.onKeyRefetch("weather-data", (event) => { +await RunCache.onKeyRefetch("weather-data", (event) => { console.log(`Weather data was refreshed`); }); // Pattern matching -RunCache.onKeyRefetch("api:*:data", (event) => { +await RunCache.onKeyRefetch("api:*:data", (event) => { console.log(`API data ${event.key} was refreshed`); }); ``` @@ -265,7 +265,7 @@ RunCache.onKeyRefetch("api:*:data", (event) => { Registers a callback for refetch failure events for a specific key or pattern. ```typescript -RunCache.onKeyRefetchFailure(key: string, callback: (event: RefetchFailureEvent) => void): void +await RunCache.onKeyRefetchFailure(key: string, callback: (event: RefetchFailureEvent) => void): Promise ``` **Parameters:** @@ -276,13 +276,13 @@ RunCache.onKeyRefetchFailure(key: string, callback: (event: RefetchFailureEvent) ```typescript // Specific key -RunCache.onKeyRefetchFailure("api-data", (event) => { - console.error(`API data refresh failed:`, event.error.message); +await RunCache.onKeyRefetchFailure("api-data", (event) => { + console.error(`API data refresh failed:`, event.error); }); // Pattern matching -RunCache.onKeyRefetchFailure("api:*", (event) => { - console.error(`API data ${event.key} refresh failed:`, event.error.message); +await RunCache.onKeyRefetchFailure("api:*", (event) => { + console.error(`API data ${event.key} refresh failed:`, event.error); }); ``` @@ -291,7 +291,7 @@ RunCache.onKeyRefetchFailure("api:*", (event) => { Registers a callback for tag invalidation events for a specific key or pattern. ```typescript -RunCache.onKeyTagInvalidation(key: string, callback: (event: TagInvalidationEvent) => void): void +await RunCache.onKeyTagInvalidation(key: string, callback: (event: TagInvalidationEvent) => void): Promise ``` **Parameters:** @@ -302,12 +302,12 @@ RunCache.onKeyTagInvalidation(key: string, callback: (event: TagInvalidationEven ```typescript // Specific key -RunCache.onKeyTagInvalidation("user:1:profile", (event) => { +await RunCache.onKeyTagInvalidation("user:1:profile", (event) => { console.log(`User profile was invalidated by tag: ${event.tag}`); }); // Pattern matching -RunCache.onKeyTagInvalidation("user:*:profile", (event) => { +await RunCache.onKeyTagInvalidation("user:*:profile", (event) => { console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -317,7 +317,7 @@ RunCache.onKeyTagInvalidation("user:*:profile", (event) => { Registers a callback for dependency invalidation events for a specific key or pattern. ```typescript -RunCache.onKeyDependencyInvalidation(key: string, callback: (event: DependencyInvalidationEvent) => void): void +await RunCache.onKeyDependencyInvalidation(key: string, callback: (event: DependencyInvalidationEvent) => void): Promise ``` **Parameters:** @@ -328,12 +328,12 @@ RunCache.onKeyDependencyInvalidation(key: string, callback: (event: DependencyIn ```typescript // Specific key -RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { +await RunCache.onKeyDependencyInvalidation("dashboard:main", (event) => { console.log(`Main dashboard was invalidated due to dependency on: ${event.dependencyKey}`); }); // Pattern matching -RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { +await RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { console.log(`Dashboard ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -345,7 +345,7 @@ RunCache.onKeyDependencyInvalidation("dashboard:*", (event) => { Removes event listeners based on the specified options. ```typescript -RunCache.clearEventListeners(options?: { +await RunCache.clearEventListeners(options?: { event?: EventName; key?: string; }): Promise @@ -366,20 +366,20 @@ An exact key only clears listeners registered for that exact key. Wildcard liste ```typescript // Remove all event listeners -RunCache.clearEventListeners(); +await RunCache.clearEventListeners(); // Remove all expiry event listeners -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); // Remove all listeners for a specific key -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ key: "api-data" }); // Remove specific event listeners for a key -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: "api-data" }); @@ -392,23 +392,17 @@ Removing a single handler is not supported; clear the event (and key) it was reg ## Event Metadata -You can attach custom metadata to cache entries, which will be included in event objects: +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 -// Set cache entry with metadata -await RunCache.set({ - key: 'api-data', - value: JSON.stringify({ results: [...] }), - metadata: { - source: 'external-api', - version: '1.0', - timestamp: Date.now() - } -}); +const entryInfo = new Map(); + +await RunCache.set({ key: 'api-data', value: { results: [] } }); +entryInfo.set('api-data', { source: 'external-api', version: '1.0' }); -// Access metadata in event handlers -RunCache.onKeyExpiry('api-data', (event) => { - console.log(`API data expired. Source: ${event.metadata.source}, Version: ${event.metadata.version}`); +await RunCache.onKeyExpiry('api-data', (event) => { + const info = entryInfo.get(event.key); + console.log(`API data expired. Source: ${info?.source}, Version: ${info?.version}`); }); ``` @@ -418,23 +412,23 @@ RunCache.onKeyExpiry('api-data', (event) => { ```typescript // Set up logging for all major events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { logger.info(`Cache expired: ${event.key}`); }); -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { logger.info(`Cache refreshed: ${event.key}`); }); -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { logger.error(`Cache refresh failed: ${event.key}`, event.error); }); -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { logger.info(`Cache invalidated by tag: ${event.key} (tag: ${event.tag})`); }); -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { logger.info(`Cache invalidated by dependency: ${event.key} (depends on: ${event.dependencyKey})`); }); ``` @@ -443,52 +437,84 @@ RunCache.onDependencyInvalidation((event) => { ```typescript // Set up retry logic with exponential backoff -RunCache.onRefetchFailure((event) => { - const retryCount = (event.metadata?.retryCount || 0) + 1; - +// 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, { - metadata: { retryCount } - }); + 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(() => { - // Set up event listener for cache refreshes - RunCache.onKeyRefetch(`user:${userId}:profile`, () => { - // Update UI when profile is refreshed - RunCache.get(`user:${userId}:profile`) - .then(data => data && setProfile(JSON.parse(data))); - }); - - // Initial data fetch - RunCache.get(`user:${userId}:profile`) - .then(data => data && setProfile(JSON.parse(data))); - - // Clean up listener on unmount + 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 () => { - RunCache.clearEventListeners({ - event: EVENT.REFETCH, - key: `user:${userId}:profile` - }); + active = false; // ignore a load that finishes after cleanup + unsubscribe(); }; }, [userId]); - + // Render profile... } ``` @@ -505,18 +531,18 @@ let metrics = { dependencyInvalidationCount: 0 }; -RunCache.onExpiry(() => metrics.expiryCount++); -RunCache.onRefetch(() => metrics.refetchCount++); -RunCache.onRefetchFailure(() => metrics.refetchFailureCount++); -RunCache.onTagInvalidation(() => metrics.tagInvalidationCount++); -RunCache.onDependencyInvalidation(() => metrics.dependencyInvalidationCount++); +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, @@ -536,12 +562,12 @@ Event handlers should be fast and non-blocking: ```typescript // Good - lightweight handler -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache expired: ${event.key}`); }); // Avoid - heavy processing in handler -RunCache.onExpiry(async (event) => { +await RunCache.onExpiry(async (event) => { // DON'T do this - blocks the event loop await heavyProcessing(); await networkRequest(); @@ -564,7 +590,7 @@ To react to errors inside a specific listener, handle them there: ```typescript // Good - error handling -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { try { processRefetchEvent(event); } catch (error) { @@ -579,12 +605,12 @@ Use specific key patterns to minimize unnecessary event processing: ```typescript // Too broad - triggers for all keys -RunCache.onKeyExpiry('*', (event) => { +await RunCache.onKeyExpiry('*', (event) => { // This will run for EVERY expiry }); // Better - more specific pattern -RunCache.onKeyExpiry('api:*', (event) => { +await RunCache.onKeyExpiry('api:*', (event) => { // This will only run for API-related expirations }); ``` @@ -595,23 +621,22 @@ Remove event listeners when they're no longer needed: ```typescript // In a component or module initialization -function initializeModule() { +async function initializeModule() { // Set up event listeners - RunCache.onKeyRefetch('module-data', handleRefetch); - + await RunCache.onKeyRefetch('module-data', handleRefetch); + // Return cleanup function - return () => { + return () => RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'module-data' }); - }; } // Later, when shutting down -const cleanup = initializeModule(); +const cleanup = await initializeModule(); // When module is unloaded -cleanup(); +await cleanup(); ``` ## Next Steps diff --git a/gitbook/api/run-cache.md b/gitbook/api/run-cache.md index ba88213..33f2ca0 100644 --- a/gitbook/api/run-cache.md +++ b/gitbook/api/run-cache.md @@ -40,20 +40,20 @@ await RunCache.configure({ Gets the current cache configuration. -**Returns:** `CacheConfig` - The current configuration object +**Returns:** `Promise` - A copy of the current configuration **Example:** ```typescript -const config = RunCache.getConfig(); -console.log(config); // { maxEntries: 1000, evictionPolicy: "lru", debug: true } +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. Supports any serializable JavaScript type. +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:** @@ -69,9 +69,6 @@ Sets a cache entry with the specified options. Supports any serializable JavaScr - `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. - - `metadata?`: `any` - Custom metadata to associate with the entry - - `validator?`: `TypeValidator` - Optional type validator for runtime checking - - `validateOnSet?`: `boolean` - Validate value before caching (default: false) **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. @@ -105,11 +102,11 @@ await RunCache.set({ key: 'user:1', value: user }); // Array caching with types await RunCache.set({ key: 'scores', value: [95, 87, 92] }); -// With TTL and types -await RunCache.set({ - key: 'last-update', - value: new Date(), - ttl: 60000 +// 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 @@ -130,16 +127,12 @@ await RunCache.set<{ temperature: number; humidity: number }>({ autoRefetch: true }); -// With tags, dependencies, and validation -import { userValidator } from './validators'; - +// With tags and dependencies await RunCache.set({ key: 'user:1:profile', value: user, tags: ['user:1', 'profile'], - dependencies: ['user:1:session'], - validator: userValidator, - validateOnSet: true + dependencies: ['user:1:session'] }); ``` @@ -240,40 +233,38 @@ Removes a cache entry or entries matching a pattern. - `key`: `string` - The key to delete, or a pattern with wildcards -**Returns:** `void` +**Returns:** `Promise` - `true` if at least one entry was deleted **Example:** ```typescript // Delete a specific entry -RunCache.delete('greeting'); +await RunCache.delete('greeting'); // Delete entries matching a pattern -RunCache.delete('user:1:*'); +await RunCache.delete('user:1:*'); ``` ### `flush()` Removes all cache entries. -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript // Clear the entire cache -RunCache.flush(); +await RunCache.flush(); ``` -### `refetch(key, options?)` +### `refetch(key)` -Manually refreshes a cache entry or entries matching a pattern. +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 -- `options?`: `Object` - Optional refresh options - - `metadata?`: `any` - Custom metadata to include in refetch events **Returns:** `Promise` - `true` if the entry (or, for a pattern, at least one matching entry) was refreshed @@ -294,8 +285,6 @@ await RunCache.refetch('api-data'); // Refresh entries matching a pattern await RunCache.refetch('user:*:profile'); -// Refresh with metadata -await RunCache.refetch('api-data', { metadata: { reason: 'manual' } }); ``` ## Tag Operations @@ -308,13 +297,13 @@ Invalidates all cache entries with the specified tag. - `tag`: `string` - The tag to invalidate -**Returns:** `void` +**Returns:** `Promise` - `true` if at least one entry was invalidated **Example:** ```typescript // Invalidate all entries with the 'user:1' tag -RunCache.invalidateByTag('user:1'); +await RunCache.invalidateByTag('user:1'); ``` ## Dependency Operations @@ -367,14 +356,14 @@ Registers a callback for all expiry events. **Parameters:** -- `callback`: `(event: ExpiryEvent) => void` - Function to call when any entry expires +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry expires -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache key ${event.key} expired`); }); ``` @@ -386,18 +375,18 @@ Registers a callback for expiry events for a specific key or pattern. **Parameters:** - `key`: `string` - The key or pattern to watch -- `callback`: `(event: ExpiryEvent) => void` - Function to call when matching entries expire +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries expire -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onKeyExpiry('api-data', (event) => { +await RunCache.onKeyExpiry('api-data', (event) => { console.log('API data expired'); }); -RunCache.onKeyExpiry('user:*:profile', (event) => { +await RunCache.onKeyExpiry('user:*:profile', (event) => { console.log(`User profile ${event.key} expired`); }); ``` @@ -408,14 +397,14 @@ Registers a callback for all refetch events. **Parameters:** -- `callback`: `(event: RefetchEvent) => void` - Function to call when any entry is refreshed +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is refreshed -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache key ${event.key} was refreshed`); }); ``` @@ -427,14 +416,14 @@ Registers a callback for refetch events for a specific key or pattern. **Parameters:** - `key`: `string` - The key or pattern to watch -- `callback`: `(event: RefetchEvent) => void` - Function to call when matching entries are refreshed +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are refreshed -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onKeyRefetch('weather-data', (event) => { +await RunCache.onKeyRefetch('weather-data', (event) => { console.log('Weather data was refreshed'); }); ``` @@ -445,14 +434,14 @@ Registers a callback for all refetch failure events. **Parameters:** -- `callback`: `(event: RefetchFailureEvent) => void` - Function to call when any refresh fails +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any refresh fails -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`Failed to refresh ${event.key}:`, event.error); }); ``` @@ -464,15 +453,15 @@ Registers a callback for refetch failure events for a specific key or pattern. **Parameters:** - `key`: `string` - The key or pattern to watch -- `callback`: `(event: RefetchFailureEvent) => void` - Function to call when matching refreshes fail +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching refreshes fail -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onKeyRefetchFailure('api-data', (event) => { - console.error('API data refresh failed:', event.error); +await RunCache.onKeyRefetchFailure('api-data', (event) => { + console.error(`API data refresh failed: ${event.key}`, event.error); }); ``` @@ -482,14 +471,14 @@ Registers a callback for all tag invalidation events. **Parameters:** -- `callback`: `(event: TagInvalidationEvent) => void` - Function to call when any entry is invalidated by tag +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is invalidated by tag -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -501,14 +490,14 @@ Registers a callback for tag invalidation events for a specific key or pattern. **Parameters:** - `key`: `string` - The key or pattern to watch -- `callback`: `(event: TagInvalidationEvent) => void` - Function to call when matching entries are invalidated by tag +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are invalidated by tag -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onKeyTagInvalidation('user:*:profile', (event) => { +await RunCache.onKeyTagInvalidation('user:*:profile', (event) => { console.log(`User profile ${event.key} was invalidated by tag: ${event.tag}`); }); ``` @@ -519,14 +508,14 @@ Registers a callback for all dependency invalidation events. **Parameters:** -- `callback`: `(event: DependencyInvalidationEvent) => void` - Function to call when any entry is invalidated by dependency +- `callback`: `(event: EventParam) => void | Promise` - Function to call when any entry is invalidated by dependency -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onDependencyInvalidation((event) => { +await RunCache.onDependencyInvalidation((event) => { console.log(`${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -538,14 +527,14 @@ Registers a callback for dependency invalidation events for a specific key or pa **Parameters:** - `key`: `string` - The key or pattern to watch -- `callback`: `(event: DependencyInvalidationEvent) => void` - Function to call when matching entries are invalidated by dependency +- `callback`: `(event: EventParam) => void | Promise` - Function to call when matching entries are invalidated by dependency -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript -RunCache.onKeyDependencyInvalidation('dashboard:*', (event) => { +await RunCache.onKeyDependencyInvalidation('dashboard:*', (event) => { console.log(`Dashboard ${event.key} was invalidated due to dependency on: ${event.dependencyKey}`); }); ``` @@ -560,22 +549,22 @@ Removes event listeners based on the specified options. - `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` otherwise +**Returns:** `Promise` - `true` if at least one listener was removed, `false` if there was nothing to remove. **Example:** ```typescript // Remove all event listeners -RunCache.clearEventListeners(); +await RunCache.clearEventListeners(); // Remove all expiry listeners -RunCache.clearEventListeners({ event: EVENT.EXPIRE }); +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); // Remove listeners for a specific key -RunCache.clearEventListeners({ key: 'api-data' }); +await RunCache.clearEventListeners({ key: 'api-data' }); // Remove specific event listeners for a key -RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'api-data' }); +await RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'api-data' }); ``` ## Middleware @@ -588,20 +577,20 @@ Adds a middleware function to intercept and transform cache operations. - `middleware`: `MiddlewareFunction` - The middleware function to add -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript // Add a logging middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`${context.operation} operation for key: ${context.key}`); return next(value); }); // Add an encryption middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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); @@ -615,13 +604,13 @@ RunCache.use(async (value, context, next) => { Removes all middleware functions. -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript // Remove all middleware -RunCache.clearMiddleware(); +await RunCache.clearMiddleware(); ``` ## Storage Operations @@ -634,16 +623,16 @@ Configures automatic saving to persistent storage. - `interval`: `number` - The interval in milliseconds between saves (0 to disable) -**Returns:** `void` +**Returns:** `Promise` **Example:** ```typescript // Save cache to storage every 5 minutes -RunCache.setupAutoSave(300000); +await RunCache.setupAutoSave(300000); // Disable auto-saving -RunCache.setupAutoSave(0); +await RunCache.setupAutoSave(0); ``` ### `saveToStorage()` @@ -682,7 +671,7 @@ Creates a typed cache interface that provides type-safe operations for a specifi - `T` - The type of values that will be cached -**Returns:** `TypedCacheInterface` - A typed cache interface instance +**Returns:** A typed wrapper around the same global cache. See [Typed Cache Interface](typed-cache-interface.md). **Example:** @@ -704,19 +693,19 @@ 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 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 } +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 | undefined -const product = await productCache.get('product:456'); // Product | undefined +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 @@ -755,7 +744,7 @@ Enum for cache eviction policies: ```typescript import { RunCache, EvictionPolicy } from 'run-cache'; -RunCache.configure({ +await RunCache.configure({ evictionPolicy: EvictionPolicy.LRU }); ``` @@ -775,130 +764,11 @@ Enum for event types: ```typescript import { RunCache, EVENT } from 'run-cache'; -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.EXPIRE }); ``` ## Type Definitions -### `CacheConfig` - -Configuration options for RunCache: - -```typescript -interface CacheConfig { - maxEntries?: number; - evictionPolicy?: EvictionPolicy; - debug?: boolean; - storageAdapter?: StorageAdapter; -} -``` - -### `ExpiryEvent` - -Event object for expiry events: - -```typescript -interface ExpiryEvent { - key: string; - ttl: number; - updatedAt: number; - metadata?: any; -} -``` - -### `RefetchEvent` - -Event object for refetch events: - -```typescript -interface RefetchEvent { - key: string; - metadata?: any; -} -``` - -### `RefetchFailureEvent` - -Event object for refetch failure events: - -```typescript -interface RefetchFailureEvent { - key: string; - error: Error; - metadata?: any; -} -``` - -### `TagInvalidationEvent` - -Event object for tag invalidation events: - -```typescript -interface TagInvalidationEvent { - key: string; - tag: string; - metadata?: any; -} -``` - -### `DependencyInvalidationEvent` - -Event object for dependency invalidation events: - -```typescript -interface DependencyInvalidationEvent { - key: string; - dependencyKey: string; - metadata?: any; -} -``` - -### `MiddlewareFunction` - -Type definition for middleware functions: - -```typescript -type MiddlewareFunction = ( - value: string | undefined, - context: MiddlewareContext, - next: (value: string | undefined) => Promise -) => Promise; -``` - -### `MiddlewareContext` - -Context object passed to middleware functions: - -```typescript -interface MiddlewareContext { - operation: 'get' | 'set' | 'delete' | 'refetch' | 'evict'; - key: string; - metadata?: any; -} -``` - -### `StorageAdapter` - -Interface for storage adapters: - -```typescript -interface StorageAdapter { - save(data: string): Promise; - load(): Promise; -} -``` - -### `StorageAdapterConfig` - -Configuration options for storage adapters: - -```typescript -interface StorageAdapterConfig { - storageKey?: string; - autoSaveInterval?: number; - autoLoadOnInit?: boolean; - filePath?: string; // FilesystemAdapter only -} -``` \ No newline at end of file +The exported types (`CacheConfig`, `EventParam`, `EventName`, `MiddlewareFunction`, `MiddlewareContext`, `StorageAdapter`, `StorageAdapterConfig`) and the `EvictionPolicy` enum are documented in [Types](types.md). diff --git a/gitbook/api/serialization-system.md b/gitbook/api/serialization-system.md deleted file mode 100644 index 1073c76..0000000 --- a/gitbook/api/serialization-system.md +++ /dev/null @@ -1,672 +0,0 @@ -# Serialization System API - -The RunCache serialization system provides extensible type serialization for caching complex JavaScript types. This API reference covers all serialization interfaces, adapters, and utilities. - -## Core Interfaces - -### `SerializationAdapter` - -The base interface for creating custom serialization adapters. - -```typescript -interface SerializationAdapter { - serialize(value: T): string; - deserialize(serialized: string): T; - canHandle(value: any): boolean; -} -``` - -**Methods:** - -- `serialize(value: T): string` - Converts a value to a serialized string -- `deserialize(serialized: string): T` - Reconstructs a value from serialized string -- `canHandle(value: any): boolean` - Determines if this adapter can handle the given value - -**Example Implementation:** - -```typescript -class CustomDateAdapter implements SerializationAdapter { - serialize(value: Date): string { - return JSON.stringify({ - __type__: 'CustomDate', - iso: value.toISOString(), - timestamp: value.getTime() - }); - } - - deserialize(serialized: string): Date { - try { - const parsed = JSON.parse(serialized); - if (parsed.__type__ === 'CustomDate') { - return new Date(parsed.iso); - } - } catch (error) { - console.warn('Failed to deserialize CustomDate:', error); - } - throw new Error('Invalid CustomDate serialization'); - } - - canHandle(value: any): boolean { - return value instanceof Date; - } -} -``` - -### `TypeValidator` - -Interface for runtime type validation during cache operations. - -```typescript -interface TypeValidator { - validate(value: any): value is T; - name: string; -} -``` - -**Properties:** - -- `name: string` - Human-readable name for the validator - -**Methods:** - -- `validate(value: any): value is T` - Type guard function that validates and narrows type - -## Built-in Adapters - -### `DefaultSerializationAdapter` - -The fallback adapter that handles basic JSON serialization. - -```typescript -class DefaultSerializationAdapter implements SerializationAdapter { - serialize(value: any): string; - deserialize(serialized: string): any; - canHandle(value: any): boolean; // Always returns true -} -``` - -**Behavior:** -- For strings: Returns the string unchanged -- For other values: Uses `JSON.stringify()` -- Deserialization: Attempts `JSON.parse()`, falls back to original string - -**How the cache uses it:** RunCache records for each entry whether its value was serialized from a non-string value. `RunCache.get()` deserializes only those entries; strings are stored and returned unchanged, so a string such as `"123"` or `'{"a":1}'` is never turned into a number or an object. This applies to values passed to `set()` and to values returned by source functions, on the initial fetch and on every refetch. Deserialization runs after `get` middleware, so middleware always works with the stored string. - -### `DateSerializationAdapter` - -Handles Date object serialization with timezone preservation. - -```typescript -class DateSerializationAdapter implements SerializationAdapter { - serialize(value: Date): string; - deserialize(serialized: string): Date; - canHandle(value: any): boolean; // Returns value instanceof Date -} -``` - -**Features:** -- Preserves timezone information -- Handles invalid dates gracefully -- Serializes to ISO string format with type metadata - -**Example:** - -```typescript -import { DateSerializationAdapter } from 'run-cache'; - -const adapter = new DateSerializationAdapter(); -const date = new Date('2024-12-25T10:30:00Z'); - -const serialized = adapter.serialize(date); -console.log(serialized); // '{"__type__":"Date","value":"2024-12-25T10:30:00.000Z"}' - -const deserialized = adapter.deserialize(serialized); -console.log(deserialized instanceof Date); // true -console.log(deserialized.getTime() === date.getTime()); // true -``` - -### `MapSerializationAdapter` - -Handles Map object serialization with support for any key/value types. - -```typescript -class MapSerializationAdapter implements SerializationAdapter> { - serialize(value: Map): string; - deserialize(serialized: string): Map; - canHandle(value: any): boolean; // Returns value instanceof Map -} -``` - -**Features:** -- Supports any serializable key/value types -- Preserves Map iteration order -- Handles nested Maps and complex values - -**Example:** - -```typescript -import { MapSerializationAdapter } from 'run-cache'; - -const adapter = new MapSerializationAdapter(); -const map = new Map([ - ['string-key', 'value'], - [42, { nested: 'object' }], - ['date', new Date()] -]); - -const serialized = adapter.serialize(map); -const deserialized = adapter.deserialize(serialized); - -console.log(deserialized instanceof Map); // true -console.log(deserialized.get('string-key')); // 'value' -console.log(deserialized.get(42)); // { nested: 'object' } -``` - -### `SetSerializationAdapter` - -Handles Set object serialization while preserving uniqueness. - -```typescript -class SetSerializationAdapter implements SerializationAdapter> { - serialize(value: Set): string; - deserialize(serialized: string): Set; - canHandle(value: any): boolean; // Returns value instanceof Set -} -``` - -**Example:** - -```typescript -import { SetSerializationAdapter } from 'run-cache'; - -const adapter = new SetSerializationAdapter(); -const set = new Set(['a', 'b', 'c', 1, 2, 3]); - -const serialized = adapter.serialize(set); -const deserialized = adapter.deserialize(serialized); - -console.log(deserialized instanceof Set); // true -console.log(deserialized.size); // 6 -console.log(deserialized.has('a')); // true -``` - -### `RegExpSerializationAdapter` - -Handles RegExp object serialization with flags preservation. - -```typescript -class RegExpSerializationAdapter implements SerializationAdapter { - serialize(value: RegExp): string; - deserialize(serialized: string): RegExp; - canHandle(value: any): boolean; // Returns value instanceof RegExp -} -``` - -**Example:** - -```typescript -import { RegExpSerializationAdapter } from 'run-cache'; - -const adapter = new RegExpSerializationAdapter(); -const regex = /hello\s+world/gim; - -const serialized = adapter.serialize(regex); -const deserialized = adapter.deserialize(serialized); - -console.log(deserialized instanceof RegExp); // true -console.log(deserialized.source); // 'hello\\s+world' -console.log(deserialized.flags); // 'gim' -console.log(deserialized.test('Hello World')); // true -``` - -### `BigIntSerializationAdapter` - -Handles BigInt serialization for large integers. - -```typescript -class BigIntSerializationAdapter implements SerializationAdapter { - serialize(value: bigint): string; - deserialize(serialized: string): bigint; - canHandle(value: any): boolean; // Returns typeof value === 'bigint' -} -``` - -**Example:** - -```typescript -import { BigIntSerializationAdapter } from 'run-cache'; - -const adapter = new BigIntSerializationAdapter(); -const bigInt = BigInt('123456789012345678901234567890'); - -const serialized = adapter.serialize(bigInt); -const deserialized = adapter.deserialize(serialized); - -console.log(typeof deserialized); // 'bigint' -console.log(deserialized === bigInt); // true -``` - -### `URLSerializationAdapter` - -Handles URL object serialization. - -```typescript -class URLSerializationAdapter implements SerializationAdapter { - serialize(value: URL): string; - deserialize(serialized: string): URL; - canHandle(value: any): boolean; // Returns value instanceof URL -} -``` - -### `ErrorSerializationAdapter` - -Handles Error object serialization with stack trace preservation. - -```typescript -class ErrorSerializationAdapter implements SerializationAdapter { - serialize(value: Error): string; - deserialize(serialized: string): Error; - canHandle(value: any): boolean; // Returns value instanceof Error -} -``` - -### `BufferSerializationAdapter` (Node.js only) - -Handles Buffer object serialization for binary data. - -```typescript -class BufferSerializationAdapter implements SerializationAdapter { - serialize(value: Buffer): string; - deserialize(serialized: string): Buffer; - canHandle(value: any): boolean; // Returns Buffer.isBuffer(value) -} -``` - -## Composite Adapters - -### `CompositeSerializationAdapter` - -Manages multiple serialization adapters with priority-based selection. - -```typescript -class CompositeSerializationAdapter implements SerializationAdapter { - addAdapter(adapter: SerializationAdapter): void; - removeAdapter(adapter: SerializationAdapter): void; - clearAdapters(): void; - serialize(value: any): string; - deserialize(serialized: string): any; - canHandle(value: any): boolean; // Always returns true (fallback) -} -``` - -**Methods:** - -- `addAdapter(adapter)` - Adds an adapter with high priority -- `removeAdapter(adapter)` - Removes a specific adapter -- `clearAdapters()` - Removes all custom adapters - -**Example:** - -```typescript -import { - CompositeSerializationAdapter, - DateSerializationAdapter, - MapSerializationAdapter -} from 'run-cache'; - -const composite = new CompositeSerializationAdapter(); -composite.addAdapter(new DateSerializationAdapter()); -composite.addAdapter(new MapSerializationAdapter()); - -// The composite will automatically choose the right adapter -const date = new Date(); -const map = new Map([['key', 'value']]); - -const serializedDate = composite.serialize(date); -const serializedMap = composite.serialize(map); - -const deserializedDate = composite.deserialize(serializedDate); -const deserializedMap = composite.deserialize(serializedMap); - -console.log(deserializedDate instanceof Date); // true -console.log(deserializedMap instanceof Map); // true -``` - -## Factory Functions - -### `createStandardSerializationAdapter()` - -Creates a composite adapter with commonly used serialization adapters. - -```typescript -function createStandardSerializationAdapter(): CompositeSerializationAdapter -``` - -**Includes:** -- DateSerializationAdapter -- MapSerializationAdapter -- SetSerializationAdapter -- RegExpSerializationAdapter -- BigIntSerializationAdapter -- URLSerializationAdapter -- ErrorSerializationAdapter -- BufferSerializationAdapter (Node.js only) - -**Example:** - -```typescript -import { createStandardSerializationAdapter } from 'run-cache'; - -const adapter = createStandardSerializationAdapter(); -RunCache.setSerializationAdapter(adapter); - -// Now all standard types are automatically handled -await RunCache.set({ - key: 'complex-data', - value: { - date: new Date(), - pattern: /test/g, - mapping: new Map([['key', 'value']]), - collection: new Set([1, 2, 3]), - url: new URL('https://example.com'), - bigNumber: BigInt(123) - } -}); -``` - -### `createTypedArrayAdapters()` - -Creates serialization adapters for all TypedArray types. - -```typescript -function createTypedArrayAdapters(): SerializationAdapter[] -``` - -**Returns array of adapters for:** -- Int8Array, Uint8Array -- Int16Array, Uint16Array -- Int32Array, Uint32Array -- Float32Array, Float64Array - -**Example:** - -```typescript -import { createTypedArrayAdapters } from 'run-cache'; - -const adapters = createTypedArrayAdapters(); -adapters.forEach(adapter => { - RunCache.addSerializationAdapter(adapter); -}); - -// Now TypedArrays are supported -const audioData = new Float32Array([0.1, 0.2, 0.3]); -await RunCache.set({ key: 'audio', value: audioData }); - -const retrieved = await RunCache.get('audio'); -console.log(retrieved instanceof Float32Array); // true -``` - -## Class Instance Serialization - -### `ClassInstanceSerializationAdapter` - -Generic adapter for serializing class instances with method preservation. - -```typescript -class ClassInstanceSerializationAdapter implements SerializationAdapter { - constructor( - classConstructor: new (...args: any[]) => T, - typeName: string, - reconstructor?: (data: any) => T - ); - - serialize(value: T): string; - deserialize(serialized: string): T; - canHandle(value: any): boolean; -} -``` - -**Parameters:** - -- `classConstructor` - The class constructor function -- `typeName` - Unique type name for serialization -- `reconstructor` - Optional custom reconstruction function - -**Example:** - -```typescript -class Person { - constructor( - public name: string, - public age: number, - public email: string - ) {} - - greet(): string { - return `Hello, I'm ${this.name}`; - } - - isAdult(): boolean { - return this.age >= 18; - } -} - -const personAdapter = new ClassInstanceSerializationAdapter( - Person, - 'Person', - (data) => new Person(data.name, data.age, data.email) -); - -RunCache.addSerializationAdapter(personAdapter); - -// Cache Person instances -const person = new Person('John', 30, 'john@example.com'); -await RunCache.set({ key: 'person:1', value: person }); - -const retrieved = await RunCache.get('person:1'); -console.log(retrieved instanceof Person); // true -console.log(retrieved.greet()); // "Hello, I'm John" -console.log(retrieved.isAdult()); // true -``` - -## TypedArray Support - -### `TypedArraySerializationAdapter` - -Generic adapter for TypedArray serialization. - -```typescript -class TypedArraySerializationAdapter - implements SerializationAdapter { - - constructor( - arrayConstructor: new (data: number[]) => T, - typeName: string - ); - - serialize(value: T): string; - deserialize(serialized: string): T; - canHandle(value: any): boolean; -} -``` - -**Example:** - -```typescript -import { TypedArraySerializationAdapter } from 'run-cache'; - -// Create adapter for specific typed array -const float32Adapter = new TypedArraySerializationAdapter( - Float32Array, - 'Float32Array' -); - -RunCache.addSerializationAdapter(float32Adapter); - -const audioSample = new Float32Array([0.1, 0.2, 0.3, 0.4]); -await RunCache.set({ key: 'audio:sample', value: audioSample }); - -const retrieved = await RunCache.get('audio:sample'); -console.log(retrieved instanceof Float32Array); // true -console.log(Array.from(retrieved)); // [0.1, 0.2, 0.3, 0.4] -``` - -## Cache Integration - -### Adding Serialization Adapters - -```typescript -// Add individual adapters -RunCache.addSerializationAdapter(new DateSerializationAdapter()); -RunCache.addSerializationAdapter(new MapSerializationAdapter()); - -// Set a composite adapter -const composite = createStandardSerializationAdapter(); -RunCache.setSerializationAdapter(composite); - -// Clear all adapters (reset to default) -RunCache.clearSerializationAdapters(); -``` - -### Adapter Priority - -Adapters are processed in reverse order of addition (most recent first): - -```typescript -RunCache.addSerializationAdapter(new GenericAdapter()); // Processed 3rd -RunCache.addSerializationAdapter(new DateAdapter()); // Processed 2nd -RunCache.addSerializationAdapter(new SpecificAdapter()); // Processed 1st - -// The most specific adapter that can handle the type will be used -``` - -## Error Handling - -### Serialization Failures - -```typescript -class SafeSerializationAdapter implements SerializationAdapter { - serialize(value: any): string { - try { - return this.doSerialization(value); - } catch (error) { - console.warn('Serialization failed:', error); - return JSON.stringify({ - __type__: 'SerializationError', - error: error.message, - fallbackValue: null - }); - } - } - - deserialize(serialized: string): any { - try { - const parsed = JSON.parse(serialized); - if (parsed.__type__ === 'SerializationError') { - console.warn('Cached value had serialization error:', parsed.error); - return parsed.fallbackValue; - } - return this.doDeserialization(parsed); - } catch (error) { - console.warn('Deserialization failed:', error); - return null; - } - } - - canHandle(value: any): boolean { - return true; // Fallback adapter - } - - private doSerialization(value: any): string { - // Custom serialization logic - return JSON.stringify(value); - } - - private doDeserialization(parsed: any): any { - // Custom deserialization logic - return parsed; - } -} -``` - -### Validation Integration - -```typescript -import { TypeValidator } from 'run-cache'; - -class ValidatingAdapter implements SerializationAdapter { - constructor( - private baseAdapter: SerializationAdapter, - private validator: TypeValidator - ) {} - - serialize(value: T): string { - if (!this.validator.validate(value)) { - throw new Error(`Invalid ${this.validator.name} for serialization`); - } - return this.baseAdapter.serialize(value); - } - - deserialize(serialized: string): T { - const result = this.baseAdapter.deserialize(serialized); - if (!this.validator.validate(result)) { - throw new Error(`Deserialized ${this.validator.name} failed validation`); - } - return result; - } - - canHandle(value: any): boolean { - return this.baseAdapter.canHandle(value) && this.validator.validate(value); - } -} -``` - -## Performance Optimization - -### Adapter Caching - -```typescript -class CachedSerializationAdapter implements SerializationAdapter { - private serializationCache = new Map(); - private deserializationCache = new Map(); - - constructor(private baseAdapter: SerializationAdapter) {} - - serialize(value: T): string { - const key = this.createCacheKey(value); - - if (this.serializationCache.has(key)) { - return this.serializationCache.get(key)!; - } - - const serialized = this.baseAdapter.serialize(value); - this.serializationCache.set(key, serialized); - return serialized; - } - - deserialize(serialized: string): T { - if (this.deserializationCache.has(serialized)) { - return this.deserializationCache.get(serialized)!; - } - - const deserialized = this.baseAdapter.deserialize(serialized); - this.deserializationCache.set(serialized, deserialized); - return deserialized; - } - - canHandle(value: any): boolean { - return this.baseAdapter.canHandle(value); - } - - private createCacheKey(value: T): string { - return JSON.stringify(value); - } -} -``` - -## Next Steps - -- Learn about [Type Validation](../advanced/type-validation.md) for runtime checking -- Explore [Serialization Adapters](../advanced/serialization-adapters.md) usage guide -- See [Performance Optimization](../guides/performance.md) for serialization performance -- Check [Best Practices](../guides/best-practices.md) for serialization patterns \ No newline at end of file diff --git a/gitbook/api/storage-adapters.md b/gitbook/api/storage-adapters.md index e377157..213c12f 100644 --- a/gitbook/api/storage-adapters.md +++ b/gitbook/api/storage-adapters.md @@ -12,20 +12,13 @@ Storage adapters implement a common interface to save and load cache data to/fro ## Common Configuration Options -All storage adapters accept the following common options: +All storage adapters accept the following options (`FilesystemAdapter` also accepts `filePath`): -```typescript -interface StorageAdapterConfig { - // Storage key/filename to use - storageKey?: string; // Default: "run-cache-data" - - // Auto-save interval in milliseconds - autoSaveInterval?: number; // Default: 0 (disabled) - - // Whether to load cache automatically when adapter is initialized - autoLoadOnInit?: boolean; // Default: true -} -``` +- `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. @@ -42,30 +35,26 @@ import { RunCache, LocalStorageAdapter } from 'run-cache'; ### Constructor ```typescript -constructor(config?: StorageAdapterConfig) +constructor(config?: Partial) ``` #### Parameters - `config?`: `StorageAdapterConfig` - Optional configuration options - `storageKey?`: `string` - Key to use in localStorage (default: "run-cache-data") - - `autoSaveInterval?`: `number` - Auto-save interval in milliseconds (default: 0) - - `autoLoadOnInit?`: `boolean` - Whether to load cache automatically when adapter is initialized (default: true) ### Example Usage ```typescript // Basic usage with default options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new LocalStorageAdapter() }); // With custom options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new LocalStorageAdapter({ storageKey: 'my-app-cache', - autoSaveInterval: 300000, // 5 minutes - autoLoadOnInit: true }) }); ``` @@ -89,30 +78,26 @@ import { RunCache, IndexedDBAdapter } from 'run-cache'; ### Constructor ```typescript -constructor(config?: StorageAdapterConfig) +constructor(config?: Partial) ``` #### Parameters - `config?`: `StorageAdapterConfig` - Optional configuration options - `storageKey?`: `string` - Database and store name (default: "run-cache-data") - - `autoSaveInterval?`: `number` - Auto-save interval in milliseconds (default: 0) - - `autoLoadOnInit?`: `boolean` - Whether to load cache automatically when adapter is initialized (default: true) ### Example Usage ```typescript // Basic usage with default options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new IndexedDBAdapter() }); // With custom options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new IndexedDBAdapter({ storageKey: 'my-app-cache', - autoSaveInterval: 300000, // 5 minutes - autoLoadOnInit: true }) }); ``` @@ -148,25 +133,21 @@ constructor(config?: FilesystemAdapterConfig) - `config?`: `FilesystemAdapterConfig` - Optional configuration options - `storageKey?`: `string` - Filename to use (default: "run-cache-data") - - `autoSaveInterval?`: `number` - Auto-save interval in milliseconds (default: 0) - - `autoLoadOnInit?`: `boolean` - Whether to load cache automatically when adapter is initialized (default: true) - `filePath?`: `string` - Custom file path (default: current working directory) ### Example Usage ```typescript // Basic usage with default options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new FilesystemAdapter() }); // With custom options -RunCache.configure({ +await RunCache.configure({ storageAdapter: new FilesystemAdapter({ storageKey: 'my-app-cache', filePath: '/path/to/cache/directory', - autoSaveInterval: 300000, // 5 minutes - autoLoadOnInit: true }) }); ``` @@ -193,7 +174,7 @@ interface StorageAdapter { load(): Promise; clear(): Promise; - // Optional: picked up when the adapter is attached with configure() or create() + // 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) } @@ -204,7 +185,7 @@ interface StorageAdapter { Here's an example of a custom adapter that uses a RESTful API for storage: ```typescript -import { StorageAdapter } from 'run-cache'; +import type { StorageAdapter } from 'run-cache'; class ApiStorageAdapter implements StorageAdapter { private apiUrl: string; @@ -238,11 +219,11 @@ class ApiStorageAdapter implements StorageAdapter { 'Authorization': `Bearer ${this.apiKey}` } }); - + if (!response.ok) { return null; } - + const result = await response.json(); return result.data; } catch (error) { @@ -250,10 +231,21 @@ class ApiStorageAdapter implements StorageAdapter { 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 -RunCache.configure({ +await RunCache.configure({ storageAdapter: new ApiStorageAdapter('https://api.example.com', 'your-api-key') }); ``` @@ -278,20 +270,23 @@ Configure automatic saving at regular intervals: ```typescript // Save cache to storage every 5 minutes -RunCache.setupAutoSave(300000); +await RunCache.setupAutoSave(300000); // Disable auto-saving -RunCache.setupAutoSave(0); +await RunCache.setupAutoSave(0); ``` ### Storage Cleanup -To clear persistent storage: +To clear persistent storage, either save an empty cache or clear the adapter directly: ```typescript // Clear cache and save empty state to storage -RunCache.flush(); +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 @@ -304,15 +299,15 @@ await RunCache.saveToStorage(); ### 2. Handle Storage Errors -Always handle potential 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 -try { - await RunCache.loadFromStorage(); - console.log('Cache loaded successfully'); -} catch (error) { - console.error('Failed to load cache:', error); - // Implement fallback mechanism +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?)'); } ``` @@ -322,7 +317,7 @@ Be mindful of storage limits, especially in browsers: ```typescript // Configure cache with size limits -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, // Limit to 1000 entries evictionPolicy: EvictionPolicy.LRU, storageAdapter: new LocalStorageAdapter() @@ -335,10 +330,10 @@ Balance between data freshness and performance: ```typescript // For frequently changing data, save more often -RunCache.setupAutoSave(60000); // 1 minute +await RunCache.setupAutoSave(60000); // 1 minute // For relatively stable data, save less frequently -RunCache.setupAutoSave(3600000); // 1 hour +await RunCache.setupAutoSave(3600000); // 1 hour ``` ### 5. Consider Data Serialization diff --git a/gitbook/api/typed-cache-interface.md b/gitbook/api/typed-cache-interface.md index acbe0d1..cd51cb4 100644 --- a/gitbook/api/typed-cache-interface.md +++ b/gitbook/api/typed-cache-interface.md @@ -1,6 +1,8 @@ # Typed Cache Interface -The `TypedCacheInterface` provides a type-safe wrapper around RunCache operations for a specific type. This interface ensures compile-time type checking and better developer experience when working with consistently typed cache entries. +`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 @@ -14,7 +16,7 @@ Created using `RunCache.createTypedCache()`, this interface provides all stan ### `set(options)` -Sets a cache entry with type-safe value validation. +Sets a cache entry. Same as `RunCache.set()`. **Parameters:** @@ -26,8 +28,6 @@ Sets a cache entry with type-safe value validation. - `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 - - `metadata?`: `any` - Custom metadata to associate with the entry - - `validator?`: `TypeValidator` - Optional type validator for runtime checking **Returns:** `Promise` - Returns `true` if the value was successfully set @@ -141,7 +141,7 @@ Removes a cache entry or entries matching a pattern. - `key`: `string` - The key to delete, or a pattern with wildcards -**Returns:** `Promise` +**Returns:** `Promise` - `true` if at least one entry was deleted **Example:** @@ -153,17 +153,15 @@ await userCache.delete('user:123'); await userCache.delete('user:*'); ``` -### `refetch(key, options?)` +### `refetch(key)` -Manually refreshes a cache entry or entries matching a pattern. +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 -- `options?`: `Object` - Optional refresh options - - `metadata?`: `any` - Custom metadata to include in refetch events -**Returns:** `Promise` +**Returns:** `Promise` - `true` if at least one entry was refetched **Example:** @@ -173,32 +171,31 @@ await userCache.refetch('user:123'); // Refresh all users await userCache.refetch('user:*'); - -// Refresh with metadata -await userCache.refetch('user:123', { - metadata: { reason: 'manual-refresh', userId: 123 } -}); ``` ## Event System Integration -Typed cache interfaces work seamlessly with the event system, providing typed event parameters. +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 -// Type-safe event handlers -userCache.onExpiry((event) => { - console.log(`User ${event.value.name} expired from cache`); - // event.value is typed as User +// 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`); }); -userCache.onRefetch((event) => { +await userCache.onKeyRefetch('user:*', (event) => { console.log(`User cache refreshed: ${event.key}`); }); -userCache.onRefetchFailure((event) => { - console.error(`Failed to refresh user: ${event.error.message}`); +await userCache.onKeyRefetchFailure('user:*', (event) => { + console.error(`Failed to refresh user: ${event.key}`, event.error); }); ``` @@ -211,11 +208,12 @@ Use typed cache interfaces to implement repository patterns: ```typescript class UserRepository { private cache = RunCache.createTypedCache(); - + async findById(id: number): Promise { - return this.cache.get(`user:${id}`); + // 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}`, @@ -224,7 +222,7 @@ class UserRepository { tags: ['user', `user:${user.id}`] }); } - + async findByEmail(email: string): Promise { const users = await this.cache.get('user:*'); if (Array.isArray(users)) { @@ -232,11 +230,11 @@ class UserRepository { } return undefined; } - + async invalidateUser(id: number): Promise { await this.cache.delete(`user:${id}`); } - + async refreshUser(id: number): Promise { await this.cache.refetch(`user:${id}`); } @@ -265,14 +263,14 @@ interface Product { class ProductService { private cache = RunCache.createTypedCache(); - + async getProduct(id: number): Promise { // Try cache first - const cached = await this.cache.get(`product:${id}`); + 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) { @@ -284,13 +282,13 @@ class ProductService { 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}`, @@ -299,17 +297,17 @@ class ProductService { tags: ['product', `category:${product.category}`] }); } - + async invalidateCategory(category: string): Promise { - // This would require tag invalidation on the main RunCache + // 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 } @@ -333,12 +331,12 @@ class CacheManager { private userCache = RunCache.createTypedCache(); private productCache = RunCache.createTypedCache(); private orderCache = RunCache.createTypedCache(); - + // User operations async getUser(id: number): Promise { - return this.userCache.get(`user:${id}`); + return (await this.userCache.get(`user:${id}`)) as User | undefined; } - + async setUser(user: User): Promise { await this.userCache.set({ key: `user:${user.id}`, @@ -347,12 +345,12 @@ class CacheManager { tags: ['user'] }); } - + // Product operations async getProduct(id: number): Promise { - return this.productCache.get(`product:${id}`); + return (await this.productCache.get(`product:${id}`)) as Product | undefined; } - + async setProduct(product: Product): Promise { await this.productCache.set({ key: `product:${product.id}`, @@ -361,12 +359,12 @@ class CacheManager { tags: ['product', `category:${product.category}`] }); } - + // Order operations async getOrder(id: number): Promise { - return this.orderCache.get(`order:${id}`); + return (await this.orderCache.get(`order:${id}`)) as Order | undefined; } - + async setOrder(order: Order): Promise { await this.orderCache.set({ key: `order:${order.id}`, @@ -376,7 +374,7 @@ class CacheManager { dependencies: [`user:${order.userId}`] }); } - + // Cross-type operations async getUserOrders(userId: number): Promise { const orders = await this.orderCache.get('order:*'); @@ -385,7 +383,7 @@ class CacheManager { } return []; } - + async invalidateUserData(userId: number): Promise { await this.userCache.delete(`user:${userId}`); await RunCache.invalidateByTag(`user:${userId}`); @@ -402,7 +400,7 @@ interface StrictUser { id: number; name: string; email: string; - createdAt: Date; + createdAt: string; // ISO date: a Date would come back from get() as a string } const strictUserCache = RunCache.createTypedCache(); @@ -414,7 +412,7 @@ await strictUserCache.set({ id: 1, name: 'John', email: 'john@example.com', - createdAt: new Date() + createdAt: new Date().toISOString() } }); @@ -434,25 +432,7 @@ await strictUserCache.set({ ### Runtime Type Validation -Combine with type validators for runtime checking: - -```typescript -import { ValidatorUtils, NumberValidator, StringValidator } from 'run-cache'; - -const userValidator = ValidatorUtils.object({ - id: NumberValidator, - name: StringValidator, - email: ValidatorUtils.string(email => email.includes('@')), - createdAt: ValidatorUtils.instanceOf(Date) -}); - -await strictUserCache.set({ - key: 'user:1', - value: userData, - validator: userValidator, // Runtime validation - validateOnSet: true -}); -``` +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 @@ -460,20 +440,20 @@ 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 performance characteristics -- **Method Calls**: Minimal indirection overhead (< 1ms) +- **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. **Type Validation**: Use runtime validators for critical data integrity -5. **Event Handling**: Leverage typed events for better debugging and monitoring +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 [Serialization Adapters](serialization-system.md) for complex types -- Explore [Type Validation](../advanced/type-validation.md) for runtime checking +- 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/api/types.md b/gitbook/api/types.md index dc748bb..a8041b6 100644 --- a/gitbook/api/types.md +++ b/gitbook/api/types.md @@ -1,349 +1,148 @@ # TypeScript Types -RunCache is built with TypeScript and provides comprehensive type definitions to help you write type-safe code. This page documents all the TypeScript types, interfaces, and enums available in the RunCache library. +This page lists every type the `run-cache` package exports. Import them with `import type`: -## Core Types +```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 +## CacheConfig -Configuration options for RunCache. +Options for `RunCache.configure()`. Every option is optional, and a call only changes the options it passes. ```typescript interface CacheConfig { - /** - * Maximum number of entries before eviction - */ + /** Maximum number of entries. Default: unlimited */ maxEntries?: number; - - /** - * Eviction policy to use - */ + + /** Declared but not used: entries without a ttl never expire */ + defaultTTL?: number; + + /** What to evict when maxEntries is reached. Default: EvictionPolicy.NONE */ evictionPolicy?: EvictionPolicy; - - /** - * Enable debug logging - */ - debug?: boolean; - - /** - * Storage adapter for persistence - */ + + /** Adapter to persist the cache with. Attaching one loads its saved data */ storageAdapter?: StorageAdapter; - /** - * Shut the cache down (saving to the storage adapter) on SIGTERM/SIGINT in - * Node.js and on `beforeunload` in browsers. The signal is re-raised afterwards - * unless the application has its own listener for it. - * @default false - */ + /** 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 or rejected by event listeners. - * Defaults to writing them to console.error. - */ + /** Receives errors thrown by event listeners. Default: console.error */ onListenerError?: (error: unknown, context: { event: string; key: string }) => void; } ``` -### SetOptions +## Set options -Options for setting a cache entry. +`RunCache.set()` takes an inline options object; there is no exported name for it: ```typescript -interface SetOptions { - /** - * Unique identifier for the cache entry - */ - key: string; - - /** - * String value to cache (required if no sourceFn) - */ - value?: string; - - /** - * Time-to-live in milliseconds - */ - ttl?: number; - - /** - * Automatically refetch on expiry (requires ttl and sourceFn) - */ - autoRefetch?: boolean; - - /** - * Function to generate cache value (required if no value) - */ - sourceFn?: () => string | Promise; - - /** - * Array of tags for tag-based invalidation - */ +{ + 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[]; - - /** - * Array of cache keys this entry depends on - */ dependencies?: string[]; - - /** - * Custom metadata to associate with the entry - */ - metadata?: any; } ``` -### RefetchOptions - -Options for refreshing a cache entry. - -```typescript -interface RefetchOptions { - /** - * Custom metadata to include in refetch events - */ - metadata?: any; -} -``` +One of `value` or `sourceFn` is required. If you need the type, derive it: `Parameters[0]`. ## Event Types -### EventName - -Union type of all possible event names. - -```typescript -type EventName = 'expire' | 'refetch' | 'refetch_failure' | 'tag_invalidation' | 'dependency_invalidation'; -``` - ### EVENT -Enum for event types. - ```typescript -enum EVENT { - EXPIRE = 'expire', - REFETCH = 'refetch', - REFETCH_FAILURE = 'refetch_failure', - TAG_INVALIDATION = 'tag_invalidation', - DEPENDENCY_INVALIDATION = 'dependency_invalidation' -} +const EVENT = { + EXPIRE: 'expire', + REFETCH: 'refetch', + REFETCH_FAILURE: 'refetch_failure', + TAG_INVALIDATION: 'tag_invalidation', + DEPENDENCY_INVALIDATION: 'dependency_invalidation', +} as const; ``` -### EventParam - -Union type of all possible event objects. +### EventName ```typescript -type EventParam = ExpiryEvent | RefetchEvent | RefetchFailureEvent | TagInvalidationEvent | DependencyInvalidationEvent; +type EventName = keyof typeof EVENT + | 'expire' | 'refetch' | 'refetch_failure' | 'tag_invalidation' | 'dependency_invalidation'; ``` -### ExpiryEvent - -Event object for expiry events. +Accepted by `RunCache.clearEventListeners({ event })`. -```typescript -interface ExpiryEvent { - /** - * The key of the expired entry - */ - key: string; - - /** - * The stored value at the time it expired - */ - value: string; - - /** - * The TTL value in milliseconds - */ - ttl: number; - - /** - * Timestamp when the entry was created - */ - createdAt: number; - - /** - * Timestamp when the entry was last updated - */ - updatedAt: number; -} -``` - -### RefetchEvent +### EventParam -Event object for refetch events. +Every event listener receives an `EventParam`: ```typescript -interface RefetchEvent { - /** - * The key of the refreshed entry - */ +type EventParam = { key: string; - - /** - * The value returned by the source function - */ - value: string; - - /** - * The entry's TTL in milliseconds, if it has one - */ + value: T; // see the note below + serializedValue?: string; ttl?: number; - - /** - * Timestamps of the refetch - */ - createdAt: number; + createdAt: number; // ms since epoch updatedAt: number; -} -``` - -### RefetchFailureEvent - -Event object for refetch failure events. - -```typescript -interface RefetchFailureEvent { - /** - * The key of the entry that failed to refresh - */ - key: string; - - /** - * The error thrown by the source function (or a SourceFnError if it - * resolved to undefined) - */ - error: unknown; -} -``` - -### TagInvalidationEvent - -Event object for tag invalidation events. - -```typescript -interface TagInvalidationEvent { - /** - * The key of the invalidated entry - */ - key: string; - - /** - * The tag that caused the invalidation - */ - tag: string; - - /** - * Optional custom metadata associated with the entry - */ - metadata?: any; -} -``` - -### DependencyInvalidationEvent - -Event object for dependency invalidation events. - -```typescript -interface DependencyInvalidationEvent { - /** - * The key of the invalidated entry - */ - key: string; - - /** - * The key of the dependency that caused the invalidation - */ - dependencyKey: string; - - /** - * Optional custom metadata associated with the entry - */ - metadata?: any; -} + tag?: string; // tag_invalidation events only + dependencyKey?: string; // dependency_invalidation events only + error?: unknown; // refetch_failure events only +}; ``` -### EventListenerOptions - -Options for clearing event listeners. - -```typescript -interface EventListenerOptions { - /** - * The event type to remove listeners for - */ - event?: EVENT; - - /** - * The key or pattern to remove listeners for - */ - key?: string; - - /** - * The specific handler function to remove - */ - handler?: Function; -} -``` +`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 -Type definition for middleware functions. - ```typescript -type MiddlewareFunction = ( - value: string | undefined, - context: MiddlewareContext, - next: (value: string | undefined) => Promise -) => Promise; +type MiddlewareFunction = ( + value: T, + context: MiddlewareContext, + next: (nextValue: T) => Promise +) => Promise; ``` -### MiddlewareContext +`RunCache.use()` takes a `MiddlewareFunction`: middleware always sees the stored string, never the original object. -Context object passed to middleware functions. +### MiddlewareContext ```typescript -interface MiddlewareContext { - /** - * The operation being performed - */ - operation: 'get' | 'set' | 'delete' | 'refetch' | 'evict'; - - /** - * The key of the cache entry - */ +interface MiddlewareContext { key: string; - - /** - * Optional custom metadata associated with the entry - */ - metadata?: any; + 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 -Interface for storage adapters. - ```typescript interface StorageAdapter { - /** - * Save cache data to storage - * @param data The stringified cache data - */ save(data: string): Promise; - - /** - * Load cache data from storage - * @returns The stringified cache data or null if not found - */ load(): Promise; /** @@ -363,178 +162,62 @@ interface StorageAdapter { } ``` -### StorageAdapterConfig +Implement it to persist the cache somewhere other than the built-in adapters. See [Persistent Storage](../advanced/persistent-storage.md#custom-storage-adapters). -Common configuration options for storage adapters. +### StorageAdapterConfig ```typescript interface StorageAdapterConfig { - /** - * Storage key/filename to use - * @default "run-cache-data" - */ + /** Key (or file name, for FilesystemAdapter) to store under. Default: "run-cache-data" */ storageKey?: string; - - /** - * Auto-save interval in milliseconds - * @default 0 (disabled) - */ + /** Save at this interval (ms) while the adapter is attached. Default: 0 (off) */ autoSaveInterval?: number; - - /** - * Whether to load cache automatically when adapter is initialized - * @default true - */ + /** Load existing data when the adapter is attached. Default: true */ autoLoadOnInit?: boolean; } ``` -### FilesystemAdapterConfig +The adapter constructors take `Partial`; `FilesystemAdapter` additionally accepts `filePath?: string`. -Configuration options specific to FilesystemAdapter. +## Error Classes ```typescript -interface FilesystemAdapterConfig extends StorageAdapterConfig { - /** - * Custom file path - * @default current working directory - */ - filePath?: string; -} +import { RunCacheError, SourceFnError, MiddlewareError } from 'run-cache'; ``` -## Enums +| 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` | -### EvictionPolicy - -Enum for cache eviction policies. +Each has `key` (the cache key of the failing operation) and, when there is an underlying error, `cause`: ```typescript -enum EvictionPolicy { - /** - * No automatic eviction - */ - NONE = 'none', - - /** - * Least Recently Used eviction policy - */ - LRU = 'lru', - - /** - * Least Frequently Used eviction policy - */ - LFU = 'lfu' -} -``` +import { RunCache, SourceFnError } from 'run-cache'; -## Internal Types - -These types are used internally by RunCache but may be useful for understanding the library's implementation. - -### CacheEntry - -Represents a single cache entry. - -```typescript -interface CacheEntry { - /** - * The cached value - */ - value: string; - - /** - * Time-to-live in milliseconds - */ - ttl?: number; - - /** - * Timestamp when the entry was last updated - */ - updatedAt: number; - - /** - * Timestamp when the entry was last accessed - */ - accessedAt: number; - - /** - * Number of times the entry has been accessed - */ - accessCount: number; - - /** - * Function to generate cache value - */ - sourceFn?: () => string | Promise; - - /** - * Whether to automatically refetch on expiry - */ - autoRefetch?: boolean; - - /** - * Array of tags associated with the entry - */ - tags?: string[]; - - /** - * Array of cache keys this entry depends on - */ - dependencies?: string[]; - - /** - * Custom metadata associated with the entry - */ - metadata?: any; +try { + await RunCache.refetch('api-data'); +} catch (error) { + if (error instanceof SourceFnError) { + console.error(`Refetch of ${error.key} failed`, error.cause); + } } ``` -### CacheState - -Represents the entire cache state. +## EvictionPolicy ```typescript -interface CacheState { - /** - * Map of cache entries - */ - entries: Map; - - /** - * Map of tags to sets of keys - */ - tagMap: Map>; - - /** - * Map of dependencies to sets of dependent keys - */ - dependencyMap: Map>; - - /** - * Cache configuration - */ - config: CacheConfig; +enum EvictionPolicy { + NONE = 'NONE', // never evict (default) + LRU = 'LRU', // evict the least recently used entry + LFU = 'LFU', // evict the least frequently used entry } ``` -## Using Types in Your Code - -### Import Types - -```typescript -import { - RunCache, - EvictionPolicy, - EVENT, - type CacheConfig, - type SetOptions, - type StorageAdapter, - type MiddlewareFunction -} from 'run-cache'; -``` +## Examples -### Example: Configuring RunCache with Types +### Configuration ```typescript import { RunCache, EvictionPolicy, type CacheConfig } from 'run-cache'; @@ -542,93 +225,39 @@ import { RunCache, EvictionPolicy, type CacheConfig } from 'run-cache'; const config: CacheConfig = { maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU, - debug: true + debug: process.env.NODE_ENV !== 'production' }; -RunCache.configure(config); +await RunCache.configure(config); ``` -### Example: Setting Cache Entry with Types +### Middleware ```typescript -import { RunCache, type SetOptions } from 'run-cache'; +import { RunCache, type MiddlewareFunction } from 'run-cache'; -const options: SetOptions = { - key: 'user:1', - value: JSON.stringify({ name: 'John Doe' }), - ttl: 3600000, - tags: ['user', 'user:1'] -}; - -await RunCache.set(options); -``` - -### Example: Creating a Custom Storage Adapter - -```typescript -import { StorageAdapter } from 'run-cache'; - -class CustomStorageAdapter implements StorageAdapter { - async save(data: string): Promise { - // Implementation - } - - async load(): Promise { - // Implementation - return null; - } -} -``` - -### Example: Creating a Middleware Function - -```typescript -import { MiddlewareFunction, MiddlewareContext } from 'run-cache'; - -const loggingMiddleware: MiddlewareFunction = async (value, context, next) => { - console.log(`${context.operation} operation for key: ${context.key}`); +const logOperations: MiddlewareFunction = async (value, context, next) => { + console.log(`${context.operation} ${context.key}`); return next(value); }; -RunCache.use(loggingMiddleware); +await RunCache.use(logOperations); ``` -### Example: Handling Events with Types +### Event handler ```typescript -import { RunCache, EVENT, ExpiryEvent, RefetchEvent } from 'run-cache'; +import { RunCache, type EventParam } from 'run-cache'; -const handleExpiry = (event: ExpiryEvent) => { - console.log(`Cache key ${event.key} expired`); -}; - -const handleRefetch = (event: RefetchEvent) => { - console.log(`Cache key ${event.key} was refreshed`); -}; - -RunCache.onExpiry(handleExpiry); -RunCache.onRefetch(handleRefetch); +function logExpiry(event: EventParam) { + console.log(`${event.key} expired after ${event.ttl}ms`); +} -// Later, remove specific handlers -RunCache.clearEventListeners({ - event: EVENT.EXPIRE, - handler: handleExpiry -}); +await RunCache.onExpiry(logExpiry); ``` -## Type Compatibility - -RunCache is compatible with TypeScript 4.0 and above. The library uses modern TypeScript features like: - -- Discriminated unions -- Generic types -- Function types -- Interface inheritance -- Optional properties -- Readonly properties - ## Next Steps -- [RunCache API](./run-cache.md) - Learn about the main RunCache API -- [Events](./events.md) - Understand the event system -- [Storage Adapters](./storage-adapters.md) - Learn about persistent storage options \ No newline at end of file +- [RunCache API](run-cache.md) - Method reference +- [Events](events.md) - Event reference +- [Typed Cache Interface](typed-cache-interface.md) - `createTypedCache()` diff --git a/gitbook/book.json b/gitbook/book.json deleted file mode 100644 index 9092847..0000000 --- a/gitbook/book.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "title": "RunCache Documentation", - "description": "Documentation for the RunCache library - A dependency-free, lightweight runtime caching library for JavaScript and TypeScript applications", - "author": "helloscoopa", - "language": "en", - "structure": { - "readme": "README.md", - "summary": "SUMMARY.md" - }, - "plugins": [ - "search", - "github", - "edit-link", - "prism", - "-highlight", - "copy-code-button", - "expandable-chapters", - "heading-anchors", - "back-to-top-button" - ], - "pluginsConfig": { - "github": { - "url": "https://github.com/helloscoopa/run-cache" - }, - "edit-link": { - "base": "https://github.com/helloscoopa/run-cache/edit/main/gitbook", - "label": "Edit This Page" - }, - "prism": { - "lang": { - "typescript": "typescript", - "bash": "bash", - "json": "json" - } - } - }, - "styles": { - "website": "styles/website.css" - } -} \ No newline at end of file diff --git a/gitbook/features/auto-refetch.md b/gitbook/features/auto-refetch.md index d5ff563..b435562 100644 --- a/gitbook/features/auto-refetch.md +++ b/gitbook/features/auto-refetch.md @@ -30,7 +30,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.weather.com/current'); const data = await response.json(); - return JSON.stringify(data); + return data; }, ttl: 5 * 60 * 1000, // 5 minutes autoRefetch: true @@ -65,17 +65,17 @@ RunCache provides events to monitor automatic refetching: ```typescript // Global refetch event -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache key ${event.key} was refreshed at ${new Date().toISOString()}`); }); // Specific key refetch -RunCache.onKeyRefetch("weather-data", (event) => { +await RunCache.onKeyRefetch("weather-data", (event) => { console.log(`Weather data was refreshed`); }); // Pattern-based refetch events -RunCache.onKeyRefetch("user:*:profile", (event) => { +await RunCache.onKeyRefetch("user:*:profile", (event) => { console.log(`User profile ${event.key} was refreshed`); }); ``` @@ -86,14 +86,14 @@ If a background refresh fails, RunCache provides events to handle the failure: ```typescript // Global refetch failure event -RunCache.onRefetchFailure((event) => { - console.error(`Failed to refresh cache key ${event.key}: ${event.error.message}`); +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}: ${event.error}`); }); // Specific key refetch failure -RunCache.onKeyRefetchFailure("weather-data", (event) => { - console.error(`Weather data refresh failed: ${event.error.message}`); - +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 }); @@ -188,45 +188,55 @@ await RunCache.set({ Always implement error handling for refetch failures: ```typescript -RunCache.onRefetchFailure((event) => { +// 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 = (event.metadata?.retryCount || 0) + 1; + 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, { - metadata: { retryCount } - }); - }, delay); + + 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. Use Metadata for Tracking +### 5. Track Refetch Statistics -You can use the metadata parameter to track information about refetches: +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, - metadata: { - lastRefreshSource: 'initial', - refreshCount: 0 - } + autoRefetch: true }); -RunCache.onRefetch((event) => { - // Update metadata - const metadata = event.metadata || {}; - metadata.lastRefreshSource = 'auto'; - metadata.refreshCount = (metadata.refreshCount || 0) + 1; - - // You can update metadata here if needed +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); }); ``` @@ -234,7 +244,7 @@ RunCache.onRefetch((event) => { ### Cascading Refreshes -You can implement cascading refreshes using dependencies: +You can implement cascading refreshes using dependencies. Each automatic refetch of the primary entry invalidates its dependents: ```typescript // Primary data @@ -251,21 +261,23 @@ await RunCache.set({ sourceFn: () => fetchUserRecommendations(1), ttl: 300000, autoRefetch: true, - dependencies: ['user:1:profile'] // Will be invalidated when profile changes + 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 -RunCache.onKeyExpiry('conditional-data', async (event) => { +await RunCache.onKeyExpiry('conditional-data', async (event) => { const shouldRefresh = await checkIfRefreshNeeded(event.key); - + if (shouldRefresh) { - RunCache.refetch(event.key); + await RunCache.refetch(event.key); } else { console.log('Skipping refresh based on condition'); } diff --git a/gitbook/features/cache-management.md b/gitbook/features/cache-management.md index a13319c..0d08f30 100644 --- a/gitbook/features/cache-management.md +++ b/gitbook/features/cache-management.md @@ -36,13 +36,13 @@ await RunCache.set({ // Store a simple string await RunCache.set({ key: 'greeting', value: 'Hello, World!' }); -// Store a JSON object (must be stringified) +// Store an object (serialized for you) const user = { id: 1, name: 'John Doe' }; -await RunCache.set({ key: 'user:1', value: JSON.stringify(user) }); +await RunCache.set({ key: 'user:1', value: user }); // Store with expiration (TTL) -await RunCache.set({ - key: 'temporary-data', +await RunCache.set({ + key: 'temporary-data', value: 'This will expire soon', ttl: 60000 // 1 minute }); @@ -57,21 +57,21 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/data'); const data = await response.json(); - return JSON.stringify(data); + return data; } }); // Store with tags for group invalidation await RunCache.set({ key: 'user:1:profile', - value: JSON.stringify({ name: 'John Doe' }), + value: { name: 'John Doe' }, tags: ['user:1', 'profile'] }); // Store with dependencies await RunCache.set({ key: 'dashboard:1', - value: JSON.stringify({ widgets: [...] }), + value: { widgets: [...] }, dependencies: ['user:1:profile'] }); ``` @@ -91,10 +91,10 @@ const value = await RunCache.get(key); const greeting = await RunCache.get('greeting'); console.log(greeting); // Output: Hello, World! -// Get and parse a JSON object -const userJson = await RunCache.get('user:1'); -if (userJson) { - const user = JSON.parse(userJson); +// 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 } ``` @@ -143,17 +143,17 @@ if (hasUserData) { The `delete` method removes entries from the cache: ```typescript -RunCache.delete(key); +await RunCache.delete(key); ``` ### Examples ```typescript // Delete a specific entry -RunCache.delete('greeting'); +await RunCache.delete('greeting'); // Delete multiple entries using a pattern -RunCache.delete('user:1:*'); // Deletes all entries that match the pattern +await RunCache.delete('user:1:*'); // Deletes all entries that match the pattern ``` ## Clearing the Entire Cache @@ -161,7 +161,7 @@ RunCache.delete('user:1:*'); // Deletes all entries that match the pattern The `flush` method removes all entries from the cache: ```typescript -RunCache.flush(); +await RunCache.flush(); ``` This is useful for: diff --git a/gitbook/features/pattern-matching.md b/gitbook/features/pattern-matching.md index 14bd566..2445f7f 100644 --- a/gitbook/features/pattern-matching.md +++ b/gitbook/features/pattern-matching.md @@ -56,13 +56,13 @@ The `delete` method supports patterns to remove multiple cache entries: ```typescript // Delete all data for user 1 -RunCache.delete('user:1:*'); +await RunCache.delete('user:1:*'); // Delete all email entries -RunCache.delete('user:*:email'); +await RunCache.delete('user:*:email'); // Delete all user data -RunCache.delete('user:*'); +await RunCache.delete('user:*'); ``` ## Using Patterns with Has @@ -104,12 +104,12 @@ You can use patterns when registering event listeners: ```typescript // Listen for expiry of any user profile -RunCache.onKeyExpiry('user:*:profile', (event) => { +await RunCache.onKeyExpiry('user:*:profile', (event) => { console.log(`User profile ${event.key} expired`); }); // Listen for refetch of any API data -RunCache.onKeyRefetch('api:*', (event) => { +await RunCache.onKeyRefetch('api:*', (event) => { console.log(`API data ${event.key} was refreshed`); }); ``` @@ -170,20 +170,20 @@ For complex grouping needs, consider using tags instead of relying solely on pat ```typescript // Set entries with tags -await RunCache.set({ - key: 'user:1:profile', - value: '...', +await RunCache.set({ + key: 'user:1:profile', + value: '...', tags: ['user:1', 'profile'] }); -await RunCache.set({ - key: 'user:1:settings', - value: '...', +await RunCache.set({ + key: 'user:1:settings', + value: '...', tags: ['user:1', 'settings'] }); // Later, invalidate by tag -RunCache.invalidateByTag('user:1'); +await RunCache.invalidateByTag('user:1'); ``` ## Common Pattern Matching Use Cases @@ -199,7 +199,7 @@ 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 -RunCache.delete(`user:${userId}:*`); +await RunCache.delete(`user:${userId}:*`); ``` ### 2. API Response Caching @@ -208,14 +208,14 @@ Cache API responses with structured keys: ```typescript // Cache API responses -await RunCache.set({ - key: `api:users:list:page=${page}:limit=${limit}`, - value: JSON.stringify(usersList), +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 -RunCache.delete('api:users:list:*'); +await RunCache.delete('api:users:list:*'); ``` ### 3. Feature Flags @@ -249,7 +249,7 @@ await RunCache.set({ key: 'org:1:dept:marketing:team:content', value: '...' }); const engineeringTeams = await RunCache.get('org:1:dept:engineering:team:*'); // Delete all marketing teams -RunCache.delete('org:1:dept:marketing:team:*'); +await RunCache.delete('org:1:dept:marketing:team:*'); ``` ## Advanced Pattern Matching Techniques @@ -268,7 +268,7 @@ function generateUserPattern(userId, section = null) { // Usage const userProfileData = await RunCache.get(generateUserPattern(userId, 'profile')); -RunCache.delete(generateUserPattern(userId)); // Delete all user data +await RunCache.delete(generateUserPattern(userId)); // Delete all user data ``` ### 2. Pattern-Based Cache Warming @@ -279,12 +279,12 @@ Use patterns to implement cache warming strategies: 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: JSON.stringify(userData.profile) }); - await RunCache.set({ key: `user:${userId}:preferences`, value: JSON.stringify(userData.preferences) }); + await RunCache.set({ key: `user:${userId}:profile`, value: userData.profile }); + await RunCache.set({ key: `user:${userId}:preferences`, value: userData.preferences }); // ...more user data } } @@ -304,7 +304,7 @@ await RunCache.set({ }); // Listen for refetch events on all region stats -RunCache.onKeyRefetch('data:region:*:stats', (event) => { +await RunCache.onKeyRefetch('data:region:*:stats', (event) => { console.log(`Stats for ${event.key} were refreshed`); }); diff --git a/gitbook/features/source-functions.md b/gitbook/features/source-functions.md index ca18071..6a4732e 100644 --- a/gitbook/features/source-functions.md +++ b/gitbook/features/source-functions.md @@ -23,7 +23,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/users/1'); const data = await response.json(); - return JSON.stringify(data); + return data; } }); ``` @@ -46,7 +46,7 @@ await RunCache.set({ key: 'computed-value', sourceFn: () => { const result = performExpensiveCalculation(); - return JSON.stringify(result); + return result; } }); ``` @@ -59,7 +59,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/data'); const data = await response.json(); - return JSON.stringify(data); + return data; } }); ``` @@ -76,7 +76,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.weather.com/current'); const data = await response.json(); - return JSON.stringify(data); + return data; }, ttl: 30 * 60 * 1000 // 30 minutes }); @@ -97,7 +97,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/stocks'); const data = await response.json(); - return JSON.stringify(data); + return data; }, ttl: 60000, // 1 minute autoRefetch: true @@ -153,9 +153,9 @@ If the source function throws during an automatic refetch: ```typescript // Register for refetch failure events -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`Failed to refresh ${event.key}:`, event.error); - + // Implement retry logic setTimeout(() => RunCache.refetch(event.key), 30000); }); @@ -172,8 +172,7 @@ You can create source functions that use parameters from the cache key: function createUserProfileSource(userId) { return async () => { const response = await fetch(`https://api.example.com/users/${userId}`); - const data = await response.json(); - return JSON.stringify(data); + return response.json(); }; } @@ -196,27 +195,26 @@ 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) { - return JSON.parse(cachedResponse); + 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 JSON.stringify(data); + return data; }, ttl: options.ttl || 60000 // Default 1 minute TTL }); - + // Get the newly cached value - const freshResponse = await RunCache.get(cacheKey); - return JSON.parse(freshResponse); + return RunCache.get(cacheKey); } // Usage @@ -228,13 +226,17 @@ const userData = await cachedFetch('https://api.example.com/users/1', { ttl: 300 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 JSON.stringify(data); + return data; } }); @@ -243,15 +245,17 @@ await RunCache.set({ key: 'user:1:recommendations', sourceFn: async () => { // Get the user profile from cache first - const profileJson = await RunCache.get('user:1:profile'); - const profile = JSON.parse(profileJson); - + 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 JSON.stringify(recommendations); + return recommendations; }, - dependencies: ['user:1:profile'] // Will be invalidated when profile changes + dependencies: ['user:1:profile'] // Removed by invalidateByDependency('user:1:profile') }); ``` @@ -293,7 +297,7 @@ await RunCache.set({ throw new Error(`API returned ${response.status}`); } const data = await response.json(); - return JSON.stringify(data); + return data; } catch (error) { console.error('Source function error:', error); throw error; // Rethrow to let RunCache handle it @@ -306,6 +310,7 @@ await RunCache.set({ 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({ @@ -338,7 +343,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/users/1'); const user = await response.json(); - return JSON.stringify(user.name); // Only needed the name + return user.name; // Only needed the name } }); diff --git a/gitbook/features/ttl-expiration.md b/gitbook/features/ttl-expiration.md index c115e2e..82da4a4 100644 --- a/gitbook/features/ttl-expiration.md +++ b/gitbook/features/ttl-expiration.md @@ -17,9 +17,9 @@ Key benefits of using TTL: You can set TTL when creating a cache entry using the `set` method: ```typescript -await RunCache.set({ - key: 'user-profile', - value: JSON.stringify({ name: 'John Doe' }), +await RunCache.set({ + key: 'user-profile', + value: { name: 'John Doe' }, ttl: 3600000 // 1 hour in milliseconds }); ``` @@ -85,17 +85,17 @@ RunCache provides an event system to monitor when cache entries expire: ```typescript // Global expiry event -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache key ${event.key} expired at ${new Date(event.updatedAt + event.ttl).toISOString()}`); }); // Specific key expiry -RunCache.onKeyExpiry("api-data", (event) => { +await RunCache.onKeyExpiry("api-data", (event) => { console.log(`API data cache expired`); }); // Pattern-based expiry events -RunCache.onKeyExpiry("user-*", (event) => { +await RunCache.onKeyExpiry("user-*", (event) => { console.log(`User cache ${event.key} expired`); }); ``` @@ -117,7 +117,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.weather.com/current'); const data = await response.json(); - return JSON.stringify(data); + return data; }, ttl: 30 * 60 * 1000 // 30 minutes }); @@ -138,7 +138,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/stats'); const data = await response.json(); - return JSON.stringify(data); + return data; }, ttl: 5 * 60 * 1000, // 5 minutes autoRefetch: true @@ -159,14 +159,14 @@ When using `autoRefetch`, it's important to handle potential failures in the bac ```typescript // Global refetch failure event -RunCache.onRefetchFailure((event) => { - console.error(`Failed to refresh cache key ${event.key}: ${event.error.message}`); +await RunCache.onRefetchFailure((event) => { + console.error(`Failed to refresh cache key ${event.key}: ${event.error}`); }); // Specific key refetch failure -RunCache.onKeyRefetchFailure("critical-stats", (event) => { - console.error(`Critical stats refresh failed: ${event.error.message}`); - +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 }); @@ -229,13 +229,13 @@ You can implement conditional expiration by checking certain conditions before r ```typescript async function getWithConditionalRefresh(key) { const value = await RunCache.get(key); - + // If value exists but some condition requires refresh - if (value && shouldRefreshData(JSON.parse(value))) { + if (value !== undefined && shouldRefreshData(value)) { await RunCache.refetch(key); return await RunCache.get(key); } - + return value; } diff --git a/gitbook/getting-started/basic-usage.md b/gitbook/getting-started/basic-usage.md index 2141cd7..d199727 100644 --- a/gitbook/getting-started/basic-usage.md +++ b/gitbook/getting-started/basic-usage.md @@ -21,12 +21,12 @@ The most basic operation is storing a value in the cache: await RunCache.set({ key: 'greeting', value: 'Hello, World!' }); ``` -When working with objects or complex data, you need to stringify them first: +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: JSON.stringify(user) }); +await RunCache.set({ key: 'user:1', value: user }); ``` ### Getting Cache Values @@ -38,10 +38,10 @@ To retrieve values from the cache: const greeting = await RunCache.get('greeting'); console.log(greeting); // Output: Hello, World! -// Get and parse a JSON object -const userJson = await RunCache.get('user:1'); -if (userJson) { - const user = JSON.parse(userJson); +// 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 } ``` @@ -81,8 +81,8 @@ You can set an expiration time for cache entries using the `ttl` parameter (in m ```typescript // Cache with 5-minute expiration -await RunCache.set({ - key: 'temporary-data', +await RunCache.set({ + key: 'temporary-data', value: 'This will expire soon', ttl: 5 * 60 * 1000 // 5 minutes in milliseconds }); @@ -99,11 +99,11 @@ Source functions allow you to generate cache values dynamically. This is particu async function fetchUserData(userId) { console.log(`Fetching data for user ${userId}...`); // Simulate API call - return JSON.stringify({ - id: userId, + return { + id: userId, name: `User ${userId}`, lastUpdated: new Date().toISOString() - }); + }; } // Cache the result of the source function @@ -139,7 +139,7 @@ await RunCache.set({ sourceFn: async () => { // Simulate API call const price = Math.floor(Math.random() * 1000) / 10; - return JSON.stringify({ symbol: 'AAPL', price }); + return { symbol: 'AAPL', price }; }, ttl: 60000, // 1 minute autoRefetch: true @@ -232,14 +232,14 @@ Configure RunCache with global settings: import { RunCache, EvictionPolicy } from 'run-cache'; // Configure cache settings -RunCache.configure({ +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 = RunCache.getConfig(); +const config = await RunCache.getConfig(); console.log(config); ``` @@ -256,27 +256,27 @@ 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 JSON.parse(cachedUser); + 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: JSON.stringify(userData), + await RunCache.set({ + key: cacheKey, + value: userData, ttl: 60 * 60 * 1000 // 1 hour }); - + return userData; } catch (error) { console.error('Error fetching user data:', error); diff --git a/gitbook/getting-started/installation.md b/gitbook/getting-started/installation.md index afaaae2..934168f 100644 --- a/gitbook/getting-started/installation.md +++ b/gitbook/getting-started/installation.md @@ -68,10 +68,14 @@ RunCache includes TypeScript definitions, so no additional packages are required import { RunCache, EvictionPolicy } from 'run-cache'; // Configure with proper type checking -RunCache.configure({ - maxEntries: 100, - evictionPolicy: EvictionPolicy.LRU -}); +async function setupCache(): Promise { + await RunCache.configure({ + maxEntries: 100, + evictionPolicy: EvictionPolicy.LRU + }); +} + +setupCache().catch(console.error); ``` ## Verifying Installation diff --git a/gitbook/getting-started/typed-caching.md b/gitbook/getting-started/typed-caching.md index e4ed54d..a3895fe 100644 --- a/gitbook/getting-started/typed-caching.md +++ b/gitbook/getting-started/typed-caching.md @@ -45,7 +45,7 @@ interface User { const user: User = { id: 123, - name: 'John Doe', + name: 'John Doe', email: 'john@example.com', preferences: { theme: 'dark', @@ -81,8 +81,8 @@ const products: Product[] = [ ]; // Cache arrays with type safety -await RunCache.set({ - key: 'products:featured', +await RunCache.set({ + key: 'products:featured', value: products, ttl: 300000 // 5 minutes }); @@ -104,8 +104,8 @@ For better type safety and organization, you can create typed cache instances: const userCache = RunCache.createTypedCache(); // All operations are now strongly typed for User objects -await userCache.set({ - key: 'user:456', +await userCache.set({ + key: 'user:456', value: { id: 456, name: 'Jane Smith', @@ -176,7 +176,7 @@ interface WeatherData { 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, @@ -209,7 +209,7 @@ RunCache supports complex TypeScript types including unions and enums: ```typescript enum UserRole { ADMIN = 'admin', - MODERATOR = 'moderator', + MODERATOR = 'moderator', USER = 'user' } @@ -261,9 +261,9 @@ const partialSettings: Partial = { notifications: { email: true } }; -await RunCache.set>({ - key: 'settings:partial:123', - value: partialSettings +await RunCache.set>({ + key: 'settings:partial:123', + value: partialSettings }); const settings = await RunCache.get>('settings:partial:123'); @@ -286,7 +286,7 @@ interface EntityCache { } async function cacheEntity( - id: string, + id: string, entity: T ): Promise { const cacheEntry: EntityCache = { @@ -294,7 +294,7 @@ async function cacheEntity( lastModified: new Date(), version: 1 }; - + await RunCache.set>({ key: `entity:${id}`, value: cacheEntry, @@ -366,11 +366,11 @@ await RunCache.invalidateByTag('user'); ### Events with Types ```typescript -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`User ${event.value.name} expired from cache`); }); -RunCache.onKeyExpiry('product:*', (event) => { +await RunCache.onKeyExpiry('product:*', (event) => { console.log(`Product ${event.value.name} expired`); }); ``` @@ -390,6 +390,7 @@ await RunCache.set({ 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' }); @@ -402,6 +403,7 @@ 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' }) }); diff --git a/gitbook/guides/best-practices.md b/gitbook/guides/best-practices.md index 874255e..9a221f5 100644 --- a/gitbook/guides/best-practices.md +++ b/gitbook/guides/best-practices.md @@ -55,21 +55,21 @@ Set TTL values based on how frequently the underlying data changes: // Frequently changing data await RunCache.set({ key: 'stock-price', - value: JSON.stringify(price), + value: price, ttl: 60 * 1000 // 1 minute }); // Relatively stable data await RunCache.set({ key: 'product-catalog', - value: JSON.stringify(catalog), + value: catalog, ttl: 60 * 60 * 1000 // 1 hour }); // Very stable data await RunCache.set({ key: 'app-configuration', - value: JSON.stringify(config), + value: config, ttl: 24 * 60 * 60 * 1000 // 1 day }); ``` @@ -150,7 +150,7 @@ await RunCache.set({ throw new Error(`API returned ${response.status}`); } const data = await response.json(); - return JSON.stringify(data); + return data; } catch (error) { console.error('Source function error:', error); throw error; // Rethrow to let RunCache handle it @@ -173,7 +173,7 @@ await RunCache.set({ sourceFn: async () => { const response = await fetch('https://api.example.com/users/1'); const user = await response.json(); - return JSON.stringify(user.name); // Only needed the name + return user.name; // Only needed the name } }); @@ -220,18 +220,22 @@ await RunCache.set({ Always handle potential failures in automatic refetching: ```typescript -RunCache.onRefetchFailure((event) => { +// 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 = (event.metadata?.retryCount || 0) + 1; + 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, { - metadata: { retryCount } - }); + RunCache.refetch(event.key) + .then((ok) => { if (ok) retryCounts.delete(event.key); }) + .catch(() => { /* reported again through onRefetchFailure */ }); }, delay); }); ``` @@ -273,20 +277,20 @@ Tags are ideal for grouping related cache entries that need to be invalidated to ```typescript // Set entries with tags -await RunCache.set({ - key: 'user:1:profile', - value: '...', +await RunCache.set({ + key: 'user:1:profile', + value: '...', tags: ['user:1', 'profile'] }); -await RunCache.set({ - key: 'user:1:settings', - value: '...', +await RunCache.set({ + key: 'user:1:settings', + value: '...', tags: ['user:1', 'settings'] }); // Later, invalidate all user:1 data -RunCache.invalidateByTag('user:1'); +await RunCache.invalidateByTag('user:1'); ``` ### Use Dependencies for Derived Data @@ -297,13 +301,13 @@ Dependencies are ideal for derived data that depends on base data: // Primary data await RunCache.set({ key: 'user:1:profile', - value: JSON.stringify({ name: 'John Doe' }) + value: { name: 'John Doe' } }); // Dependent data await RunCache.set({ key: 'user:1:dashboard', - value: JSON.stringify({ widgets: [...] }), + value: { widgets: [...] }, dependencies: ['user:1:profile'] // This entry depends on the profile }); @@ -331,12 +335,12 @@ Event handlers should be fast and non-blocking: ```typescript // Good - lightweight handler -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache expired: ${event.key}`); }); // Avoid - heavy processing in handler -RunCache.onExpiry(async (event) => { +await RunCache.onExpiry(async (event) => { // DON'T do this - blocks the event loop await heavyProcessing(); await networkRequest(); @@ -351,23 +355,22 @@ Remove event listeners when they're no longer needed: ```typescript // In a component or module initialization -function initializeModule() { +async function initializeModule() { // Set up event listeners - RunCache.onKeyRefetch('module-data', handleRefetch); - + await RunCache.onKeyRefetch('module-data', handleRefetch); + // Return cleanup function - return () => { + return () => RunCache.clearEventListeners({ event: EVENT.REFETCH, key: 'module-data' }); - }; } // Later, when shutting down -const cleanup = initializeModule(); +const cleanup = await initializeModule(); // When module is unloaded -cleanup(); +await cleanup(); ``` ## Memory Management @@ -378,7 +381,7 @@ Configure maximum cache size based on your application's memory constraints: ```typescript // Configure cache with size limits -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, // Limit to 1000 entries evictionPolicy: EvictionPolicy.LRU }); @@ -394,13 +397,13 @@ Select an eviction policy that matches your access patterns: ```typescript // For most applications -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU }); // For frequency-based patterns -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LFU }); @@ -414,30 +417,30 @@ Minimize the size of cached values: // Bad - storing unnecessary data await RunCache.set({ key: 'user-profile', - value: JSON.stringify({ + 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: JSON.stringify({ + 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: JSON.stringify(completeUserHistory), + value: completeUserHistory, ttl: 3600000 // With shorter TTL }); ``` @@ -454,17 +457,17 @@ Select the appropriate storage adapter based on your environment and requirement ```typescript // For browser with small data -RunCache.configure({ +await RunCache.configure({ storageAdapter: new LocalStorageAdapter() }); // For browser with larger data -RunCache.configure({ +await RunCache.configure({ storageAdapter: new IndexedDBAdapter() }); // For Node.js applications -RunCache.configure({ +await RunCache.configure({ storageAdapter: new FilesystemAdapter() }); ``` @@ -489,10 +492,10 @@ Balance between data freshness and performance: ```typescript // For frequently changing data, save more often -RunCache.setupAutoSave(60000); // 1 minute +await RunCache.setupAutoSave(60000); // 1 minute // For relatively stable data, save less frequently -RunCache.setupAutoSave(3600000); // 1 hour +await RunCache.setupAutoSave(3600000); // 1 hour ``` ## Error Handling @@ -504,15 +507,14 @@ Always handle potential cache misses: ```typescript // Good - handles cache miss const userData = await RunCache.get('user:1'); -if (userData) { - // Cache hit - const user = JSON.parse(userData); - displayUser(user); +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: JSON.stringify(user) }); + await RunCache.set({ key: 'user:1', value: user }); displayUser(user); } ``` @@ -531,15 +533,15 @@ async function getCachedData(key) { // Circuit is open, bypass cache return fetchDataFromSource(key); } - + try { const data = await RunCache.get(key); - if (data) return JSON.parse(data); - + if (data !== undefined) return data; + // Cache miss, fetch from source const sourceData = await fetchDataFromSource(key); try { - await RunCache.set({ key, value: JSON.stringify(sourceData) }); + await RunCache.set({ key, value: sourceData }); } catch (error) { cacheFailures++; if (cacheFailures === FAILURE_THRESHOLD) { @@ -573,7 +575,7 @@ for (const id of userIds) { // More efficient - batch processing async function batchSetProfiles(profiles) { - const operations = Object.entries(profiles).map(([id, profile]) => + const operations = Object.entries(profiles).map(([id, profile]) => RunCache.set({ key: `user:${id}:profile`, value: profile }) ); await Promise.all(operations); @@ -589,22 +591,22 @@ 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: JSON.stringify(config) }); + await RunCache.set({ key: 'app:config', value: config }); } - + if (!hasGlobalData) { const globalData = await fetchGlobalData(); - await RunCache.set({ key: 'app:global-data', value: JSON.stringify(globalData) }); + await RunCache.set({ key: 'app:global-data', value: globalData }); } - + console.log('Cache warming complete'); } @@ -618,18 +620,18 @@ Implement middleware for functionality that applies to all cache operations: ```typescript // Add logging middleware -RunCache.use(async (value, context, next) => { +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 -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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); @@ -666,24 +668,24 @@ export function mockRunCache() { 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), @@ -703,33 +705,45 @@ export function mockRunCache() { Test the cache with actual storage adapters: ```typescript -// Use in-memory adapter for tests -import { RunCache, MemoryStorageAdapter } from 'run-cache'; +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 - RunCache.configure({ + 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); }); @@ -753,7 +767,7 @@ let metrics = { }; // Add monitoring middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { if (context.operation === 'get') { const result = await next(value); if (result) { @@ -767,16 +781,16 @@ RunCache.use(async (value, context, next) => { }); // Monitor events -RunCache.onExpiry(() => metrics.expirations++); -RunCache.onRefetch(() => metrics.refetches++); -RunCache.onRefetchFailure(() => metrics.errors++); +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, @@ -784,7 +798,7 @@ setInterval(() => { cacheRefetches: metrics.refetches, cacheErrors: metrics.errors }); - + // Reset counters metrics = { hits: 0, misses: 0, expirations: 0, refetches: 0, errors: 0 }; }, 60000); // Every minute @@ -796,21 +810,21 @@ Use middleware and events for comprehensive logging: ```typescript // Log all cache operations -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`Cache operation: ${context.operation}, Key: ${context.key}`); return next(value); }); // Log cache events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Cache expired: ${event.key}`); }); -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`Cache refreshed: ${event.key}`); }); -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`Cache refresh failed: ${event.key}`, event.error); }); ``` diff --git a/gitbook/guides/debugging.md b/gitbook/guides/debugging.md index ba1933a..93d6bc7 100644 --- a/gitbook/guides/debugging.md +++ b/gitbook/guides/debugging.md @@ -14,7 +14,7 @@ To enable debug logging: import { RunCache } from 'run-cache'; // Enable debug logging -RunCache.configure({ +await RunCache.configure({ debug: true }); ``` @@ -25,7 +25,7 @@ When debug mode is enabled, RunCache logs detailed information about: - Refetch operations and failures - Configuration changes -All logs include timestamps and operation details. +All logs include timestamps and operation details. Nothing is logged, not even errors, while debug mode is off. ### Disabling debug Mode @@ -33,7 +33,7 @@ To disable debug logging when you're done debugging: ```typescript // Disable debug logging -RunCache.configure({ +await RunCache.configure({ debug: false }); ``` @@ -48,9 +48,9 @@ You can implement more detailed custom logging using middleware. import { RunCache } from 'run-cache'; // Add logging middleware -RunCache.use(async (value, context, next) => { +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}`); @@ -67,21 +67,21 @@ RunCache.use(async (value, context, next) => { For more advanced logging with performance metrics: ```typescript -RunCache.use(async (value, context, next) => { +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; @@ -89,7 +89,7 @@ RunCache.use(async (value, context, next) => { `[RunCache] ERROR ${operation} - Key: ${context.key}, Duration: ${duration.toFixed(2)}ms, ` + `Error: ${error.message}` ); - + throw error; } }); @@ -114,23 +114,23 @@ const logger = winston.createLogger({ }); // Add winston logging middleware -RunCache.use(async (value, context, next) => { +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({ @@ -140,7 +140,7 @@ RunCache.use(async (value, context, next) => { error: error.message, stack: error.stack }); - + throw error; } }); @@ -156,47 +156,49 @@ The event system provides another way to debug and monitor cache operations. import { RunCache, EVENT } from 'run-cache'; // Monitor expiry events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`[RunCache] Key expired: ${event.key}, TTL: ${event.ttl}ms`); }); // Monitor refetch events -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`[RunCache] Key refreshed: ${event.key}`); }); // Monitor refetch failures -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`[RunCache] Refresh failed for key: ${event.key}`, event.error); }); // Monitor tag invalidations -RunCache.onTagInvalidation((event) => { +await RunCache.onTagInvalidation((event) => { console.log(`[RunCache] Key invalidated by tag: ${event.key}, Tag: ${event.tag}`); }); // Monitor dependency invalidations -RunCache.onDependencyInvalidation((event) => { +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 -RunCache.onKeyExpiry('important-data', (event) => { +await RunCache.onKeyExpiry('important-data', (event) => { console.log(`[RunCache] Important data expired at ${new Date().toISOString()}`); }); -RunCache.onKeyRefetch('important-data', (event) => { +await RunCache.onKeyRefetch('important-data', (event) => { console.log(`[RunCache] Important data refreshed at ${new Date().toISOString()}`); }); -RunCache.onKeyRefetchFailure('important-data', (event) => { - console.error(`[RunCache] Important data refresh failed:`, event.error); +await RunCache.onKeyRefetchFailure('important-data', (event) => { + console.error(`[RunCache] Important data refresh failed: ${event.key}`); }); ``` @@ -206,12 +208,12 @@ You can use patterns to monitor groups of related keys: ```typescript // Monitor all user-related expirations -RunCache.onKeyExpiry('user:*', (event) => { +await RunCache.onKeyExpiry('user:*', (event) => { console.log(`[RunCache] User data expired: ${event.key}`); }); // Monitor all API-related refresh failures -RunCache.onKeyRefetchFailure('api:*', (event) => { +await RunCache.onKeyRefetchFailure('api:*', (event) => { console.error(`[RunCache] API data refresh failed: ${event.key}`, event.error); }); ``` @@ -220,42 +222,43 @@ RunCache.onKeyRefetchFailure('api:*', (event) => { ### Diagnosing Cache Misses -If you're experiencing unexpected cache misses: +Middleware only runs for `get` on a hit, so it cannot see misses. `debug: true` logs every read with the reason: ```typescript -// Debug cache misses with middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'get') { - const result = await next(value); - if (!result) { - console.log(`[RunCache] Cache miss for key: ${context.key}`); - - // Check if the key exists but is expired - // Note: This is internal API usage for debugging only - const internalCache = RunCache.getInternalCache(); - if (internalCache.has(context.key)) { - const entry = internalCache.get(context.key); - if (entry && entry.ttl && Date.now() > entry.updatedAt + entry.ttl) { - console.log(`[RunCache] Key ${context.key} exists but has expired. ` + - `Expired at ${new Date(entry.updatedAt + entry.ttl).toISOString()}`); - } else { - console.log(`[RunCache] Key ${context.key} exists but returned no value.`); - } - } - } - return result; +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 next(value); -}); + 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 -RunCache.use(async (value, context, next) => { +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, ` + @@ -266,7 +269,7 @@ RunCache.use(async (value, context, next) => { }); // Monitor all expiry events -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log( `[RunCache] Key ${event.key} expired. ` + `TTL was ${event.ttl}ms. ` + @@ -278,34 +281,17 @@ RunCache.onExpiry((event) => { ### Debugging Automatic Refetching -If automatic refetching isn't working as expected: +`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. -```typescript -// Debug auto-refetch setup -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && context.autoRefetch) { - console.log( - `[RunCache] Setting up auto-refetch for key ${context.key}. ` + - `TTL: ${context.ttl}ms, Source function provided: ${!!context.sourceFn}` - ); - - if (!context.ttl) { - console.warn(`[RunCache] Warning: Auto-refetch enabled for ${context.key} but no TTL provided.`); - } - - if (!context.sourceFn) { - console.warn(`[RunCache] Warning: Auto-refetch enabled for ${context.key} but no source function provided.`); - } - } - return next(value); -}); +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 -RunCache.onRefetch((event) => { +await RunCache.onRefetch((event) => { console.log(`[RunCache] Auto-refetch successful for key: ${event.key}`); }); -RunCache.onRefetchFailure((event) => { +await RunCache.onRefetchFailure((event) => { console.error(`[RunCache] Auto-refetch failed for key: ${event.key}:`, event.error); }); ``` @@ -320,13 +306,13 @@ 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 length: ${result ? result.length : 0}` + `Result: ${typeof result}` ); return result; } catch (error) { @@ -345,8 +331,7 @@ await RunCache.set({ key: 'data', sourceFn: debugSourceFn('data', async () => { const response = await fetch('https://api.example.com/data'); - const data = await response.json(); - return JSON.stringify(data); + return response.json(); }), ttl: 60000, autoRefetch: true @@ -355,39 +340,28 @@ await RunCache.set({ ### Debugging Storage Adapters -If you're having issues with persistent storage: +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 -// Add storage debugging -const originalSave = storageAdapter.save; -const originalLoad = storageAdapter.load; - -storageAdapter.save = async function(data) { - console.log(`[RunCache] Saving ${data.length} bytes to storage`); - try { - await originalSave.call(this, data); - console.log(`[RunCache] Successfully saved to storage`); - } catch (error) { - console.error(`[RunCache] Failed to save to storage:`, error); - throw error; - } -}; +import { RunCache, FilesystemAdapter, type StorageAdapter } from 'run-cache'; -storageAdapter.load = async function() { - console.log(`[RunCache] Loading from storage`); - try { - const data = await originalLoad.call(this); - console.log(`[RunCache] Successfully loaded ${data ? data.length : 0} bytes from storage`); - return data; - } catch (error) { - console.error(`[RunCache] Failed to load from storage:`, error); - throw error; - } -}; +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() + }; +} -// Then configure RunCache with the patched adapter -RunCache.configure({ - storageAdapter: storageAdapter +await RunCache.configure({ + storageAdapter: withLogging(new FilesystemAdapter({ storageKey: 'my-app-cache' })) }); ``` @@ -411,14 +385,14 @@ class CacheLogger { 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, @@ -426,7 +400,7 @@ class CacheLogger { message, ...data }; - + for (const transport of this.transports) { if (typeof transport[level] === 'function') { transport[level](message, logObj); @@ -435,7 +409,7 @@ class CacheLogger { } } } - + error(message, data) { this.log('error', message, data); } warn(message, data) { this.log('warn', message, data); } info(message, data) { this.log('info', message, data); } @@ -453,24 +427,24 @@ export const logger = new CacheLogger({ level: process.env.LOG_LEVEL || 'info' } import { RunCache } from 'run-cache'; import { logger } from './logger'; -export function setupCacheLogging() { - // Add logging middleware - RunCache.use(async (value, context, next) => { - logger.debug(`Operation ${context.operation} started for key: ${context.key}`, { +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}`, { + 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}`, { + logger.error(`Operation ${context.operation} failed for key: ${context.key}`, { operation: context.operation, key: context.key, error: error.message, @@ -479,43 +453,42 @@ export function setupCacheLogging() { throw error; } }); - + // Set up event logging - RunCache.onExpiry((event) => { - logger.debug(`Key expired: ${event.key}`, { + await RunCache.onExpiry((event) => { + logger.debug(`Key expired: ${event.key}`, { event: 'expire', key: event.key, ttl: event.ttl, updatedAt: event.updatedAt }); }); - - RunCache.onRefetch((event) => { - logger.debug(`Key refreshed: ${event.key}`, { + + await RunCache.onRefetch((event) => { + logger.debug(`Key refreshed: ${event.key}`, { event: 'refetch', key: event.key }); }); - - RunCache.onRefetchFailure((event) => { - logger.error(`Refresh failed for key: ${event.key}`, { + + await RunCache.onRefetchFailure((event) => { + logger.error(`Refresh failed for key: ${event.key}`, { event: 'refetch_failure', key: event.key, - error: event.error.message, - stack: event.error.stack + error: event.error }); }); - - RunCache.onTagInvalidation((event) => { - logger.debug(`Key invalidated by tag: ${event.key}`, { + + await RunCache.onTagInvalidation((event) => { + logger.debug(`Key invalidated by tag: ${event.key}`, { event: 'tag_invalidation', key: event.key, tag: event.tag }); }); - - RunCache.onDependencyInvalidation((event) => { - logger.debug(`Key invalidated by dependency: ${event.key}`, { + + await RunCache.onDependencyInvalidation((event) => { + logger.debug(`Key invalidated by dependency: ${event.key}`, { event: 'dependency_invalidation', key: event.key, dependencyKey: event.dependencyKey @@ -532,7 +505,7 @@ For browser environments: ```typescript // Enable detailed console output -RunCache.configure({ debug: true }); +await RunCache.configure({ debug: true }); // Use browser dev tools // 1. Set breakpoints in source functions @@ -541,16 +514,16 @@ RunCache.configure({ debug: true }); // 4. Watch for errors in the console // Add a global debug function -window.__debugRunCache = function(pattern = '*') { +window.__debugRunCache = async function(pattern = '*') { return { - entries: RunCache.get(pattern), - config: RunCache.getConfig(), + entries: await RunCache.get(pattern), + config: await RunCache.getConfig(), // Add any other debug info you need }; }; // In browser console, you can now run: -// > window.__debugRunCache('user:*') +// > await window.__debugRunCache('user:*') ``` ### Node.js Debugging @@ -562,15 +535,15 @@ For Node.js environments: // Start Node with: node --inspect your-script.js // Add debug endpoints to Express app -app.get('/debug/cache', (req, res) => { +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 = RunCache.get(pattern); - const config = RunCache.getConfig(); - + const entries = await RunCache.get(pattern); + const config = await RunCache.getConfig(); + res.json({ pattern, entries, @@ -584,68 +557,97 @@ app.get('/debug/cache', (req, res) => { ### Cache Inspector Utility -Create a utility for inspecting the cache: +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 getEntries(pattern = '*') { - const entries = await RunCache.get(pattern); - return Array.isArray(entries) ? entries : [entries].filter(Boolean); + 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 getKeys(pattern = '*') { - // Implementation depends on internal APIs - // This is for illustration purposes - const internalCache = RunCache.getInternalCache(); - return Array.from(internalCache.keys()) - .filter(key => key.includes(pattern.replace('*', ''))); - } - - static async getStats() { - const keys = await this.getKeys(); - const values = await Promise.all(keys.map(key => RunCache.get(key))); - - const totalSize = values.reduce((size, value) => { - return size + (value ? value.length : 0); - }, 0); - - return { - entryCount: keys.length, - totalSize, - averageSize: keys.length ? totalSize / keys.length : 0 - }; + + static async countMatching(pattern = '*') { + return (await this.getValues(pattern)).length; } - - static async analyzePatterns() { - const keys = await this.getKeys(); - const patterns = {}; - - // Simple pattern analysis - keys.forEach(key => { - const parts = key.split(':'); - const prefix = parts[0]; - patterns[prefix] = (patterns[prefix] || 0) + 1; - }); - - return patterns; + + 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 -Create a utility for monitoring cache performance: +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, hits: 0, misses: 0, totalTime: 0 }, + get: { count: 0, totalTime: 0 }, set: { count: 0, totalTime: 0 }, - delete: { count: 0, totalTime: 0 } + refetch: { count: 0, totalTime: 0 } }, events: { expire: 0, @@ -655,72 +657,12 @@ export class CachePerformanceMonitor { dependency_invalidation: 0 } }; - - this.setupMonitoring(); - } - - setupMonitoring() { - // Add performance middleware - RunCache.use(async (value, context, next) => { - const start = performance.now(); - const result = await next(value); - const duration = performance.now() - start; - - if (this.metrics.operations[context.operation]) { - this.metrics.operations[context.operation].count++; - this.metrics.operations[context.operation].totalTime += duration; - - if (context.operation === 'get') { - if (result) { - this.metrics.operations.get.hits++; - } else { - this.metrics.operations.get.misses++; - } - } - } - - return result; - }); - - // Track events - RunCache.onExpiry(() => this.metrics.events.expire++); - RunCache.onRefetch(() => this.metrics.events.refetch++); - RunCache.onRefetchFailure(() => this.metrics.events.refetch_failure++); - RunCache.onTagInvalidation(() => this.metrics.events.tag_invalidation++); - RunCache.onDependencyInvalidation(() => this.metrics.events.dependency_invalidation++); - } - - getMetrics() { - const metrics = JSON.parse(JSON.stringify(this.metrics)); - - // Add calculated metrics - const hitRatio = metrics.operations.get.hits / - (metrics.operations.get.hits + metrics.operations.get.misses || 1); - metrics.hitRatio = hitRatio; - - for (const [op, data] of Object.entries(metrics.operations)) { - if (data.count > 0) { - data.avgTime = data.totalTime / data.count; - } - } - - return metrics; - } - - resetMetrics() { - for (const op in this.metrics.operations) { - this.metrics.operations[op] = { - count: 0, - totalTime: 0, - ...(op === 'get' ? { hits: 0, misses: 0 } : {}) - }; - } - - for (const event in this.metrics.events) { - this.metrics.events[event] = 0; - } } } + +// Usage +const monitor = new CachePerformanceMonitor(); +await monitor.start(); ``` ## Best Practices for Debugging diff --git a/gitbook/guides/migration-guide.md b/gitbook/guides/migration-guide.md index 27d02d9..39ea861 100644 --- a/gitbook/guides/migration-guide.md +++ b/gitbook/guides/migration-guide.md @@ -12,6 +12,7 @@ RunCache now supports any serializable JavaScript type while maintaining 100% ba 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' }); @@ -47,12 +48,13 @@ await RunCache.set({ key: 'legacy:user:name', value: 'John Doe' }); 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) +await RunCache.set({ + key: 'user:1', + value: JSON.stringify(userData) }); const userJson = await RunCache.get('user:1'); const user = userJson ? JSON.parse(userJson) : null; @@ -74,6 +76,7 @@ const user = await RunCache.get('user:1'); // User | undefined ### 1. Simple Object Caching **Before:** + ```typescript const config = { theme: 'dark', language: 'en' }; await RunCache.set({ key: 'config', value: JSON.stringify(config) }); @@ -98,27 +101,28 @@ 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, + await RunCache.set({ + key: cacheKey, value: JSON.stringify(userData), - ttl: 300000 + ttl: 300000 }); - + return userData; } ``` @@ -137,24 +141,24 @@ interface User { 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, + await RunCache.set({ + key: cacheKey, value: userData, - ttl: 300000 + ttl: 300000 }); - + return userData; } ``` @@ -162,6 +166,7 @@ async function fetchUserData(userId: number): Promise { ### 3. Source Functions with Types **Before:** + ```typescript await RunCache.set({ key: 'weather:current', @@ -201,15 +206,16 @@ const weather = await RunCache.get('weather:current'); // WeatherDa ### 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) +await RunCache.set({ + key: 'products:featured', + value: JSON.stringify(products) }); const productsJson = await RunCache.get('products:featured'); @@ -229,9 +235,9 @@ const products: Product[] = [ { id: 2, name: 'Mouse', price: 29 } ]; -await RunCache.set({ - key: 'products:featured', - value: products +await RunCache.set({ + key: 'products:featured', + value: products }); const productList = await RunCache.get('products:featured'); // Product[] | undefined @@ -261,17 +267,8 @@ const productList = await RunCache.get('products:featured'); // Produ You can use these utilities to help with migration: ```typescript -// Helper function to detect if a cached value is typed or legacy -function isLegacyStringValue(value: string): boolean { - try { - JSON.parse(value); - return true; // It's a JSON string - } catch { - return true; // It's a plain string - } -} - -// Migration helper for gradual conversion +// 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') { @@ -298,14 +295,14 @@ For large-scale migrations, you can use pattern matching: 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 }); @@ -332,9 +329,9 @@ interface AppSettings { version: string; } -await RunCache.set({ - key: 'modern:settings', - value: { theme: 'dark', version: '2.0.0' } +await RunCache.set({ + key: 'modern:settings', + value: { theme: 'dark', version: '2.0.0' } }); // Both work together @@ -357,10 +354,10 @@ describe('Migration Tests', () => { 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'); }); @@ -402,7 +399,7 @@ await RunCache.set({ key: 'circular', value: obj }); // Will fail **Solution:** ```typescript // Use custom serialization or break circular references -const safeObj = { +const safeObj = { name: obj.name, // Don't include circular properties }; @@ -421,12 +418,11 @@ const retrieved = await RunCache.get('date'); **Solution:** ```typescript -// Use serialization adapters for Date objects -import { DateSerializationAdapter } from 'run-cache'; - -RunCache.addSerializationAdapter(new DateSerializationAdapter()); +// Store dates as ISO strings and convert them back after reading +await RunCache.set({ key: 'date', value: { timestamp: new Date().toISOString() } }); -// Now Date objects are properly serialized/deserialized +const retrieved = (await RunCache.get('date')) as { timestamp: string } | undefined; +const timestamp = retrieved && new Date(retrieved.timestamp); ``` ### 3. Function Properties @@ -474,7 +470,7 @@ const serializableObj = { ## Next Steps -- Explore [Serialization Adapters](../advanced/serialization-adapters.md) for custom types -- Learn about [Type Validation](../advanced/type-validation.md) for runtime checking +- 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/guides/performance.md b/gitbook/guides/performance.md index b58ffde..7e25c2e 100644 --- a/gitbook/guides/performance.md +++ b/gitbook/guides/performance.md @@ -24,7 +24,7 @@ Configure appropriate size limits and eviction policies for your use case: import { RunCache, EvictionPolicy } from 'run-cache'; // For most applications -RunCache.configure({ +await RunCache.configure({ maxEntries: 1000, // Limit to 1000 entries evictionPolicy: EvictionPolicy.LRU }); @@ -55,7 +55,7 @@ setInterval(() => { let hits = 0; let misses = 0; -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { if (context.operation === 'get') { const result = await next(value); if (result) { @@ -88,9 +88,9 @@ Key design significantly impacts performance: await RunCache.set({ key: `user:${userId}:preferences:theme:color:mode:${mode}:variant:${variant}`, value: '...' }); // More efficient - simpler keys with structured data -await RunCache.set({ +await RunCache.set({ key: `user:${userId}:theme-settings`, - value: JSON.stringify({ mode, variant, color }) + value: { mode, variant, color } }); ``` @@ -121,7 +121,7 @@ await RunCache.set({ const transformed = complexTransformation(rawData); const filtered = filterData(transformed); const sorted = sortData(filtered); - return JSON.stringify(sorted); + return sorted; } }); @@ -130,7 +130,7 @@ await RunCache.set({ key: 'data', sourceFn: async () => { const data = await fetchData(); - return JSON.stringify(data); + return data; } }); @@ -150,7 +150,7 @@ For expensive source functions, consider memoization: function createMemoizedSourceFn(fn, maxAge = 60000) { let cachedResult = null; let cachedAt = 0; - + return async () => { const now = Date.now(); if (!cachedResult || now - cachedAt > maxAge) { @@ -163,8 +163,7 @@ function createMemoizedSourceFn(fn, maxAge = 60000) { // Usage const expensiveDataFetch = createMemoizedSourceFn(async () => { - const data = await fetchExpensiveData(); - return JSON.stringify(data); + return fetchExpensiveData(); }); await RunCache.set({ @@ -247,7 +246,7 @@ const userValues = await batchGet(userKeys); // Batch set const entries = userIds.map(id => ({ key: `user:${id}`, - value: JSON.stringify({ name: `User ${id}` }) + value: { name: `User ${id}` } })); await batchSet(entries); ``` @@ -260,7 +259,7 @@ Keep middleware functions simple and focused: ```typescript // Less efficient - complex middleware -RunCache.use(async (value, context, next) => { +await RunCache.use(async (value, context, next) => { console.log(`Start ${context.operation} for ${context.key}`); const start = Date.now(); try { @@ -281,15 +280,15 @@ RunCache.use(async (value, context, next) => { }); // More efficient - simpler middleware -RunCache.use(async (value, context, next) => { +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; }); ``` @@ -300,12 +299,12 @@ Order middleware for optimal performance: ```typescript // Less efficient - expensive middleware runs first -RunCache.use(expensiveMiddleware); // Runs for all operations -RunCache.use(filterMiddleware); // Could have filtered out some operations +await RunCache.use(expensiveMiddleware); // Runs for all operations +await RunCache.use(filterMiddleware); // Could have filtered out some operations // More efficient - filtering middleware runs first -RunCache.use(filterMiddleware); // Filters out operations -RunCache.use(expensiveMiddleware); // Only runs for filtered operations +await RunCache.use(filterMiddleware); // Filters out operations +await RunCache.use(expensiveMiddleware); // Only runs for filtered operations ``` ## Optimizing Event Listeners @@ -316,13 +315,13 @@ Use specific event listeners rather than global ones: ```typescript // Less efficient - global listener for all events -RunCache.onExpiry((event) => { +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 -RunCache.onKeyExpiry('important-data', (event) => { +await RunCache.onKeyExpiry('important-data', (event) => { // Only process events for 'important-data' console.log('Important data expired'); }); @@ -334,12 +333,12 @@ Be specific with event listener patterns: ```typescript // Less efficient - very broad pattern -RunCache.onKeyExpiry('*', (event) => { +await RunCache.onKeyExpiry('*', (event) => { // Triggered for ALL expiry events }); // More efficient - more specific pattern -RunCache.onKeyExpiry('user:*', (event) => { +await RunCache.onKeyExpiry('user:*', (event) => { // Only triggered for user-related expirations }); ``` @@ -354,29 +353,29 @@ Minimize the size of cached values: // Less efficient - storing large objects await RunCache.set({ key: 'large-report', - value: JSON.stringify({ + 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: JSON.stringify({ + value: { highlights: summaryResults, timestamp: Date.now() - }) + } }); // Store additional data separately if needed await RunCache.set({ key: 'report-details', - value: JSON.stringify(detailedResults), + value: detailedResults, ttl: 3600000 // Shorter TTL for detailed data }); ``` @@ -389,32 +388,32 @@ Use appropriate TTL values to prevent memory bloat: // Strategy: Use shorter TTL for larger data await RunCache.set({ key: 'small-config', - value: JSON.stringify(smallConfig), + value: smallConfig, ttl: 86400000 // 24 hours for small data }); await RunCache.set({ key: 'large-dataset', - value: JSON.stringify(largeDataset), + value: largeDataset, ttl: 3600000 // 1 hour for large data }); // Strategy: Tiered caching with different TTLs await RunCache.set({ key: 'user:summary', - value: JSON.stringify(userSummary), + value: userSummary, ttl: 86400000 // 24 hours for summary }); await RunCache.set({ key: 'user:details', - value: JSON.stringify(userDetails), + value: userDetails, ttl: 3600000 // 1 hour for details }); await RunCache.set({ key: 'user:activity', - value: JSON.stringify(userActivity), + value: userActivity, ttl: 300000 // 5 minutes for activity }); ``` @@ -427,17 +426,17 @@ Select the most appropriate storage adapter for your needs: ```typescript // For browser environments with small data -RunCache.configure({ +await RunCache.configure({ storageAdapter: new LocalStorageAdapter() }); // For browser environments with larger data -RunCache.configure({ +await RunCache.configure({ storageAdapter: new IndexedDBAdapter() }); // For Node.js environments -RunCache.configure({ +await RunCache.configure({ storageAdapter: new FilesystemAdapter() }); ``` @@ -448,13 +447,13 @@ Balance persistence needs with performance: ```typescript // Too frequent - performance impact -RunCache.setupAutoSave(1000); // Save every second +await RunCache.setupAutoSave(1000); // Save every second // More balanced -RunCache.setupAutoSave(300000); // Save every 5 minutes +await RunCache.setupAutoSave(300000); // Save every 5 minutes // For mostly read-only data -RunCache.setupAutoSave(3600000); // Save every hour +await RunCache.setupAutoSave(3600000); // Save every hour ``` ## Advanced Performance Techniques @@ -476,40 +475,40 @@ const metrics = { }; // Performance middleware -RunCache.use(async (value, context, next) => { +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 }; @@ -528,16 +527,16 @@ For very large caches, implement a sharding strategy: 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; @@ -547,19 +546,19 @@ class ShardedCache { } 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 } @@ -578,33 +577,33 @@ 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: JSON.stringify({ id: i, data: `Test data ${i}` }) + value: { id: i, data: `Test data ${i}` } })); - + // Benchmark set operations const setStart = performance.now(); - await Promise.all(testData.map(item => + 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))); diff --git a/gitbook/mint.json b/gitbook/mint.json deleted file mode 100644 index b3d9330..0000000 --- a/gitbook/mint.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "$schema": "https://mintlify.com/schema.json", - "name": "RunCache", - "logo": { - "light": "/logo/light.svg", - "dark": "/logo/dark.svg" - }, - "favicon": "/favicon.svg", - "colors": { - "primary": "#0D9373", - "light": "#07C983", - "dark": "#0D9373" - }, - "topbarLinks": [ - { - "name": "GitHub", - "url": "https://github.com/helloscoopa/run-cache" - }, - { - "name": "NPM", - "url": "https://www.npmjs.com/package/run-cache" - } - ], - "anchors": [], - "redirects": [ - { - "source": "/", - "destination": "/getting-started/installation" - } - ], - "navigation": [ - { - "group": "Getting Started", - "pages": [ - "getting-started/installation", - "getting-started/basic-usage", - "getting-started/typed-caching" - ] - }, - { - "group": "Core Features", - "pages": [ - "features/cache-management", - "features/ttl-expiration", - "features/auto-refetch", - "features/source-functions", - "features/eviction-policies", - "features/pattern-matching" - ] - }, - { - "group": "Advanced Features", - "pages": [ - "advanced/tag-invalidation", - "advanced/dependency-tracking", - "advanced/event-system", - "advanced/middleware", - "advanced/persistent-storage", - "advanced/resource-management", - "advanced/serialization-adapters", - "advanced/type-validation" - ] - }, - { - "group": "API Reference", - "pages": [ - "api/run-cache", - "api/storage-adapters", - "api/events", - "api/types", - "api/typed-cache-interface", - "api/serialization-system" - ] - }, - { - "group": "Guides", - "pages": [ - "guides/best-practices", - "guides/performance", - "guides/debugging", - "guides/migration-guide" - ] - }, - { - "group": "Resources", - "pages": [ - "resources/faq", - "resources/contributing", - "resources/license" - ] - } - ], - "footerSocials": { - "github": "https://github.com/helloscoopa/run-cache" - } -} diff --git a/gitbook/resources/contributing.md b/gitbook/resources/contributing.md index 0f56423..b55d30c 100644 --- a/gitbook/resources/contributing.md +++ b/gitbook/resources/contributing.md @@ -1,315 +1,9 @@ # Contributing to RunCache -Thank you for your interest in contributing to RunCache! This document provides guidelines and instructions for contributing to the project. +Contributions are welcome. The contributor guide lives in the repository, next to the code it describes: -## Code of Conduct +- [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 -By participating in this project, you agree to abide by our Code of Conduct. Please read it before contributing. - -## Getting Started - -### Prerequisites - -- Node.js (version 14 or higher) -- npm or yarn -- Git - -### Setting Up the Development Environment - -1. Fork the repository on GitHub -2. Clone your fork locally: - ```bash - git clone https://github.com/YOUR-USERNAME/run-cache.git - cd run-cache - ``` -3. Install dependencies: - ```bash - npm install - ``` -4. Set up pre-commit hooks: - ```bash - npm run prepare - ``` -5. Create a branch for your changes: - ```bash - git checkout -b feature/your-feature-name - ``` - -## Development Workflow - -### Running Tests - -We use Jest for testing. Run the full test suite: - -```bash -npm test -``` - -Run tests in watch mode during development: - -```bash -npm run test:watch -``` - -Run tests with coverage: - -```bash -npm run test:coverage -``` - -### Linting - -We use ESLint and Prettier for code quality: - -```bash -npm run lint # Check for issues -npm run lint:fix # Fix issues automatically -npm run format # Format code with Prettier -``` - -### Building the Library - -Build the library: - -```bash -npm run build -``` - -### Running Examples - -The project includes example applications in the `examples` directory. You can run them to test your changes: - -```bash -# Run the browser example -cd examples/browser -npm install -npm start - -# Run the Node.js example -cd examples/node -npm install -npm start -``` - -## Making Changes - -### Coding Standards - -- Follow the existing code style -- Write clean, readable, and maintainable code -- Include comments where necessary -- Update documentation for any changed functionality -- Add tests for new features or bug fixes - -### Commit Guidelines - -We follow [Conventional Commits](https://www.conventionalcommits.org/) for commit messages: - -``` -type(scope): short description - -longer description if needed -``` - -Types include: -- `feat`: A new feature -- `fix`: A bug fix -- `docs`: Documentation changes -- `style`: Changes that don't affect code functionality (formatting, etc.) -- `refactor`: Code changes that neither fix bugs nor add features -- `perf`: Performance improvements -- `test`: Adding or updating tests -- `chore`: Changes to build process, tooling, etc. - -Examples: -``` -feat(api): add support for custom serialization -fix(storage): resolve issue with localStorage persistence -docs(readme): update installation instructions -``` - -### Pull Request Process - -1. **Before submitting a PR**: - - Update your fork with the latest changes from the main repository - - Ensure all tests pass - - Make sure your code follows our coding standards - - Add/update tests for your changes - - Update documentation as needed - -2. **Submit your PR**: - - Fill out the PR template - - Link any relevant issues - - Provide a clear description of the changes and their purpose - - Include screenshots or examples if applicable - -3. **Code Review Process**: - - A maintainer will review your PR - - Address any feedback or changes requested - - Once approved, a maintainer will merge your PR - -### Dependency Management - -- Avoid adding new dependencies unless absolutely necessary -- If you need to add a dependency, explain why in your PR description -- Prefer smaller, focused packages over large frameworks - -## Types of Contributions - -### Bug Fixes - -Bug fixes are always welcome! If you find a bug: - -1. Check if it's already reported in the Issues tab -2. If not, create a new issue with steps to reproduce -3. If you want to fix it yourself, mention that in the issue and submit a PR - -### Features - -For new features: - -1. First open an issue describing the feature and its benefits -2. Wait for discussion and approval from maintainers -3. Once approved, implement the feature and submit a PR - -### Documentation - -Documentation improvements are highly valued: - -- Fix typos or unclear explanations -- Add examples or use cases -- Update outdated information -- Improve API documentation - -### Performance Improvements - -Performance improvements should: -- Include before/after benchmarks -- Maintain compatibility with existing APIs -- Not sacrifice code readability for minor optimizations - -## Testing Guidelines - -### Unit Tests - -- Each new feature should include unit tests -- Bug fixes should include tests that reproduce the bug -- Tests should be fast and deterministic -- Try to achieve high test coverage for new code - -### Integration Tests - -- Integration tests should verify that components work together -- Mock external dependencies when needed -- Test both successful and error scenarios - -### Test Naming - -Name tests clearly and descriptively: - -```typescript -describe('RunCache', () => { - describe('get', () => { - it('should return undefined for non-existent keys', () => { - // Test implementation - }); - - it('should return the cached value for existing keys', () => { - // Test implementation - }); - - it('should not return expired values', () => { - // Test implementation - }); - }); -}); -``` - -## Documentation Guidelines - -### Code Documentation - -- Use JSDoc comments for functions, classes, and methods -- Document parameters, return values, and thrown exceptions -- Include examples for complex functionality - -Example: - -```typescript -/** - * Sets a value in the cache with the given options. - * - * @param options - The options for setting the cache entry - * @param options.key - Unique identifier for the cache entry - * @param options.value - String value to cache (required if no sourceFn) - * @param options.ttl - Time-to-live in milliseconds - * @param options.autoRefetch - Automatically refetch on expiry - * @param options.sourceFn - Function to generate cache value - * @param options.tags - Array of tags for tag-based invalidation - * @param options.dependencies - Array of cache keys this entry depends on - * @returns A Promise that resolves when the operation completes - * @throws Error if key is empty, or if neither value nor sourceFn is provided - * - * @example - * ```typescript - * // Set a simple value - * await RunCache.set({ key: 'user', value: JSON.stringify({ name: 'John' }) }); - * - * // Set with TTL and auto-refetch - * await RunCache.set({ - * key: 'weather', - * sourceFn: async () => JSON.stringify(await fetchWeather()), - * ttl: 300000, - * autoRefetch: true - * }); - * ``` - */ -async set(options: SetOptions): Promise { - // Implementation -} -``` - -### README and Documentation - -- Update relevant documentation for new features -- Ensure examples are accurate and working -- Use clear, concise language -- Include visuals where appropriate (diagrams, screenshots) - -## Release Process - -Maintainers handle releases following this process: - -1. Update version in package.json according to [Semantic Versioning](https://semver.org/) -2. Update the CHANGELOG.md file -3. Create a new release on GitHub with release notes -4. Publish to npm - -## Creating a Good Issue - -When creating an issue: - -1. Use a clear, descriptive title -2. Include your environment details (Node.js version, browser, etc.) -3. Provide steps to reproduce -4. Describe expected and actual behavior -5. Add screenshots or code examples if relevant -6. Use issue templates when available - -## Becoming a Maintainer - -Active contributors may be invited to become maintainers. Maintainers: -- Have write access to the repository -- Review and merge PRs -- Help with issue triage -- Guide the project direction -- Maintain code quality and test coverage - -## Questions? - -If you have questions about contributing, please: -- Start a discussion in the GitHub Discussions tab -- Ask in the issues tab with the "question" label -- Reach out to the maintainers - -Thank you for contributing to RunCache! \ No newline at end of file +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/resources/faq.md b/gitbook/resources/faq.md index 0d6bd71..35116ce 100644 --- a/gitbook/resources/faq.md +++ b/gitbook/resources/faq.md @@ -120,21 +120,21 @@ 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'] +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 explicitly -RunCache.invalidateByDependency('user:1'); +// Or invalidate the dependents explicitly, keeping 'user:1' itself +await RunCache.invalidateByDependency('user:1'); ``` -When a cache entry is updated or invalidated, all entries that depend on it are also invalidated, creating a cascading effect through the dependency chain. +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? @@ -157,18 +157,20 @@ function UserProfile({ userId }) { const [loading, setLoading] = useState(true); useEffect(() => { + let active = true; + async function loadUser() { setLoading(true); const cacheKey = `user:${userId}`; - - // Try to get from cache + + // Try to get from cache (objects come back parsed) let userData = await RunCache.get(cacheKey); - - if (!userData) { + + if (userData === undefined) { // Cache miss, fetch from API const response = await fetch(`/api/users/${userId}`); - userData = await response.text(); // Already stringified - + userData = await response.json(); + // Store in cache await RunCache.set({ key: cacheKey, @@ -176,25 +178,27 @@ function UserProfile({ userId }) { ttl: 300000 // 5 minutes }); } - - setUser(JSON.parse(userData)); + + if (!active) return; // the effect was cleaned up while loading + setUser(userData); setLoading(false); } - - loadUser(); - - // Set up event listener for cache changes - const handleRefresh = () => loadUser(); - RunCache.onKeyRefetch(`user:${userId}`, handleRefresh); - + + // 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 () => { - RunCache.clearEventListeners({ - event: 'refetch', - key: `user:${userId}` - }); + active = false; + unsubscribe(); }; }, [userId]); - + if (loading) return
Loading...
; return
{user.name}
; } @@ -206,22 +210,22 @@ function UserProfile({ userId }) { // 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: JSON.stringify(config) }); + await RunCache.set({ key: 'app:config', value: config }); } - + if (!hasGlobalData) { const globalData = await fetchGlobalData(); - await RunCache.set({ key: 'app:global-data', value: JSON.stringify(globalData) }); + await RunCache.set({ key: 'app:global-data', value: globalData }); } - + console.log('Cache warming complete'); } @@ -238,11 +242,11 @@ import { RunCache } from 'run-cache'; import { encrypt, decrypt } from './your-crypto-lib'; // Add encryption middleware -RunCache.use(async (value, context, next) => { - if (context.operation === 'set' && value) { +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' || context.operation === 'refetch') { + } else if (context.operation === 'get') { // Decrypt value after retrieving from cache const encrypted = await next(value); return encrypted ? decrypt(encrypted) : undefined; @@ -258,13 +262,13 @@ RunCache.use(async (value, context, next) => { Common issues include: 1. Not providing a required parameter (key or value/sourceFn) 2. Exception in source function -3. Incorrect value format (must be a string) +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 -RunCache.configure({ debug: true }); +await RunCache.configure({ debug: true }); // Check for errors in source function try { @@ -272,7 +276,7 @@ try { key: 'data', sourceFn: async () => { const data = await fetchData(); - return JSON.stringify(data); // Ensure you return a string + return data; // Return a string or a JSON-serializable value } }); } catch (error) { @@ -299,7 +303,7 @@ await RunCache.set({ }); // Monitor expiration -RunCache.onKeyExpiry('data', (event) => { +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()}`); }); @@ -318,21 +322,21 @@ Solution: import { RunCache, EVENT } from 'run-cache'; // Use the correct event type -RunCache.onExpiry((event) => { +await RunCache.onExpiry((event) => { console.log(`Key expired: ${event.key}`); }); // For specific key patterns, ensure correct syntax -RunCache.onKeyExpiry('user:*', (event) => { +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); -RunCache.onRefetch(handler); +await RunCache.onRefetch(handler); // Later, if needed: -RunCache.clearEventListeners({ +await RunCache.clearEventListeners({ event: EVENT.REFETCH, handler: handler }); @@ -383,7 +387,7 @@ await RunCache.set({ }); // Handle refetch failures -RunCache.onKeyRefetchFailure('api-data', (event) => { +await RunCache.onKeyRefetchFailure('api-data', (event) => { console.error('API data refresh failed:', event.error); notifyAdmins('API data refresh failed'); }); @@ -402,13 +406,13 @@ RunCache can be appropriate for session data with some considerations: // Store session data await RunCache.set({ key: `session:${sessionId}:user`, - value: JSON.stringify(userData), + value: userData, ttl: 30 * 60 * 1000, // 30 minutes tags: [`session:${sessionId}`, 'user-sessions'] }); // On logout, invalidate all session data -RunCache.invalidateByTag(`session:${sessionId}`); +await RunCache.invalidateByTag(`session:${sessionId}`); ``` ## More Help diff --git a/gitbook/resources/license.md b/gitbook/resources/license.md index 97152cb..3ed2910 100644 --- a/gitbook/resources/license.md +++ b/gitbook/resources/license.md @@ -57,7 +57,7 @@ When using RunCache in your projects, you should: Example attribution text: ``` -This project uses RunCache (https://github.com/example/run-cache), +This project uses RunCache (https://github.com/example/run-cache), licensed under the MIT License. ``` diff --git a/gitbook/setup-gitbook.sh b/gitbook/setup-gitbook.sh deleted file mode 100755 index 953bc71..0000000 --- a/gitbook/setup-gitbook.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -# Setup script for RunCache GitBook documentation - -# Check if npm is installed -if ! command -v npm &> /dev/null; then - echo "npm is not installed. Please install Node.js and npm first." - exit 1 -fi - -# Install GitBook CLI -echo "Installing GitBook CLI..." -npm install -g gitbook-cli - -# Initialize GitBook -echo "Initializing GitBook..." -gitbook init - -# Install plugins -echo "Installing GitBook plugins..." -gitbook install - -# Build the documentation -echo "Building documentation..." -gitbook build - -# Success message -echo "" -echo "✅ GitBook documentation setup complete!" -echo "" -echo "To serve the documentation locally, run:" -echo " cd gitbook && gitbook serve" -echo "" -echo "To build the documentation for production, run:" -echo " cd gitbook && gitbook build" -echo "" -echo "The built documentation will be available in the '_book' directory." \ No newline at end of file diff --git a/gitbook/styles/website.css b/gitbook/styles/website.css deleted file mode 100644 index 2f5b085..0000000 --- a/gitbook/styles/website.css +++ /dev/null @@ -1,95 +0,0 @@ -/* Custom styles for RunCache documentation */ - -/* Improve code block readability */ -.markdown-section pre { - background-color: #f8f8f8; - border-radius: 4px; - border: 1px solid #e8e8e8; -} - -.markdown-section code { - border-radius: 3px; - font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; - font-size: 0.9em; -} - -/* Improve headings */ -.markdown-section h1 { - border-bottom: 1px solid #eaecef; - padding-bottom: 0.3em; -} - -.markdown-section h2 { - border-bottom: 1px solid #eaecef; - padding-bottom: 0.3em; -} - -/* Improve tables */ -.markdown-section table { - display: table; - width: 100%; - border-collapse: collapse; -} - -.markdown-section table th { - font-weight: 600; - background-color: #f6f8fa; -} - -.markdown-section table tr { - border-top: 1px solid #dfe2e5; -} - -.markdown-section table tr:nth-child(2n) { - background-color: #f6f8fa; -} - -.markdown-section table td, -.markdown-section table th { - border: 1px solid #dfe2e5; - padding: 6px 13px; -} - -/* Improve blockquotes */ -.markdown-section blockquote { - border-left: 4px solid #0366d6; - color: #6a737d; - padding: 0 1em; -} - -/* Improve links */ -.markdown-section a { - color: #0366d6; - text-decoration: none; -} - -.markdown-section a:hover { - text-decoration: underline; -} - -/* Improve note boxes */ -.markdown-section .hint, -.markdown-section .warning { - padding: 1em; - border-radius: 4px; - margin: 1em 0; -} - -.markdown-section .hint { - background-color: #f1f8ff; - border-left: 4px solid #0366d6; -} - -.markdown-section .warning { - background-color: #fff5f5; - border-left: 4px solid #d73a49; -} - -/* Custom class for API method signatures */ -.method-signature { - background-color: #f6f8fa; - padding: 1em; - border-radius: 4px; - font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; - overflow-x: auto; -} \ No newline at end of file diff --git a/package.json b/package.json index 2c72e8f..16c9f8a 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,8 @@ "test:coverage": "jest --coverage", "lint": "eslint src/**/*.ts", "prepare": "npm run build && npm run lint", - "lint:fix": "eslint src/**/*.ts --fix" + "lint:fix": "eslint src/**/*.ts --fix", + "docs:check": "node scripts/check-docs.mjs" }, "repository": { "type": "git", diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs new file mode 100644 index 0000000..bb8f1b8 --- /dev/null +++ b/scripts/check-docs.mjs @@ -0,0 +1,298 @@ +#!/usr/bin/env node +/** + * Checks the code samples in the docs against the package's public API. + * + * It reads fenced js/ts code blocks from README.md, CLAUDE.md and gitbook/ + * (the live "next" docs), plus every file in examples/, and reports: + * - named imports from 'run-cache' that the package entry does not export + * - RunCache. calls that the RunCache class does not have + * - library internals (exported inside src/ but not from the package) used by name + * - async RunCache calls in statement or assignment position without `await` + * - a few known-stale patterns (see STALE_PATTERNS) + * + * The exported surface is read from src/, so the check follows the code. + * Frozen docs in gitbook-versions/ are not checked: they describe what shipped. + * + * To skip one block on purpose, put `` on the line + * directly above its opening fence. + * + * Usage: node scripts/check-docs.mjs [files...] + */ +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { join, relative, resolve, extname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = join(fileURLToPath(import.meta.url), "..", ".."); +const read = (p) => readFileSync(join(ROOT, p), "utf8"); + +function walk(dir, filter) { + const out = []; + for (const name of readdirSync(join(ROOT, dir))) { + const p = join(dir, name); + if (statSync(join(ROOT, p)).isDirectory()) out.push(...walk(p, filter)); + else if (filter(p)) out.push(p); + } + return out; +} + +// --------------------------------------------------------------------------- +// Public API, read from src/ +// --------------------------------------------------------------------------- + +const isSource = (p) => p.endsWith(".ts") && !p.endsWith(".d.ts") && !p.includes(".test.") && !p.startsWith(join("src", "examples")); +const sourceFiles = walk("src", isSource); + +function exportedNames(file) { + const src = read(file); + const names = new Set(); + for (const m of src.matchAll(/export\s+(?:declare\s+)?(?:abstract\s+)?(?:class|const|let|function|interface|type|enum)\s+(\w+)/g)) { + names.add(m[1]); + } + for (const m of src.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) { + for (const part of m[1].split(",")) { + const name = part.trim().split(/\s+as\s+/).pop().trim(); + if (name) names.add(name); + } + } + return names; +} + +// Package entry: its own export lists plus everything reached through `export * from`. +function resolveExports(file, seen = new Set()) { + if (seen.has(file)) return new Set(); + seen.add(file); + const names = exportedNames(file); + for (const m of read(file).matchAll(/export\s+\*\s+from\s+['"](.+?)['"]/g)) { + for (const n of resolveExports(`${join(file, "..", m[1])}.ts`, seen)) names.add(n); + } + return names; +} +const publicExports = resolveExports(join("src", "index.ts")); +publicExports.add("default"); + +// Names exported somewhere in src/ but not from the package entry. +const internalNames = new Set(); +for (const f of sourceFiles) for (const n of exportedNames(f)) if (!publicExports.has(n)) internalNames.add(n); +// Generic words that are also ordinary identifiers in sample code. +for (const n of ["Logger", "ExpiryTimer", "SourceFn", "CacheState"]) internalNames.add(n); + +// RunCache static members, and which of them are async. +const runCacheSrc = read(join("src", "run-cache.ts")); +const classBody = runCacheSrc.slice(runCacheSrc.indexOf("export class RunCache"), runCacheSrc.indexOf("export class TypedCacheInterface")); +const runCacheMembers = new Map(); +for (const m of classBody.matchAll(/^\s+(?:public\s+)?static\s+(async\s+)?(\w+)\s*[<(]/gm)) { + runCacheMembers.set(m[2], Boolean(m[1])); +} +for (const m of classBody.matchAll(/^\s+private\s+static\s+(?:async\s+)?(\w+)/gm)) runCacheMembers.delete(m[1]); + +// --------------------------------------------------------------------------- +// Known-stale patterns that the API checks above cannot see +// --------------------------------------------------------------------------- + +const STALE_PATTERNS = [ + [/\bvalidator\s*:/, "no RunCache method takes a `validator` option"], + [/(?:value|sourceFn)\s*:.*JSON\.stringify\(/, "non-string values are serialized for you; pass the value itself"], + [/JSON\.parse\(\s*(?:await\s+)?[\w.]*\.get\(/, "get() already returns the stored value (objects are parsed); do not JSON.parse it"], + [/\binternalCache\b|\bgetInternalCache\b/, "the cache's internals are not public API"], + [/\b(?:event|e|evt)\.(?:metadata|timestamp|reason|oldValue|newValue|duration|operation)\b/, "event payloads only have key, value, ttl, createdAt, updatedAt, tag, dependencyKey and error"], + [/\.refetch\(\s*[^,()]+(?:\([^()]*\))?\s*,/, "refetch() takes only a key"], + [/context\.operation\s*===?\s*['"](?:save|load)['"]/, "middleware does not run on save/load; operations are get, set, delete, has and refetch"], +]; + +// --------------------------------------------------------------------------- +// Code block extraction +// --------------------------------------------------------------------------- + +const CODE_LANGS = new Set(["js", "javascript", "ts", "typescript", "jsx", "tsx", "mjs"]); + +function codeBlocks(file) { + const text = read(file); + if (!file.endsWith(".md")) return [{ line: 1, code: text }]; + const lines = text.split("\n"); + const blocks = []; + for (let i = 0; i < lines.length; i++) { + const open = lines[i].match(/^(\s*)(```+|~~~+)\s*([\w-]*)/); + if (!open) continue; + const fence = open[2]; + const lang = open[3].toLowerCase(); + const start = i; + // A closing fence uses the same character, is at least as long, and has only + // spaces or tabs after it (CommonMark), so `~~~ payload` inside a block is content. + const closing = new RegExp(`^\\s*${fence[0] === "`" ? "`" : "~"}{${fence.length},}[ \\t]*$`); + let j = i + 1; + while (j < lines.length && !closing.test(lines[j])) j++; + const ignored = start > 0 && lines[start - 1].includes("docs-check-ignore"); + if (CODE_LANGS.has(lang) && !ignored) { + blocks.push({ line: start + 2, code: lines.slice(start + 1, j).join("\n") }); + } + i = j; + } + return blocks; +} + +// --------------------------------------------------------------------------- +// Checks +// --------------------------------------------------------------------------- + +function stripComments(line) { + // Good enough for samples: drop `// ...` that is not inside a string or URL. + return line.replace(/(^|[^:'"`\\])\/\/.*$/, "$1"); +} + +/** True if the call whose `(` is at lines[line][col] is followed by `.then`/`.catch`/`.finally`. */ +function isChained(lines, line, col) { + let depth = 0; + let quote = null; // open string delimiter; parentheses inside strings do not count + for (let l = line; l < lines.length; l++) { + const text = lines[l]; + if (quote && quote !== "`") quote = null; // '...' and "..." strings end with the line + for (let c = l === line ? col : 0; c < text.length; c++) { + const ch = text[c]; + if (quote) { + if (ch === "\\") c++; + else if (ch === quote) quote = null; + continue; + } + if (ch === "'" || ch === '"' || ch === "`") quote = ch; + else if (ch === "(") depth++; + else if (ch === ")" && --depth === 0) { + const rest = [text.slice(c + 1), ...lines.slice(l + 1, l + 3)].join("\n"); + return /^\s*\.(?:then|catch|finally)\(/.test(rest); + } + } + } + return false; +} + +/** + * True if line i is a property of the options object passed directly to a + * `.set(`/`.refetch(` call that starts a few lines above. Properties of nested + * objects (such as `value: { metadata: ... }`) do not count. + */ +function insideCacheCall(lines, i) { + let parens = 0; + let braces = 0; // closed `{...}` pairs seen while walking back + let openBraces = 0; // unclosed `{` between line i and the call + for (let j = i - 1; j >= Math.max(0, i - 15); j--) { + const text = lines[j]; + for (let c = text.length - 1; c >= 0; c--) { + const ch = text[c]; + if (ch === ")") parens++; + else if (ch === "}") braces++; + else if (ch === "{") { + if (braces > 0) braces--; + else openBraces++; + } else if (ch === "(") { + if (parens === 0) { + return openBraces === 1 && /\.(?:set|refetch)\s*(?:<[^>]*>)?$/.test(text.slice(0, c)); + } + parens--; + } + } + } + return false; +} + +function previousCodeLine(lines, i) { + for (let j = i - 1; j >= 0; j--) if (lines[j].trim()) return stripComments(lines[j]); + return ""; +} + +function checkBlock(code) { + const problems = []; + const lines = code.split("\n"); + const add = (i, msg) => problems.push({ offset: i, msg }); + + // Imports (may span lines). + for (const m of code.matchAll(/import\s+(?:type\s+)?(?:\w+\s*,\s*)?\{([^}]*)\}\s*from\s*['"]run-cache['"]/g)) { + const offset = code.slice(0, m.index).split("\n").length - 1; + for (const raw of m[1].split(",")) { + const name = raw.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim(); + if (name && !publicExports.has(name)) add(offset, `'${name}' is not exported by 'run-cache'`); + } + } + for (const m of code.matchAll(/require\(\s*['"]run-cache['"]\s*\)/g)) void m; // CommonJS default is fine + + // Variables that hold a get() result, to catch `JSON.parse(thatVariable)` later on. + const getResults = new Set(); + for (const m of code.matchAll(/(?:const|let|var)\s+(\w+)\s*=\s*\(?\s*await\s+[\w.]*\.get\s*(?:<[^>]*>)?\(/g)) { + getResults.add(m[1]); + } + + let inBlockComment = false; + lines.forEach((rawLine, i) => { + let line = rawLine; + if (inBlockComment) { + if (!line.includes("*/")) return; + line = line.slice(line.indexOf("*/") + 2); + inBlockComment = false; + } + if (line.includes("/*") && !line.includes("*/")) { + inBlockComment = true; + line = line.slice(0, line.indexOf("/*")); + } + line = stripComments(line); + if (/^\s*\*/.test(line)) return; + + for (const m of line.matchAll(/\bRunCache\.(\w+)/g)) { + const name = m[1]; + if (name === "prototype") continue; + if (!runCacheMembers.has(name)) { + add(i, `RunCache.${name} does not exist`); + continue; + } + } + + // Un-awaited async call as a statement or the right side of an assignment. + // Calls whose promise is chained (`.then`/`.catch` after the call) or that are the + // body of a concise arrow function (`() =>` ending the previous line) are handled. + const stmt = line.match(/^\s*(?:(?:const|let|var)\s+[\w{}\s,[\]]+=\s*|[\w.[\]]+\s*=\s*)?RunCache\.(\w+)\s*(?:<[^>]*>)?\(/); + if (stmt && runCacheMembers.get(stmt[1]) + && !isChained(lines, i, stmt.index + stmt[0].length - 1) + && !/=>\s*$/.test(previousCodeLine(lines, i))) { + add(i, `RunCache.${stmt[1]}() is async; await it (or return/collect the promise)`); + } + + for (const name of internalNames) { + if (new RegExp(`(^|[^\\w.'"\`])${name}\\b(?!['"\`])`).test(line)) { + add(i, `'${name}' is internal and not exported by 'run-cache'`); + } + } + + for (const [re, msg] of STALE_PATTERNS) if (re.test(line)) add(i, msg); + for (const m of line.matchAll(/JSON\.parse\(\s*(\w+)\s*\)/g)) { + if (getResults.has(m[1]) && !new RegExp(`typeof\\s+${m[1]}\\s*===?\\s*['"]string['"]`).test(code)) add(i, `'${m[1]}' holds a get() result, which is already parsed; do not JSON.parse it`); + } + // `metadata:` only matters inside a set()/refetch() call, not in the reader's own objects. + if (/^\s*metadata\s*:/.test(line) && insideCacheCall(lines, i)) { + add(i, "cache entries have no metadata option"); + } + }); + return problems; +} + +const args = process.argv.slice(2); +const files = args.length + ? args.map((p) => relative(ROOT, resolve(p))) + : [ + "README.md", + "CLAUDE.md", + ...walk("gitbook", (p) => p.endsWith(".md")), + ...walk("examples", (p) => [".js", ".ts", ".mjs"].includes(extname(p))), + ]; + +let count = 0; +for (const file of files) { + for (const block of codeBlocks(file)) { + for (const p of checkBlock(block.code)) { + count++; + console.log(`${file}:${block.line + p.offset}: ${p.msg}`); + } + } +} + +if (count) { + console.log(`\n${count} problem(s) in doc code samples.`); + process.exit(1); +} +console.log(`Doc code samples match the public API (${files.length} files checked).`); diff --git a/src/index.ts b/src/index.ts index cebc891..5f70ba6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,7 @@ * import { RunCache, EvictionPolicy } from 'run-cache'; * * // Configure the cache - * RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU }); + * await RunCache.configure({ maxEntries: 1000, evictionPolicy: EvictionPolicy.LRU }); * * // Set a cache entry * await RunCache.set({ key: 'user:123', value: 'John Doe', ttl: 60000 }); diff --git a/src/run-cache.ts b/src/run-cache.ts index 59eb088..934aaa8 100644 --- a/src/run-cache.ts +++ b/src/run-cache.ts @@ -196,7 +196,7 @@ export class RunCache { * * @param {Object} params - The parameters to set in the cache. * @param {string} params.key - The key for the cache entry. Must be a non-empty string. - * @param {string} [params.value] - The value to store in the cache. If not provided, the `sourceFn` must be defined to generate the value. + * @param {T} [params.value] - The value to store in the cache: a string (stored as-is) or any JSON-serializable value (serialized on set and parsed again by `get()`). If not provided, the `sourceFn` must be defined to generate the value. * @param {number} [params.ttl] - The time-to-live for the cache entry in milliseconds. After this time, the cache entry will expire. * @param {boolean} [params.autoRefetch] - Whether to automatically refetch the value after the TTL expires. Requires a TTL to be set. * @param {SourceFn} [params.sourceFn] - A function that returns the value for the cache. This is used when the value is not provided directly. @@ -206,14 +206,14 @@ export class RunCache { * @returns {Promise} - Returns `true` when the cache entry is successfully set. * * @throws {Error} If the key is empty, if both `value` and `sourceFn` are missing, or if `autoRefetch` is set without a TTL. - * @throws {Error} If `ttl` is negative. + * @throws {Error} If `ttl` is not a finite number greater than zero. * @throws {Error} If the `sourceFn` fails to generate a value. * * @example * // Basic usage with tags * await RunCache.set({ * key: "user:profile:123", - * value: JSON.stringify({name: "John"}), + * value: {name: "John"}, * tags: ["user:123", "profile"] * }); * diff --git a/src/types/cache-config.ts b/src/types/cache-config.ts index 5fc570a..a435b3e 100644 --- a/src/types/cache-config.ts +++ b/src/types/cache-config.ts @@ -25,8 +25,8 @@ export interface CacheConfig { maxEntries?: number; /** - * Default time-to-live in milliseconds for cache entries - * @default Infinity + * Not implemented: entries set without a `ttl` never expire, whatever this is set to. + * @deprecated Pass `ttl` to `RunCache.set()` for each entry instead. */ defaultTTL?: number;