0
# HTTP Storage
1
2
HTTP/HTTPS-based remote cache stores with compression, retry logic, and proxy support for distributed caching scenarios. Enables teams to share cached build artifacts across development environments.
3
4
## Capabilities
5
6
### HttpStore
7
8
Full-featured HTTP cache store with compression, authentication, and comprehensive retry logic for reliable remote caching.
9
10
```javascript { .api }
11
/**
12
* Remote HTTP/HTTPS cache store with compression and retry support
13
* Supports both read and write operations to remote cache servers
14
* @template T - Type of cached values
15
*/
16
class HttpStore<T> {
17
/**
18
* Create a new HTTP store instance
19
* @param options - Configuration options for HTTP endpoints and behavior
20
*/
21
constructor(options: HttpOptions);
22
23
/**
24
* Retrieve cached value via HTTP GET request
25
* @param key - Cache key as Buffer (sent as hex in URL path)
26
* @returns Promise resolving to cached value or null if not found
27
* @throws HttpError for HTTP errors, NetworkError for connectivity issues
28
*/
29
get(key: Buffer): Promise<T | null>;
30
31
/**
32
* Store value via HTTP PUT request with gzip compression
33
* @param key - Cache key as Buffer (sent as hex in URL path)
34
* @param value - Value to cache (JSON serializable or Buffer)
35
* @returns Promise that resolves when storage is complete
36
* @throws HttpError for HTTP errors, NetworkError for connectivity issues
37
*/
38
set(key: Buffer, value: T): Promise<void>;
39
40
/**
41
* Clear operation is not implemented for HTTP stores
42
* @returns void (no-op)
43
*/
44
clear(): void;
45
46
/**
47
* Reference to HttpError class for error handling
48
*/
49
static HttpError: typeof HttpError;
50
51
/**
52
* Reference to NetworkError class for error handling
53
*/
54
static NetworkError: typeof NetworkError;
55
}
56
```
57
58
**Usage Examples:**
59
60
```javascript
61
const { HttpStore } = require("metro-cache");
62
63
// Basic HTTP store
64
const httpStore = new HttpStore({
65
endpoint: "https://cache.company.com/api/v1/cache"
66
});
67
68
// HTTP store with authentication and custom settings
69
const authenticatedStore = new HttpStore({
70
endpoint: "https://secure-cache.example.com/cache",
71
timeout: 10000,
72
headers: {
73
"Authorization": "Bearer " + process.env.CACHE_TOKEN,
74
"X-Team-ID": "frontend-team"
75
},
76
maxAttempts: 3,
77
retryStatuses: new Set([502, 503, 504])
78
});
79
80
// Different endpoints for read vs write operations
81
const asymmetricStore = new HttpStore({
82
getOptions: {
83
endpoint: "https://read-cache.example.com/get",
84
timeout: 5000
85
},
86
setOptions: {
87
endpoint: "https://write-cache.example.com/put",
88
timeout: 15000,
89
headers: { "Authorization": "Bearer " + writeToken }
90
}
91
});
92
93
// Usage
94
try {
95
const result = await httpStore.get(cacheKey);
96
if (result === null) {
97
const computed = processData();
98
await httpStore.set(cacheKey, computed);
99
}
100
} catch (error) {
101
if (error instanceof HttpStore.HttpError) {
102
console.log("HTTP error:", error.code, error.message);
103
} else if (error instanceof HttpStore.NetworkError) {
104
console.log("Network error:", error.code, error.message);
105
}
106
}
107
```
108
109
### HttpGetStore
110
111
Read-only HTTP cache store that converts errors to warnings, ideal for optional remote cache access that shouldn't break builds.
112
113
```javascript { .api }
114
/**
115
* Read-only HTTP cache store that warns on connection errors
116
* Extends HttpStore but converts all errors to warnings and returns null
117
* Perfect for optional remote caches that shouldn't break builds
118
* @template T - Type of cached values
119
*/
120
class HttpGetStore<T> extends HttpStore<T> {
121
/**
122
* Create a new read-only HTTP store instance
123
* @param options - HTTP configuration options
124
*/
125
constructor(options: HttpOptions);
126
127
/**
128
* Retrieve cached value with error handling that converts errors to warnings
129
* @param key - Cache key as Buffer
130
* @returns Promise resolving to cached value or null (never throws)
131
*/
132
get(key: Buffer): Promise<T | null>;
133
134
/**
135
* No-op set operation (read-only store)
136
* @returns Promise resolving to undefined immediately
137
*/
138
set(): Promise<void>;
139
}
140
```
141
142
**Usage Examples:**
143
144
```javascript
145
const { HttpGetStore } = require("metro-cache");
146
147
// Read-only cache that won't break builds if unavailable
148
const optionalCache = new HttpGetStore({
149
endpoint: "https://shared-cache.example.com/readonly",
150
timeout: 3000 // Short timeout since it's optional
151
});
152
153
// Always succeeds - errors become warnings
154
const cached = await optionalCache.get(key);
155
if (cached !== null) {
156
console.log("Found in shared cache");
157
return cached;
158
}
159
160
// Continue with normal processing if cache unavailable
161
const result = processData();
162
// Note: set() is a no-op for HttpGetStore
163
return result;
164
```
165
166
## HTTP Configuration
167
168
### HttpOptions Type
169
170
```javascript { .api }
171
/**
172
* Configuration options for HTTP cache stores
173
* Can specify unified options or separate read/write configurations
174
*/
175
type HttpOptions = EndpointOptions | {
176
getOptions: EndpointOptions;
177
setOptions: EndpointOptions;
178
};
179
180
/**
181
* Configuration for a single HTTP endpoint
182
*/
183
interface EndpointOptions {
184
/**
185
* HTTP endpoint URL (required)
186
*/
187
endpoint: string;
188
189
/**
190
* IP family preference (4 for IPv4, 6 for IPv6)
191
*/
192
family?: 4 | 6;
193
194
/**
195
* Request timeout in milliseconds (default: 5000)
196
*/
197
timeout?: number;
198
199
/**
200
* TLS client key for mutual authentication
201
*/
202
key?: string | Array<string> | Buffer | Array<Buffer>;
203
204
/**
205
* TLS client certificate for mutual authentication
206
*/
207
cert?: string | Array<string> | Buffer | Array<Buffer>;
208
209
/**
210
* TLS certificate authority certificates
211
*/
212
ca?: string | Array<string> | Buffer | Array<Buffer>;
213
214
/**
215
* URL query parameters to include in requests
216
*/
217
params?: URLSearchParams;
218
219
/**
220
* HTTP headers to include in requests
221
*/
222
headers?: { [string]: string };
223
224
/**
225
* Additional HTTP status codes to treat as successful
226
*/
227
additionalSuccessStatuses?: Array<number>;
228
229
/**
230
* Whether to include detailed error information in exceptions
231
*/
232
debug?: boolean;
233
234
/**
235
* Maximum number of retry attempts (default: 1)
236
*/
237
maxAttempts?: number;
238
239
/**
240
* Whether to retry on network connectivity errors
241
*/
242
retryNetworkErrors?: boolean;
243
244
/**
245
* HTTP status codes that should trigger retries
246
*/
247
retryStatuses?: Set<number>;
248
249
/**
250
* Unix socket path for HTTP requests
251
*/
252
socketPath?: string;
253
254
/**
255
* HTTP proxy URL
256
*/
257
proxy?: string;
258
}
259
```
260
261
## Protocol Details
262
263
### Request Format
264
265
- **GET Requests**: `{endpoint}/{keyAsHex}?{params}`
266
- **PUT Requests**: `{endpoint}/{keyAsHex}?{params}` with gzipped body
267
- **Compression**: All data is compressed with gzip (level 9)
268
- **Content Encoding**: Responses are automatically decompressed
269
270
### Data Serialization
271
272
HTTP stores handle data serialization automatically:
273
274
- **JavaScript Objects**: JSON serialized then gzipped
275
- **Buffer Data**: Binary data prefixed with null byte (0x00) then gzipped
276
- **Response Handling**: Automatic detection of JSON vs binary data
277
278
### Error Handling
279
280
HTTP stores provide comprehensive error handling:
281
282
- **404 Responses**: Treated as cache miss (returns null)
283
- **HTTP Errors**: Thrown as HttpError with status code
284
- **Network Errors**: Thrown as NetworkError with error code
285
- **Retry Logic**: Configurable exponential backoff for transient failures
286
287
### Retry Configuration
288
289
The retry system uses exponential backoff with full jitter (via the exponential-backoff npm package):
290
291
- **Backoff Strategy**: Exponential with full jitter
292
- **Maximum Delay**: 30 seconds between attempts
293
- **Retry Conditions**: Based on error type and configured status codes
294
- **Network Errors**: Only retried if retryNetworkErrors is true