@appweaver/skill 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,233 @@
1
+ # Cache
2
+
3
+ The cache module provides a key-value store with TTL support, eviction strategies, and automatic invalidation tied to
4
+ resource mutations. The one implementation, `MemoryCache` (provider `memory`), stores its entries in the selected
5
+ `Memory` provider: in the process by default, in Redis with `MEMORY_PROVIDER=redis` (the default when
6
+ `@appweaver/redis` is installed). It is accessed through the abstract `Cache` class and the higher-level `CacheService`.
7
+
8
+ ## `Cache` — low-level provider
9
+
10
+ Inject the abstract `Cache` class directly when you need raw key-value access.
11
+
12
+ ```ts
13
+ import { inject } from '@appweaver/core';
14
+ import { Cache } from '@appweaver/common';
15
+
16
+ const cache = inject(Cache);
17
+ ```
18
+
19
+ ### Unavailable backend
20
+
21
+ With `CACHE_SKIP_ON_ERROR` enabled (the default) the cache never fails its callers. While the backing memory (e.g.
22
+ Redis) is down or a command fails, every method returns its empty result (`get` → `null`, `has`/`set`/`delete` →
23
+ `false`, `deleteMatching` → `0`, `keys` → `[]`), so the callers fall back to the database. The outage is logged once
24
+ with an error, and the recovery once with info. Entries written before an outage may have missed invalidations made
25
+ during it, so the whole cache is cleared once the memory is available again. Calling code does not need its own
26
+ `try`/`catch`around cache access. While the Redis circuit breaker is open, the cache skips Redis entirely
27
+ (see [configuration.md](./configuration.md#memory-memory_)).
28
+
29
+ Set `CACHE_SKIP_ON_ERROR` to `false` to make every method throw the memory error instead, so requests that read or
30
+ write the cache fail while its backend is down. Resource cache invalidation still only logs its errors.
31
+
32
+ #### `cache.get<T>(key)`
33
+
34
+ Retrieves a cached value. Returns `null` if the key does not exist.
35
+
36
+ ```ts
37
+ const user = await cache.get<User>('user:42');
38
+ ```
39
+
40
+ #### `cache.has(key)`
41
+
42
+ Returns `true` if the key exists and has not expired.
43
+
44
+ ```ts
45
+ if (await cache.has('user:42')) {
46
+ /* ... */
47
+ }
48
+ ```
49
+
50
+ #### `cache.set(key, value, ttl?)`
51
+
52
+ Stores a value. `ttl` is in milliseconds; omit to use `CACHE_DEFAULT_TTL`.
53
+
54
+ ```ts
55
+ await cache.set('user:42', user, 30_000); // 30 s
56
+ ```
57
+
58
+ #### `cache.delete(key)`
59
+
60
+ Removes a single entry. Returns `true` if the key existed.
61
+
62
+ ```ts
63
+ await cache.delete('user:42');
64
+ ```
65
+
66
+ #### `cache.deleteMatching(pattern?)`
67
+
68
+ Removes all entries whose keys match a glob pattern. Returns the number of removed entries. Omit `pattern` to remove
69
+ everything.
70
+
71
+ ```ts
72
+ const removed = await cache.deleteMatching('user:*');
73
+ ```
74
+
75
+ #### `cache.keys(pattern?)`
76
+
77
+ Returns all keys matching a glob pattern, or all keys if omitted.
78
+
79
+ ```ts
80
+ const keys = await cache.keys('session:*');
81
+ ```
82
+
83
+ The `Memory` provider the cache stores its entries in (`memory` or `redis`, injected with `inject(Memory)`) offers
84
+ the same `get`, `set`, `has`, `delete`, `deleteMatching`, and `keys` methods, along with `sizeBytes(key)` and
85
+ `lock(resource)`. Both store a value as plain JSON: a `Date` is read back as its ISO string, and a value JSON cannot
86
+ hold (a circular reference, a `BigInt`, `undefined`) fails with `MEMORY_VALUE_INVALID` naming its key, so turn an
87
+ object graph into JSON (references into IDs) before storing it.
88
+
89
+ ---
90
+
91
+ ## `CacheService` — high-level helper
92
+
93
+ `CacheService` wraps `Cache` with duplicate-check logic, debug logging, and resource-aware invalidation. It is
94
+ registered automatically by the framework, unless `CACHE_PROVIDER` is `none`.
95
+
96
+ ```ts
97
+ import { inject } from '@appweaver/core';
98
+ import { CacheService } from '@appweaver/core';
99
+
100
+ const cacheService = inject(CacheService);
101
+ ```
102
+
103
+ #### `cacheService.getCachedValue<T>(key)`
104
+
105
+ Returns the cached value or `null`. Logs a debug message on hit.
106
+
107
+ ```ts
108
+ const result = await cacheService.getCachedValue<Product[]>('products:all');
109
+ ```
110
+
111
+ #### `cacheService.addToCache(key, value, ttl?, replace?)`
112
+
113
+ Stores a value only if the key does not already exist. Pass `replace: true` to overwrite. Returns `false` if the key
114
+ existed and `replace` was not set.
115
+
116
+ | Parameter | Type | Default | Description |
117
+ | --------- | --------- | ------- | ------------------------------- |
118
+ | `key` | `string` | — | Cache key |
119
+ | `value` | `any` | — | Value to store |
120
+ | `ttl` | `number` | config | TTL in milliseconds |
121
+ | `replace` | `boolean` | `false` | Overwrite if key already exists |
122
+
123
+ ```ts
124
+ await cacheService.addToCache('products:all', products, 60_000);
125
+ // Overwrite an existing entry:
126
+ await cacheService.addToCache('products:all', updated, 60_000, true);
127
+ ```
128
+
129
+ #### `cacheService.removeCachedValue(key)`
130
+
131
+ Removes a single cached entry. Returns `true` if removed.
132
+
133
+ ```ts
134
+ await cacheService.removeCachedValue('products:all');
135
+ ```
136
+
137
+ #### `cacheService.invalidateCache(modelName, action)`
138
+
139
+ Expires cache entries related to a model based on `CACHE_INVALIDATION_STRATEGY`. Called automatically by the framework
140
+ after `create`, `update`, and `delete` actions.
141
+
142
+ | Parameter | Type | Description |
143
+ | ----------- | ---------------------------------- | ------------------------------------ |
144
+ | `modelName` | `string` | The resource model name |
145
+ | `action` | `'create' \| 'update' \| 'delete'` | The mutation that triggered eviction |
146
+
147
+ ```ts
148
+ await cacheService.invalidateCache('Product', 'update');
149
+ ```
150
+
151
+ #### `cacheService.buildCacheKey(data)`
152
+
153
+ Builds a structured cache key that encodes HTTP method, URL, body hash, relations, and optional user scope. A user
154
+ authenticated with an API key in the current call gets keys of their own per key (`<id>~key<keyId>`), since the scope
155
+ of a key may narrow the roles of its owner.
156
+
157
+ | Field | Type | Description |
158
+ | ------------------ | ---------- | ----------------------------------------------- |
159
+ | `baseKey` | `string` | Required prefix |
160
+ | `method` | `string` | HTTP method |
161
+ | `url` | `string` | Request URL |
162
+ | `body` | `string` | Stringified request body (hashed automatically) |
163
+ | `modelName` | `string` | Model whose relations are embedded in the key |
164
+ | `relations` | `string[]` | Explicit relation list; use `['*']` for all |
165
+ | `skipInvalidation` | `boolean` | Omit the invalidation suffix |
166
+ | `authUser` | `AuthUser` | Scope the key to the user (and its API key) |
167
+
168
+ ```ts
169
+ const key = cacheService.buildCacheKey({
170
+ baseKey: 'products',
171
+ method: 'GET',
172
+ url: '/api/products?page=1',
173
+ modelName: 'Product',
174
+ authUser: req.user
175
+ });
176
+ ```
177
+
178
+ ---
179
+
180
+ ## Configuration
181
+
182
+ | Key | Type | Default | Description |
183
+ | ----------------------------- | -------- | ------------------ | -------------------------------------------------- |
184
+ | `CACHE_ENABLED` | `bool` | `true` | Enables or disables the cache globally |
185
+ | `CACHE_PROVIDER` | `string` | `'auto'` | `auto`/`memory`, `none`, or a module path |
186
+ | `CACHE_KEY_PREFIX` | `string` | `'cache:'` | Prefix prepended to every key |
187
+ | `CACHE_MAX_ITEMS` | `int` | `1000` | Maximum number of entries before eviction kicks in |
188
+ | `CACHE_CACHE_MAX_SIZE` | `string` | - | Maximum size used by the cache. |
189
+ | `CACHE_DEFAULT_TTL` | duration | `5000` | Default TTL, milliseconds or a duration string |
190
+ | `CACHE_EVICTION_STRATEGY` | `enum` | `'lru'` | `lru`, `lfu`, or `fifo` |
191
+ | `CACHE_INVALIDATION_STRATEGY` | `enum` | `'expire-related'` | `expire-related`, `expire-all`, or `none` |
192
+ | `CACHE_INVALIDATION_DEFERRED` | `bool` | `false` | Fire invalidation in the background (non-blocking) |
193
+ | `CACHE_SKIP_ON_ERROR` | `bool` | `true` | Return empty results instead of failing on errors |
194
+
195
+ The cache follows the `Memory` provider, so keep the cache of the tests in the process with:
196
+
197
+ ```json
198
+ {
199
+ "environments": {
200
+ "test": { "memory": { "provider": "memory" } }
201
+ }
202
+ }
203
+ ```
204
+
205
+ ---
206
+
207
+ ## Real-world example
208
+
209
+ ```ts
210
+ import { inject } from '@appweaver/core';
211
+ import { CacheService } from '@appweaver/core';
212
+
213
+ export class ProductService {
214
+ private readonly _cache = inject(CacheService);
215
+
216
+ async getAll(): Promise<Product[]> {
217
+ const key = this._cache.buildCacheKey({ baseKey: 'products:all' });
218
+
219
+ const cached = await this._cache.getCachedValue<Product[]>(key);
220
+ if (cached) return cached;
221
+
222
+ const products = await fetchFromDatabase();
223
+ await this._cache.addToCache(key, products, 60_000);
224
+ return products;
225
+ }
226
+
227
+ async update(id: number, data: Partial<Product>): Promise<Product> {
228
+ const product = await updateInDatabase(id, data);
229
+ await this._cache.invalidateCache('Product', 'update');
230
+ return product;
231
+ }
232
+ }
233
+ ```