Skip to content

feat(kernel): Implement cache invalidation helper (A4)#19

Merged
pipewrk merged 2 commits intomainfrom
sprint-1/a4-cache-invalidation
Oct 1, 2025
Merged

feat(kernel): Implement cache invalidation helper (A4)#19
pipewrk merged 2 commits intomainfrom
sprint-1/a4-cache-invalidation

Conversation

@pipewrk
Copy link
Contributor

@pipewrk pipewrk commented Sep 30, 2025

Summary

Implements A4 (Cache Invalidation Helper) from Sprint 1, providing the invalidate() function for cache management in Actions.

Features

Primary API

  • invalidate(patterns, options?) - Invalidate caches by pattern matching
    • Supports prefix matching: ['thing', 'list'] matches all list queries
    • Can target specific stores or invalidate across all registered stores
    • Emits wpk.cache.invalidated event for analytics/logging
    • Gracefully handles missing window.wp (e.g., in tests)

Cache Key Utilities

  • normalizeCacheKey() - Convert cache key arrays to deterministic strings
  • matchesCacheKey() - Test if a key matches a pattern (prefix matching)
  • findMatchingKeys() - Find all matching keys in a collection
  • findMatchingKeysMultiple() - Find matches for multiple patterns with deduplication

Store Integration

  • Resources auto-register their store keys when accessed
  • Integrates with @wordpress/data registry for invalidation dispatch
  • Works across all registered gk/* stores

Implementation Details

New Files

  • packages/kernel/src/resource/cacheKeys.ts - Cache key pattern matching utilities
  • packages/kernel/src/resource/invalidate.ts - Main invalidation function
  • packages/kernel/src/resource/__tests__/cacheKeys.test.ts - 22 tests (100% coverage)
  • packages/kernel/src/resource/__tests__/invalidate.test.ts - 16 tests (all paths covered)

Modified Files

  • packages/kernel/src/resource/defineResource.ts - Register store keys on access
  • packages/kernel/src/resource/index.ts - Export new APIs
  • packages/kernel/src/index.ts - Export from main package
  • docs/api/resources.md - API documentation with examples

Pattern Matching Examples

// Invalidate all list queries
invalidate(['thing', 'list']);
// Matches: thing:list, thing:list:active, thing:list:page:2

// Invalidate specific query
invalidate(['thing', 'list', 'active']);
// Matches: thing:list:active, thing:list:active:page:2

// Multiple resources
invalidate([
  ['thing', 'list'],
  ['job', 'list']
]);

Usage in Actions

import { defineAction } from '@geekist/wp-kernel';
import { invalidate } from '@geekist/wp-kernel';
import { thing } from '@/app/resources/thing';

export const CreateThing = defineAction('Thing.Create', async ({ data }) => {
  const created = await thing.create(data);
  
  // Invalidate list caches so UI refreshes
  invalidate(['thing', 'list']);
  
  return created;
});

Tests

  • ✅ All 233 tests passing (22 new + 211 existing)
  • ✅ Cache key normalization and matching
  • ✅ Pattern matching (exact, prefix, multiple patterns)
  • ✅ Store targeting (specific vs. all stores)
  • ✅ Event emission
  • ✅ Error handling (missing stores, invalid dispatch, etc.)
  • ✅ TypeScript compilation clean

Documentation

  • Updated docs/api/resources.md with complete API reference
  • Added usage examples in Actions context
  • Documented pattern matching behavior
  • Included all utility functions

Closes

#4

Add comprehensive cache invalidation system with pattern matching support.

## Features

- **invalidate()** - Primary cache invalidation API with pattern matching
  - Supports prefix matching: ['thing', 'list'] matches all list queries
  - Can target specific stores or invalidate across all stores
  - Emits wpk.cache.invalidated event

- **Cache key utilities**:
  - normalizeCacheKey() - Convert patterns to deterministic strings
  - matchesCacheKey() - Test if key matches pattern
  - findMatchingKeys() - Find all matching keys in collection
  - findMatchingKeysMultiple() - Find matches for multiple patterns

- **Store registration** - Resources auto-register for invalidation tracking

## Implementation

- packages/kernel/src/resource/cacheKeys.ts - Cache key utilities
- packages/kernel/src/resource/invalidate.ts - Invalidation logic
- Integrated with @wordpress/data registry
- Handles graceful degradation when window.wp not available

## Tests

- 22 tests for cache key utilities (100% coverage)
- 16 tests for invalidation function (all paths tested)
- All 233 tests passing

## Documentation

- Updated docs/api/resources.md with invalidate() API reference
- Added usage examples in Actions context
- Documented pattern matching behavior

Closes #4
Copilot AI review requested due to automatic review settings September 30, 2025 23:51
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements cache invalidation functionality (A4) for the WP Kernel framework. It provides the invalidate() function for Actions to manage cache state after write operations, ensuring UI consistency.

Key changes:

  • Core cache invalidation API with pattern matching and store targeting
  • Cache key utilities for normalization and matching operations
  • Integration with WordPress data registry for store invalidation
  • Comprehensive test coverage with 38 new tests

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
packages/kernel/src/resource/invalidate.ts Main invalidation function with store targeting and event emission
packages/kernel/src/resource/cacheKeys.ts Cache key pattern matching utilities and normalization
packages/kernel/src/resource/defineResource.ts Added store key registration on resource access
packages/kernel/src/resource/__tests__/invalidate.test.ts 16 tests covering invalidation scenarios and error handling
packages/kernel/src/resource/__tests__/cacheKeys.test.ts 22 tests for cache key utilities with 100% coverage
packages/kernel/src/resource/index.ts Export new invalidation APIs
packages/kernel/src/index.ts Export from main package entry point
docs/api/resources.md API documentation with usage examples

Comment on lines +184 to +189
if (process.env.NODE_ENV === 'development') {
console.warn(
`Failed to invalidate cache for store ${key}:`,
error
);
}
Copy link

Copilot AI Sep 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Console.warn usage in production code should be replaced with a proper logging mechanism. Consider using the framework's error reporter or logging system instead of direct console calls.

Copilot uses AI. Check for mistakes.
Comment on lines +244 to +249
if (process.env.NODE_ENV === 'development') {
console.warn(
`Failed to invalidate all caches for store ${storeKey}:`,
error
);
}
Copy link

Copilot AI Sep 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Console.warn usage in production code should be replaced with a proper logging mechanism. Consider using the framework's error reporter or logging system instead of direct console calls.

Copilot uses AI. Check for mistakes.
Major improvements:
- Consolidated duplicate sections (2 Best Practices → 1 unified)
- Removed outdated 'Current Limitations' section (A3 complete)
- Removed redundant 'Using Resource Metadata' section
- Better logical flow: Quick Start → Config → Client → Store → Cache → Best Practices → Advanced

Content fixes based on feedback:
- Consistent list() destructuring pattern throughout
- Clear getItems vs getList distinction with usage guidance
- Path parameter version requirements documented (A3+)
- Nested resource examples use named params (not positional)
- Added Resource Events callout (wpk.resource.*)
- All imports extension-free
- No Date.now() in cache key examples

Technical fixes:
- Escaped angle brackets in markdown headers for VitePress compatibility
- Fixed callout block formatting
- Removed duplicate section headers

Results:
- 137 lines shorter (420 deletions, 283 additions)
- All concepts grouped logically
- No duplication
- Accurate implementation status
- Clear API patterns

Addresses documentation feedback for PR #19
@pipewrk pipewrk merged commit 6d4b083 into main Oct 1, 2025
7 checks passed
pipewrk added a commit that referenced this pull request Nov 8, 2025
Major improvements:
- Consolidated duplicate sections (2 Best Practices → 1 unified)
- Removed outdated 'Current Limitations' section (A3 complete)
- Removed redundant 'Using Resource Metadata' section
- Better logical flow: Quick Start → Config → Client → Store → Cache → Best Practices → Advanced

Content fixes based on feedback:
- Consistent list() destructuring pattern throughout
- Clear getItems vs getList distinction with usage guidance
- Path parameter version requirements documented (A3+)
- Nested resource examples use named params (not positional)
- Added Resource Events callout (wpk.resource.*)
- All imports extension-free
- No Date.now() in cache key examples

Technical fixes:
- Escaped angle brackets in markdown headers for VitePress compatibility
- Fixed callout block formatting
- Removed duplicate section headers

Results:
- 137 lines shorter (420 deletions, 283 additions)
- All concepts grouped logically
- No duplication
- Accurate implementation status
- Clear API patterns

Addresses documentation feedback for PR #19
pipewrk added a commit that referenced this pull request Nov 8, 2025
feat(kernel): Implement cache invalidation helper (A4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants