@hyperttp/cache 1.1.0 → 1.1.1

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.
Files changed (2) hide show
  1. package/README.md +64 -55
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
+ ```markdown
1
2
  # hyperttp-cache
2
3
 
3
- > English | [Русский](https://github.com/IT-IF-OR/hyperttp-cache/tree/main/lang/ru)
4
+ > [Русский](https://github.com/IT-IF-OR/hyperttp-cache/tree/main/lang/ru) | English
4
5
 
5
6
  ---
6
7
 
@@ -11,45 +12,45 @@
11
12
 
12
13
  ---
13
14
 
14
- Сверхбыстрый, изоморфный плагин кэширования и дедупликации параллельных запросов для высокопроизводительного
15
- HTTP-клиента `Hyperttp`. Оптимизирован для рантаймов **Bun** и **Node.js**.
15
+ Blazing fast, isomorphic cache management and concurrent request deduplication plugin for the high-performance
16
+ `Hyperttp` HTTP client. Optimized for **Bun** and **Node.js** runtimes.
16
17
 
17
- Плагин бесшовно встраивается в плоский конвейер жизненного цикла `HyperCore`, защищая сервер от лавинообразной
18
- нагрузки (**Cache Stampede Protection**) и предоставляя умное in-memory хранилище на базе стратегии
19
- **LRU (Least Recently Used)**.
18
+ The plugin seamlessly integrates into the flat `HyperCore` lifecycle pipeline, protecting your backend from server
19
+ breakdown (**Cache Stampede Protection**) and providing smart in-memory storage based on the **LRU (Least Recently Used)**
20
+ strategy.
20
21
 
21
22
  ---
22
23
 
23
- ## 🔥 Ключевые фичи
24
+ ## 🔥 Key Features
24
25
 
25
- - 🧠 **LRU-стратегия с поддержкой TTL:** Автоматическое вытеснение старых записей при достижении лимита. При каждом
26
- `GET`-запросе возраст записи сбрасывается (`updateAgeOnGet: true`), удерживая горячие данные в памяти.
27
- - 🚀 **In-Flight Deduplication:** Веерные параллельные запросы на один и тот же URL группируются в один сетевой
28
- hot path. Ответ клонируется и раздается всем подписчикам одновременно.
29
- - 🔄 **HTTP Revalidation:** Полная поддержка проверок свежести по `ETag` (`If-None-Match`) и `Last-Modified`
30
- (`If-Modified-Since`). Автоматически гидрирует пустые `304` ответы актуальным телом из памяти.
31
- - 🛡️ **Безопасность при сбоях:** При возникновении сетевых ошибок пул ожидания мгновенно разрывается (`onError`),
32
- разблокируя повторные попытки запросов.
33
- - 📊 **Расширение Ядра:** Автоматически инжектирует методы управления кэшем (`clearCache`) и добавляет метрику
34
- `cacheSize` в системную статистику `getStats()`.
26
+ - 🧠 **LRU Strategy with TTL Support:** Automatically evicts old entries when reaching limits. With every `GET`
27
+ request, the entry age resets (`updateAgeOnGet: true`), keeping hot data cached in memory.
28
+ - 🚀 **In-Flight Deduplication:** Concurrent fan-out requests targeting the same URL are grouped into a single network
29
+ hot path. The response is cloned and distributed to all waiting subscribers simultaneously.
30
+ - 🔄 **HTTP Revalidation:** Full freshness verification support via `ETag` (`If-None-Match`) and `Last-Modified`
31
+ (`If-Modified-Since`). Automatically re-hydrates empty `304` responses with cached data bodies.
32
+ - 🛡️ **Fail-Safe Processing:** When network processing exceptions occur, the in-flight waiting pool is instantly
33
+ purged (`onError`), unblocking immediate subsequent retry attempts.
34
+ - 📊 **Core Extension:** Automatically injects cache management methods (`clearCache`) and appends a `cacheSize`
35
+ telemetry metric into the core `getStats()` architecture.
35
36
 
36
37
  ---
37
38
 
38
- ## 📦 Установка
39
+ ## 📦 Installation
39
40
 
40
41
  ```bash
41
42
  bun add hyperttp-cache
42
- # или
43
+ # or
43
44
  npm install hyperttp-cache
44
45
 
45
46
  ```
46
47
 
47
48
  ---
48
49
 
49
- ## 🚀 Быстрый старт
50
+ ## 🚀 Quick Start
50
51
 
51
- Просто импортируйте фабрику `withCache` и передайте её в массив плагинов вашего клиента. Настройки кэша
52
- передаются в глобальный конфиг.
52
+ Simply import the `withCache` factory and append it to your client's plugin array. Cache configurations are
53
+ passed directly within the global options block.
53
54
 
54
55
  ```typescript
55
56
  import { createClient } from "@hyperttp/core";
@@ -59,75 +60,83 @@ const client = createClient({
59
60
  plugins: [withCache()],
60
61
  cache: {
61
62
  enabled: true,
62
- ttl: 60_000, // 1 минута (по умолчанию 300_000 мс)
63
- maxSize: 1000, // Лимит в 1000 элементов (по умолчанию 500)
64
- methods: ["GET"], // HTTP-методы, разрешенные для кэширования
63
+ ttl: 60_000, // 1 minute (defaults to 300_000 ms)
64
+ maxSize: 1000, // Limit to 1000 items (defaults to 500)
65
+ methods: ["GET"], // HTTP methods authorized for downstream caching
65
66
  },
66
67
  });
67
68
 
68
- // 1. Первый запрос уходит в сеть и наполняет кэш
69
+ // 1. The first request goes out to the network and populates the cache
69
70
  const res1 = await client.get("/api/data");
70
71
 
71
- // 2. Второй последующий запрос вернет изолированный клон из кэша
72
+ // 2. Subsequent requests instantly return an isolated clone from the cache
72
73
  const res2 = await client.get("/api/data");
74
+
73
75
  ```
74
76
 
75
77
  ---
76
78
 
77
- ## ⚙️ Параметры конфигурации (`CacheManagerOptions`)
79
+ ## ⚙️ Configuration Options (`CacheManagerOptions`)
78
80
 
79
- Конфигурация плагина полностью типизирована и расширяет интерфейс настроек клиента:
81
+ The plugin configuration layer is fully typed and extends the default client option interfaces:
80
82
 
81
- | Параметр | Тип | По умолчанию | Описание |
82
- | --------------- | ---------- | ----------------- | ---------------------------------------------------------------- |
83
- | `cache.enabled` | `boolean` | `false` | Флаг активации/деактивации слоя кэширования. |
84
- | `cache.ttl` | `number` | `300_000` (5 мин) | Время жизни записи в кэше (в миллисекундах). |
85
- | `cache.maxSize` | `number` | `500` | Максимальное количество записей в LRU-кэше до начала вытеснения. |
86
- | `cache.methods` | `Method[]` | `["GET"]` | Массив HTTP-методов, для которых разрешено кэширование ответов. |
83
+ | Parameter | Type | Default | Description |
84
+ | --- | --- | --- | --- |
85
+ | `cache.enabled` | `boolean` | `false` | Activation status flag for the caching layer. |
86
+ | `cache.ttl` | `number` | `300_000` (5 min) | Cache entry time-to-live threshold (in milliseconds). |
87
+ | `cache.maxSize` | `number` | `500` | Maximum entries allowed inside the LRU pool before eviction begins. |
88
+ | `cache.methods` | `Method[]` | `["GET"]` | Array of HTTP methods authorized for response interception. |
87
89
 
88
90
  ---
89
91
 
90
- ## 🛠️ API Расширения Ядра
92
+ ## 🛠️ Core API Extensions
91
93
 
92
- Плагин расширяет глобальные интерфейсы декларации типов `@hyperttp/types`. Вам становятся доступны следующие
93
- методы прямо из инстанса ядра:
94
+ The plugin extends the global `@hyperttp/types` interface declarations. The following lifecycle methods become
95
+ directly accessible via the client core instance:
94
96
 
95
- ### Очистка кэша
97
+ ### Purging Cache
96
98
 
97
99
  ```typescript
98
- // Очистить кэш полностью
100
+ // Purge the entire cache system
99
101
  client.clearCache();
100
102
 
101
- // Удалить конкретный URL из кэша
103
+ // Evict a specific URL key from the storage
102
104
  client.clearCache("/api/data");
105
+
103
106
  ```
104
107
 
105
- ### Телеметрия
108
+ ### Telemetry
106
109
 
107
- Если ваше ядро поддерживает метод `getStats()`, плагин автоматически подмешает туда текущий размер кэша:
110
+ If your core implementation supports the `getStats()` routine, the plugin automatically appends the current cache size:
108
111
 
109
112
  ```typescript
110
113
  const stats = client.getStats();
111
- console.log(stats.cacheSize); // Выведет текущее количество записей в LRU-хранилище
114
+ console.log(stats.cacheSize); // Outputs the current number of active entries inside the LRU storage
115
+
112
116
  ```
113
117
 
114
118
  ---
115
119
 
116
- ## 📐 Архитектура жизненного цикла
120
+ ## 📐 Lifecycle Architecture
117
121
 
118
- Плагин использует атомарные независимые хуки вместо тяжелых middleware-оберток:
122
+ The plugin utilizes atomic, decoupled lifecycle hooks instead of overhead-heavy middleware wrappers:
119
123
 
120
- 1. **`onRequest`**: Проверяет наличие точного совпадения в `CacheManager`. Если запись свежая и не требует
121
- проверки сервера возвращает её клон, завершая цепочку. Если идет активный запрос к этому же URL подписывается
122
- на его `Promise`. Если запись требует валидации, подмешает заголовки `If-None-Match` / `If-Modified-Since`.
123
- 2. **`onResponse`**: Перехватывает успешные ответы. Превращает пустой `304 Not Modified` обратно в полноценный
124
- `200 OK`, восстанавливая данные из локальной памяти. Записывает новые `200` ответы с валидными ETag. Разрешает
125
- (resolves) ожидания всех `In-Flight` подписчиков.
126
- 3. **`onError`**: В случае сетевого сбоя вычищает карту активных задач, чтобы не заблокировать последующие
127
- повторные вызовы к упавшему эндпоинту.
124
+ 1. **`onRequest`**: Evaluates local key hits inside the `CacheManager`. If the matching record is fresh and doesn't
125
+ require validation, it returns a clone, short-circuiting the chain. If a concurrent request to the same URL is active,
126
+ it hooks into its matching follower `Promise`. If a partial hit requires validation, it appends conditional headers
127
+ (`If-None-Match` / `If-Modified-Since`).
128
+ 2. **`onResponse`**: Intercepts successful downstream outputs. Re-hydrates an empty `304 Not Modified` status code
129
+ back into a full `200 OK` response by recovering body content from memory. Saves valid `200` ranges containing validation
130
+ metadata and resolves execution triggers for all waiting `In-Flight` threads.
131
+ 3. **`onError`**: In the event of a critical network failure, it instantly flushes matching active tracking task entries
132
+ from the map to ensure subsequent retries targeting the failed endpoint are never deadlocked.
128
133
 
129
134
  ---
130
135
 
131
- ## 📄 Лицензия
136
+ ## 📄 License
132
137
 
133
138
  MIT
139
+
140
+ ```
141
+
142
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperttp/cache",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "High-performance LRU caching plugin for Hyperttp client",
5
5
  "type": "module",
6
6
  "main": "./index.js",