graphile-cache 4.16.0 → 4.16.2
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.
- package/README.md +19 -3
- package/create-instance.d.ts +5 -1
- package/create-instance.js +9 -0
- package/esm/create-instance.js +9 -0
- package/esm/graphile-cache.js +49 -21
- package/esm/index.js +2 -2
- package/graphile-cache.d.ts +22 -0
- package/graphile-cache.js +52 -22
- package/index.d.ts +1 -1
- package/index.js +4 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -128,6 +128,21 @@ app.use((req, res, next) => {
|
|
|
128
128
|
});
|
|
129
129
|
```
|
|
130
130
|
|
|
131
|
+
### Heap Budget
|
|
132
|
+
|
|
133
|
+
Each entry records `heapBytes`, the heap growth measured while
|
|
134
|
+
`createGraphileInstance()` built it. Cache entries with
|
|
135
|
+
`cacheGraphileInstance(key, entry)` rather than `graphileCache.set()`: the
|
|
136
|
+
cache evicts least-recently-used entries before their combined `heapBytes`
|
|
137
|
+
exceeds the budget, and an entry that alone exceeds it is released and rejected
|
|
138
|
+
with `GraphileCacheBudgetError`.
|
|
139
|
+
|
|
140
|
+
| Variable | Default |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| `GRAPHILE_CACHE_MAX` | `50` entries |
|
|
143
|
+
| `GRAPHILE_CACHE_MAX_HEAP_BYTES` | half of V8's heap size limit |
|
|
144
|
+
| `GRAPHILE_CACHE_TTL_MS` | ~1 year (5 minutes in development) |
|
|
145
|
+
|
|
131
146
|
### Graceful Shutdown
|
|
132
147
|
|
|
133
148
|
```typescript
|
|
@@ -238,9 +253,10 @@ Install skills for AI coding agents:
|
|
|
238
253
|
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
239
254
|
npx skills add constructive-io/constructive-skills
|
|
240
255
|
|
|
241
|
-
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
242
|
-
npx skills add
|
|
243
|
-
npx skills add
|
|
256
|
+
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
|
|
257
|
+
npx skills add constructive-io/constructive --skill pgpm
|
|
258
|
+
npx skills add constructive-io/constructive --skill safegres
|
|
259
|
+
npx skills add constructive-io/constructive --skill constructive-testing
|
|
244
260
|
```
|
|
245
261
|
|
|
246
262
|
## Credits
|
package/create-instance.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type GraphileCacheEntry } from './graphile-cache';
|
|
2
2
|
interface GraphileInstanceOptions {
|
|
3
3
|
preset: any;
|
|
4
4
|
cacheKey: string;
|
|
@@ -24,6 +24,10 @@ interface GraphileInstanceOptions {
|
|
|
24
24
|
* instance's PgSubscriber EventEmitter. Both `pgSubscriber` and the pg
|
|
25
25
|
* pool are extracted from the resolved preset's pgServices — no separate
|
|
26
26
|
* pool parameter is needed.
|
|
27
|
+
*
|
|
28
|
+
* `heapBytes` is the heap growth across the build, which the cache uses as the
|
|
29
|
+
* entry's size. Builds running concurrently count each other's allocations,
|
|
30
|
+
* so the estimate errs towards evicting early.
|
|
27
31
|
*/
|
|
28
32
|
export declare const createGraphileInstance: (opts: GraphileInstanceOptions) => Promise<GraphileCacheEntry>;
|
|
29
33
|
export {};
|
package/create-instance.js
CHANGED
|
@@ -10,6 +10,7 @@ const express_1 = __importDefault(require("express"));
|
|
|
10
10
|
const v4_1 = require("grafserv/express/v4");
|
|
11
11
|
const graphile_realtime_subscriptions_1 = require("graphile-realtime-subscriptions");
|
|
12
12
|
const postgraphile_1 = require("postgraphile");
|
|
13
|
+
const graphile_cache_1 = require("./graphile-cache");
|
|
13
14
|
const log = new logger_1.Logger('graphile-cache:create');
|
|
14
15
|
/**
|
|
15
16
|
* Create a PostGraphile v5 instance backed by grafserv/express.
|
|
@@ -26,15 +27,22 @@ const log = new logger_1.Logger('graphile-cache:create');
|
|
|
26
27
|
* instance's PgSubscriber EventEmitter. Both `pgSubscriber` and the pg
|
|
27
28
|
* pool are extracted from the resolved preset's pgServices — no separate
|
|
28
29
|
* pool parameter is needed.
|
|
30
|
+
*
|
|
31
|
+
* `heapBytes` is the heap growth across the build, which the cache uses as the
|
|
32
|
+
* entry's size. Builds running concurrently count each other's allocations,
|
|
33
|
+
* so the estimate errs towards evicting early.
|
|
29
34
|
*/
|
|
30
35
|
const createGraphileInstance = async (opts) => {
|
|
31
36
|
const { preset, cacheKey, enableRealtime = false } = opts;
|
|
37
|
+
const heapBefore = process.memoryUsage().heapUsed;
|
|
32
38
|
const pgl = (0, postgraphile_1.postgraphile)(preset);
|
|
33
39
|
const serv = pgl.createServ(v4_1.grafserv);
|
|
34
40
|
const handler = (0, express_1.default)();
|
|
35
41
|
const httpServer = (0, node_http_1.createServer)(handler);
|
|
36
42
|
await serv.addTo(handler, httpServer);
|
|
37
43
|
await serv.ready();
|
|
44
|
+
await pgl.getSchema();
|
|
45
|
+
const heapBytes = Math.max(process.memoryUsage().heapUsed - heapBefore, graphile_cache_1.MIN_ENTRY_HEAP_BYTES);
|
|
38
46
|
const entry = {
|
|
39
47
|
pgl,
|
|
40
48
|
serv,
|
|
@@ -42,6 +50,7 @@ const createGraphileInstance = async (opts) => {
|
|
|
42
50
|
httpServer,
|
|
43
51
|
cacheKey,
|
|
44
52
|
createdAt: Date.now(),
|
|
53
|
+
heapBytes,
|
|
45
54
|
};
|
|
46
55
|
if (enableRealtime) {
|
|
47
56
|
try {
|
package/esm/create-instance.js
CHANGED
|
@@ -4,6 +4,7 @@ import express from 'express';
|
|
|
4
4
|
import { grafserv } from 'grafserv/express/v4';
|
|
5
5
|
import { RealtimeManager } from 'graphile-realtime-subscriptions';
|
|
6
6
|
import { postgraphile } from 'postgraphile';
|
|
7
|
+
import { MIN_ENTRY_HEAP_BYTES } from './graphile-cache';
|
|
7
8
|
const log = new Logger('graphile-cache:create');
|
|
8
9
|
/**
|
|
9
10
|
* Create a PostGraphile v5 instance backed by grafserv/express.
|
|
@@ -20,15 +21,22 @@ const log = new Logger('graphile-cache:create');
|
|
|
20
21
|
* instance's PgSubscriber EventEmitter. Both `pgSubscriber` and the pg
|
|
21
22
|
* pool are extracted from the resolved preset's pgServices — no separate
|
|
22
23
|
* pool parameter is needed.
|
|
24
|
+
*
|
|
25
|
+
* `heapBytes` is the heap growth across the build, which the cache uses as the
|
|
26
|
+
* entry's size. Builds running concurrently count each other's allocations,
|
|
27
|
+
* so the estimate errs towards evicting early.
|
|
23
28
|
*/
|
|
24
29
|
export const createGraphileInstance = async (opts) => {
|
|
25
30
|
const { preset, cacheKey, enableRealtime = false } = opts;
|
|
31
|
+
const heapBefore = process.memoryUsage().heapUsed;
|
|
26
32
|
const pgl = postgraphile(preset);
|
|
27
33
|
const serv = pgl.createServ(grafserv);
|
|
28
34
|
const handler = express();
|
|
29
35
|
const httpServer = createServer(handler);
|
|
30
36
|
await serv.addTo(handler, httpServer);
|
|
31
37
|
await serv.ready();
|
|
38
|
+
await pgl.getSchema();
|
|
39
|
+
const heapBytes = Math.max(process.memoryUsage().heapUsed - heapBefore, MIN_ENTRY_HEAP_BYTES);
|
|
32
40
|
const entry = {
|
|
33
41
|
pgl,
|
|
34
42
|
serv,
|
|
@@ -36,6 +44,7 @@ export const createGraphileInstance = async (opts) => {
|
|
|
36
44
|
httpServer,
|
|
37
45
|
cacheKey,
|
|
38
46
|
createdAt: Date.now(),
|
|
47
|
+
heapBytes,
|
|
39
48
|
};
|
|
40
49
|
if (enableRealtime) {
|
|
41
50
|
try {
|
package/esm/graphile-cache.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getHeapStatistics } from 'node:v8';
|
|
1
2
|
import { Logger } from '@pgpmjs/logger';
|
|
2
3
|
import { parseEnvNumber } from '12factor-env';
|
|
3
4
|
import { EventEmitter } from 'events';
|
|
@@ -18,11 +19,16 @@ export class CacheEventEmitter extends EventEmitter {
|
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
21
|
export const cacheEvents = new CacheEventEmitter();
|
|
22
|
+
/** Floor for an entry's measured heap so a GC during its build cannot make it free. */
|
|
23
|
+
export const MIN_ENTRY_HEAP_BYTES = 1024 * 1024;
|
|
24
|
+
const defaultMaxHeapBytes = () => Math.floor(getHeapStatistics().heap_size_limit / 2);
|
|
21
25
|
/**
|
|
22
26
|
* Get cache configuration from environment variables
|
|
23
27
|
*
|
|
24
28
|
* Supports:
|
|
25
29
|
* - GRAPHILE_CACHE_MAX: Maximum number of entries (default: 50)
|
|
30
|
+
* - GRAPHILE_CACHE_MAX_HEAP_BYTES: Total measured heap the cached handlers may
|
|
31
|
+
* retain (default: half of V8's heap limit, so the cache cannot fill the heap)
|
|
26
32
|
* - GRAPHILE_CACHE_TTL_MS: TTL in milliseconds
|
|
27
33
|
* - Production default: ONE_YEAR
|
|
28
34
|
* - Development default: FIVE_MINUTES_MS
|
|
@@ -35,28 +41,22 @@ export function getCacheConfig() {
|
|
|
35
41
|
const max = parseEnvNumber(process.env.GRAPHILE_CACHE_MAX) ?? 50;
|
|
36
42
|
const ttl = parseEnvNumber(process.env.GRAPHILE_CACHE_TTL_MS) ??
|
|
37
43
|
(isDevelopment ? FIVE_MINUTES_MS : ONE_YEAR);
|
|
38
|
-
|
|
44
|
+
const maxHeapBytes = parseEnvNumber(process.env.GRAPHILE_CACHE_MAX_HEAP_BYTES) ?? defaultMaxHeapBytes();
|
|
45
|
+
return { max, ttl, maxHeapBytes };
|
|
39
46
|
}
|
|
40
|
-
// Track disposed entries to prevent double-disposal
|
|
41
|
-
const disposedKeys = new Set();
|
|
42
47
|
// Track keys that are being manually evicted for accurate eviction reason
|
|
43
48
|
const manualEvictionKeys = new Set();
|
|
49
|
+
// One disposal per entry: closeAllCaches() and the LRU dispose callback both
|
|
50
|
+
// dispose the same entry, and PostGraphile throws if released twice.
|
|
51
|
+
const disposals = new WeakMap();
|
|
44
52
|
/**
|
|
45
53
|
* Dispose a PostGraphile v5 cache entry
|
|
46
54
|
*
|
|
47
55
|
* Properly releases resources by:
|
|
48
56
|
* 1. Closing the HTTP server if listening
|
|
49
57
|
* 2. Releasing the PostGraphile instance (which internally releases grafserv)
|
|
50
|
-
*
|
|
51
|
-
* Uses disposedKeys set to prevent double-disposal when closeAllCaches()
|
|
52
|
-
* explicitly disposes entries and then clear() triggers the dispose callback.
|
|
53
58
|
*/
|
|
54
|
-
const
|
|
55
|
-
// Prevent double-disposal
|
|
56
|
-
if (disposedKeys.has(key)) {
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
disposedKeys.add(key);
|
|
59
|
+
const releaseEntry = async (entry, key) => {
|
|
60
60
|
log.debug(`Disposing PostGraphile[${key}]`);
|
|
61
61
|
try {
|
|
62
62
|
// Close HTTP server if it's listening
|
|
@@ -82,9 +82,14 @@ const disposeEntry = async (entry, key) => {
|
|
|
82
82
|
catch (err) {
|
|
83
83
|
log.error(`Error disposing PostGraphile[${key}]:`, err);
|
|
84
84
|
}
|
|
85
|
-
|
|
86
|
-
|
|
85
|
+
};
|
|
86
|
+
const disposeEntry = (entry, key) => {
|
|
87
|
+
let disposal = disposals.get(entry);
|
|
88
|
+
if (!disposal) {
|
|
89
|
+
disposal = releaseEntry(entry, key);
|
|
90
|
+
disposals.set(entry, disposal);
|
|
87
91
|
}
|
|
92
|
+
return disposal;
|
|
88
93
|
};
|
|
89
94
|
/**
|
|
90
95
|
* Determine the eviction reason for a cache entry
|
|
@@ -108,6 +113,8 @@ const initialConfig = getCacheConfig();
|
|
|
108
113
|
export const graphileCache = new LRUCache({
|
|
109
114
|
max: initialConfig.max,
|
|
110
115
|
ttl: initialConfig.ttl,
|
|
116
|
+
maxSize: initialConfig.maxHeapBytes,
|
|
117
|
+
sizeCalculation: (entry) => entry.heapBytes,
|
|
111
118
|
updateAgeOnGet: true,
|
|
112
119
|
dispose: (entry, key) => {
|
|
113
120
|
// Determine eviction reason before disposal
|
|
@@ -122,6 +129,30 @@ export const graphileCache = new LRUCache({
|
|
|
122
129
|
});
|
|
123
130
|
}
|
|
124
131
|
});
|
|
132
|
+
export class GraphileCacheBudgetError extends Error {
|
|
133
|
+
cacheKey;
|
|
134
|
+
heapBytes;
|
|
135
|
+
maxHeapBytes;
|
|
136
|
+
constructor(cacheKey, heapBytes, maxHeapBytes) {
|
|
137
|
+
super(`PostGraphile[${cacheKey}] retains ${heapBytes} heap bytes, more than the ${maxHeapBytes}-byte graphile cache budget`);
|
|
138
|
+
this.cacheKey = cacheKey;
|
|
139
|
+
this.heapBytes = heapBytes;
|
|
140
|
+
this.maxHeapBytes = maxHeapBytes;
|
|
141
|
+
this.name = 'GraphileCacheBudgetError';
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Cache a newly built handler, evicting least-recently-used handlers until the
|
|
146
|
+
* measured heap of all cached handlers fits the budget. A handler that alone
|
|
147
|
+
* exceeds the budget is released and rejected instead of being served uncached.
|
|
148
|
+
*/
|
|
149
|
+
export async function cacheGraphileInstance(key, entry) {
|
|
150
|
+
if (entry.heapBytes > graphileCache.maxEntrySize) {
|
|
151
|
+
await disposeEntry(entry, key);
|
|
152
|
+
throw new GraphileCacheBudgetError(key, entry.heapBytes, graphileCache.maxEntrySize);
|
|
153
|
+
}
|
|
154
|
+
graphileCache.set(key, entry);
|
|
155
|
+
}
|
|
125
156
|
/**
|
|
126
157
|
* Get current cache statistics
|
|
127
158
|
*/
|
|
@@ -131,6 +162,8 @@ export function getCacheStats() {
|
|
|
131
162
|
size: graphileCache.size,
|
|
132
163
|
max: config.max,
|
|
133
164
|
ttl: config.ttl,
|
|
165
|
+
heapBytes: graphileCache.calculatedSize,
|
|
166
|
+
maxHeapBytes: graphileCache.maxSize,
|
|
134
167
|
keys: [...graphileCache.keys()]
|
|
135
168
|
};
|
|
136
169
|
}
|
|
@@ -186,19 +219,14 @@ export const closeAllCaches = async (verbose = false) => {
|
|
|
186
219
|
try {
|
|
187
220
|
if (verbose)
|
|
188
221
|
log.info('Closing all server caches...');
|
|
189
|
-
// Collect all entries and dispose them properly
|
|
190
222
|
const entries = [...graphileCache.entries()];
|
|
191
223
|
// Mark all as manual evictions
|
|
192
224
|
for (const [key] of entries) {
|
|
193
225
|
manualEvictionKeys.add(key);
|
|
194
226
|
}
|
|
195
|
-
|
|
196
|
-
// Wait for all disposals to complete
|
|
197
|
-
await Promise.allSettled(disposePromises);
|
|
198
|
-
// Clear the cache after disposal (dispose callback will no-op due to disposedKeys)
|
|
227
|
+
// clear() starts each entry's disposal; wait for those same disposals.
|
|
199
228
|
graphileCache.clear();
|
|
200
|
-
|
|
201
|
-
disposedKeys.clear();
|
|
229
|
+
await Promise.allSettled(entries.map(([key, entry]) => disposeEntry(entry, key)));
|
|
202
230
|
manualEvictionKeys.clear();
|
|
203
231
|
// Close pg pools
|
|
204
232
|
await pgCache.close();
|
package/esm/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// Main exports from graphile-cache package
|
|
2
2
|
export {
|
|
3
3
|
// Event emitter for cache events
|
|
4
|
-
CacheEventEmitter, cacheEvents,
|
|
4
|
+
CacheEventEmitter, cacheEvents, cacheGraphileInstance,
|
|
5
5
|
// Clear matching entries
|
|
6
6
|
clearMatchingEntries, closeAllCaches, FIVE_MINUTES_MS, getCacheConfig, getCacheStats,
|
|
7
7
|
// Cache instance and entry type
|
|
8
|
-
graphileCache,
|
|
8
|
+
graphileCache, GraphileCacheBudgetError, MIN_ENTRY_HEAP_BYTES,
|
|
9
9
|
// Time constants
|
|
10
10
|
ONE_HOUR_MS } from './graphile-cache';
|
|
11
11
|
// Factory for creating PostGraphile v5 instances
|
package/graphile-cache.d.ts
CHANGED
|
@@ -20,12 +20,18 @@ export declare const cacheEvents: CacheEventEmitter;
|
|
|
20
20
|
export interface CacheConfig {
|
|
21
21
|
max: number;
|
|
22
22
|
ttl: number;
|
|
23
|
+
/** Total measured heap the cached handlers may retain, in bytes. */
|
|
24
|
+
maxHeapBytes: number;
|
|
23
25
|
}
|
|
26
|
+
/** Floor for an entry's measured heap so a GC during its build cannot make it free. */
|
|
27
|
+
export declare const MIN_ENTRY_HEAP_BYTES: number;
|
|
24
28
|
/**
|
|
25
29
|
* Get cache configuration from environment variables
|
|
26
30
|
*
|
|
27
31
|
* Supports:
|
|
28
32
|
* - GRAPHILE_CACHE_MAX: Maximum number of entries (default: 50)
|
|
33
|
+
* - GRAPHILE_CACHE_MAX_HEAP_BYTES: Total measured heap the cached handlers may
|
|
34
|
+
* retain (default: half of V8's heap limit, so the cache cannot fill the heap)
|
|
29
35
|
* - GRAPHILE_CACHE_TTL_MS: TTL in milliseconds
|
|
30
36
|
* - Production default: ONE_YEAR
|
|
31
37
|
* - Development default: FIVE_MINUTES_MS
|
|
@@ -44,6 +50,7 @@ export declare function getCacheConfig(): CacheConfig;
|
|
|
44
50
|
* - httpServer: Node HTTP server (required by grafserv)
|
|
45
51
|
* - cacheKey: Unique identifier for this entry
|
|
46
52
|
* - createdAt: Timestamp when this entry was created
|
|
53
|
+
* - heapBytes: Heap retained by building this entry; the cache's size unit
|
|
47
54
|
*/
|
|
48
55
|
export interface GraphileCacheEntry {
|
|
49
56
|
pgl: PostGraphileInstance;
|
|
@@ -52,16 +59,31 @@ export interface GraphileCacheEntry {
|
|
|
52
59
|
httpServer: HttpServer;
|
|
53
60
|
cacheKey: string;
|
|
54
61
|
createdAt: number;
|
|
62
|
+
heapBytes: number;
|
|
55
63
|
/** Optional RealtimeManager for cursor-tracked subscription delivery */
|
|
56
64
|
realtimeManager?: {
|
|
57
65
|
stop(): Promise<void>;
|
|
58
66
|
} | null;
|
|
59
67
|
}
|
|
60
68
|
export declare const graphileCache: LRUCache<string, GraphileCacheEntry, unknown>;
|
|
69
|
+
export declare class GraphileCacheBudgetError extends Error {
|
|
70
|
+
readonly cacheKey: string;
|
|
71
|
+
readonly heapBytes: number;
|
|
72
|
+
readonly maxHeapBytes: number;
|
|
73
|
+
constructor(cacheKey: string, heapBytes: number, maxHeapBytes: number);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Cache a newly built handler, evicting least-recently-used handlers until the
|
|
77
|
+
* measured heap of all cached handlers fits the budget. A handler that alone
|
|
78
|
+
* exceeds the budget is released and rejected instead of being served uncached.
|
|
79
|
+
*/
|
|
80
|
+
export declare function cacheGraphileInstance(key: string, entry: GraphileCacheEntry): Promise<void>;
|
|
61
81
|
export interface CacheStats {
|
|
62
82
|
size: number;
|
|
63
83
|
max: number;
|
|
64
84
|
ttl: number;
|
|
85
|
+
heapBytes: number;
|
|
86
|
+
maxHeapBytes: number;
|
|
65
87
|
keys: string[];
|
|
66
88
|
}
|
|
67
89
|
/**
|
package/graphile-cache.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.closeAllCaches = exports.graphileCache = exports.cacheEvents = exports.CacheEventEmitter = exports.FIVE_MINUTES_MS = exports.ONE_HOUR_MS = void 0;
|
|
3
|
+
exports.closeAllCaches = exports.GraphileCacheBudgetError = exports.graphileCache = exports.MIN_ENTRY_HEAP_BYTES = exports.cacheEvents = exports.CacheEventEmitter = exports.FIVE_MINUTES_MS = exports.ONE_HOUR_MS = void 0;
|
|
4
4
|
exports.getCacheConfig = getCacheConfig;
|
|
5
|
+
exports.cacheGraphileInstance = cacheGraphileInstance;
|
|
5
6
|
exports.getCacheStats = getCacheStats;
|
|
6
7
|
exports.clearMatchingEntries = clearMatchingEntries;
|
|
8
|
+
const node_v8_1 = require("node:v8");
|
|
7
9
|
const logger_1 = require("@pgpmjs/logger");
|
|
8
10
|
const _12factor_env_1 = require("12factor-env");
|
|
9
11
|
const events_1 = require("events");
|
|
@@ -25,11 +27,16 @@ class CacheEventEmitter extends events_1.EventEmitter {
|
|
|
25
27
|
}
|
|
26
28
|
exports.CacheEventEmitter = CacheEventEmitter;
|
|
27
29
|
exports.cacheEvents = new CacheEventEmitter();
|
|
30
|
+
/** Floor for an entry's measured heap so a GC during its build cannot make it free. */
|
|
31
|
+
exports.MIN_ENTRY_HEAP_BYTES = 1024 * 1024;
|
|
32
|
+
const defaultMaxHeapBytes = () => Math.floor((0, node_v8_1.getHeapStatistics)().heap_size_limit / 2);
|
|
28
33
|
/**
|
|
29
34
|
* Get cache configuration from environment variables
|
|
30
35
|
*
|
|
31
36
|
* Supports:
|
|
32
37
|
* - GRAPHILE_CACHE_MAX: Maximum number of entries (default: 50)
|
|
38
|
+
* - GRAPHILE_CACHE_MAX_HEAP_BYTES: Total measured heap the cached handlers may
|
|
39
|
+
* retain (default: half of V8's heap limit, so the cache cannot fill the heap)
|
|
33
40
|
* - GRAPHILE_CACHE_TTL_MS: TTL in milliseconds
|
|
34
41
|
* - Production default: ONE_YEAR
|
|
35
42
|
* - Development default: FIVE_MINUTES_MS
|
|
@@ -42,28 +49,22 @@ function getCacheConfig() {
|
|
|
42
49
|
const max = (0, _12factor_env_1.parseEnvNumber)(process.env.GRAPHILE_CACHE_MAX) ?? 50;
|
|
43
50
|
const ttl = (0, _12factor_env_1.parseEnvNumber)(process.env.GRAPHILE_CACHE_TTL_MS) ??
|
|
44
51
|
(isDevelopment ? exports.FIVE_MINUTES_MS : ONE_YEAR);
|
|
45
|
-
|
|
52
|
+
const maxHeapBytes = (0, _12factor_env_1.parseEnvNumber)(process.env.GRAPHILE_CACHE_MAX_HEAP_BYTES) ?? defaultMaxHeapBytes();
|
|
53
|
+
return { max, ttl, maxHeapBytes };
|
|
46
54
|
}
|
|
47
|
-
// Track disposed entries to prevent double-disposal
|
|
48
|
-
const disposedKeys = new Set();
|
|
49
55
|
// Track keys that are being manually evicted for accurate eviction reason
|
|
50
56
|
const manualEvictionKeys = new Set();
|
|
57
|
+
// One disposal per entry: closeAllCaches() and the LRU dispose callback both
|
|
58
|
+
// dispose the same entry, and PostGraphile throws if released twice.
|
|
59
|
+
const disposals = new WeakMap();
|
|
51
60
|
/**
|
|
52
61
|
* Dispose a PostGraphile v5 cache entry
|
|
53
62
|
*
|
|
54
63
|
* Properly releases resources by:
|
|
55
64
|
* 1. Closing the HTTP server if listening
|
|
56
65
|
* 2. Releasing the PostGraphile instance (which internally releases grafserv)
|
|
57
|
-
*
|
|
58
|
-
* Uses disposedKeys set to prevent double-disposal when closeAllCaches()
|
|
59
|
-
* explicitly disposes entries and then clear() triggers the dispose callback.
|
|
60
66
|
*/
|
|
61
|
-
const
|
|
62
|
-
// Prevent double-disposal
|
|
63
|
-
if (disposedKeys.has(key)) {
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
disposedKeys.add(key);
|
|
67
|
+
const releaseEntry = async (entry, key) => {
|
|
67
68
|
log.debug(`Disposing PostGraphile[${key}]`);
|
|
68
69
|
try {
|
|
69
70
|
// Close HTTP server if it's listening
|
|
@@ -89,9 +90,14 @@ const disposeEntry = async (entry, key) => {
|
|
|
89
90
|
catch (err) {
|
|
90
91
|
log.error(`Error disposing PostGraphile[${key}]:`, err);
|
|
91
92
|
}
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
};
|
|
94
|
+
const disposeEntry = (entry, key) => {
|
|
95
|
+
let disposal = disposals.get(entry);
|
|
96
|
+
if (!disposal) {
|
|
97
|
+
disposal = releaseEntry(entry, key);
|
|
98
|
+
disposals.set(entry, disposal);
|
|
94
99
|
}
|
|
100
|
+
return disposal;
|
|
95
101
|
};
|
|
96
102
|
/**
|
|
97
103
|
* Determine the eviction reason for a cache entry
|
|
@@ -115,6 +121,8 @@ const initialConfig = getCacheConfig();
|
|
|
115
121
|
exports.graphileCache = new lru_cache_1.LRUCache({
|
|
116
122
|
max: initialConfig.max,
|
|
117
123
|
ttl: initialConfig.ttl,
|
|
124
|
+
maxSize: initialConfig.maxHeapBytes,
|
|
125
|
+
sizeCalculation: (entry) => entry.heapBytes,
|
|
118
126
|
updateAgeOnGet: true,
|
|
119
127
|
dispose: (entry, key) => {
|
|
120
128
|
// Determine eviction reason before disposal
|
|
@@ -129,6 +137,31 @@ exports.graphileCache = new lru_cache_1.LRUCache({
|
|
|
129
137
|
});
|
|
130
138
|
}
|
|
131
139
|
});
|
|
140
|
+
class GraphileCacheBudgetError extends Error {
|
|
141
|
+
cacheKey;
|
|
142
|
+
heapBytes;
|
|
143
|
+
maxHeapBytes;
|
|
144
|
+
constructor(cacheKey, heapBytes, maxHeapBytes) {
|
|
145
|
+
super(`PostGraphile[${cacheKey}] retains ${heapBytes} heap bytes, more than the ${maxHeapBytes}-byte graphile cache budget`);
|
|
146
|
+
this.cacheKey = cacheKey;
|
|
147
|
+
this.heapBytes = heapBytes;
|
|
148
|
+
this.maxHeapBytes = maxHeapBytes;
|
|
149
|
+
this.name = 'GraphileCacheBudgetError';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
exports.GraphileCacheBudgetError = GraphileCacheBudgetError;
|
|
153
|
+
/**
|
|
154
|
+
* Cache a newly built handler, evicting least-recently-used handlers until the
|
|
155
|
+
* measured heap of all cached handlers fits the budget. A handler that alone
|
|
156
|
+
* exceeds the budget is released and rejected instead of being served uncached.
|
|
157
|
+
*/
|
|
158
|
+
async function cacheGraphileInstance(key, entry) {
|
|
159
|
+
if (entry.heapBytes > exports.graphileCache.maxEntrySize) {
|
|
160
|
+
await disposeEntry(entry, key);
|
|
161
|
+
throw new GraphileCacheBudgetError(key, entry.heapBytes, exports.graphileCache.maxEntrySize);
|
|
162
|
+
}
|
|
163
|
+
exports.graphileCache.set(key, entry);
|
|
164
|
+
}
|
|
132
165
|
/**
|
|
133
166
|
* Get current cache statistics
|
|
134
167
|
*/
|
|
@@ -138,6 +171,8 @@ function getCacheStats() {
|
|
|
138
171
|
size: exports.graphileCache.size,
|
|
139
172
|
max: config.max,
|
|
140
173
|
ttl: config.ttl,
|
|
174
|
+
heapBytes: exports.graphileCache.calculatedSize,
|
|
175
|
+
maxHeapBytes: exports.graphileCache.maxSize,
|
|
141
176
|
keys: [...exports.graphileCache.keys()]
|
|
142
177
|
};
|
|
143
178
|
}
|
|
@@ -193,19 +228,14 @@ const closeAllCaches = async (verbose = false) => {
|
|
|
193
228
|
try {
|
|
194
229
|
if (verbose)
|
|
195
230
|
log.info('Closing all server caches...');
|
|
196
|
-
// Collect all entries and dispose them properly
|
|
197
231
|
const entries = [...exports.graphileCache.entries()];
|
|
198
232
|
// Mark all as manual evictions
|
|
199
233
|
for (const [key] of entries) {
|
|
200
234
|
manualEvictionKeys.add(key);
|
|
201
235
|
}
|
|
202
|
-
|
|
203
|
-
// Wait for all disposals to complete
|
|
204
|
-
await Promise.allSettled(disposePromises);
|
|
205
|
-
// Clear the cache after disposal (dispose callback will no-op due to disposedKeys)
|
|
236
|
+
// clear() starts each entry's disposal; wait for those same disposals.
|
|
206
237
|
exports.graphileCache.clear();
|
|
207
|
-
|
|
208
|
-
disposedKeys.clear();
|
|
238
|
+
await Promise.allSettled(entries.map(([key, entry]) => disposeEntry(entry, key)));
|
|
209
239
|
manualEvictionKeys.clear();
|
|
210
240
|
// Close pg pools
|
|
211
241
|
await pg_cache_1.pgCache.close();
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { CacheConfig, CacheEventEmitter, cacheEvents, CacheEvictionEvent, CacheStats, clearMatchingEntries, closeAllCaches, EvictionReason, FIVE_MINUTES_MS, getCacheConfig, getCacheStats, graphileCache, GraphileCacheEntry, ONE_HOUR_MS } from './graphile-cache';
|
|
1
|
+
export { CacheConfig, CacheEventEmitter, cacheEvents, CacheEvictionEvent, cacheGraphileInstance, CacheStats, clearMatchingEntries, closeAllCaches, EvictionReason, FIVE_MINUTES_MS, getCacheConfig, getCacheStats, graphileCache, GraphileCacheBudgetError, GraphileCacheEntry, MIN_ENTRY_HEAP_BYTES, ONE_HOUR_MS } from './graphile-cache';
|
|
2
2
|
export { createGraphileInstance } from './create-instance';
|
|
3
3
|
export { ModuleConfigCache, ModuleConfigCacheOptions } from './module-config-cache';
|
package/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ModuleConfigCache = exports.createGraphileInstance = exports.ONE_HOUR_MS = exports.graphileCache = exports.getCacheStats = exports.getCacheConfig = exports.FIVE_MINUTES_MS = exports.closeAllCaches = exports.clearMatchingEntries = exports.cacheEvents = exports.CacheEventEmitter = void 0;
|
|
3
|
+
exports.ModuleConfigCache = exports.createGraphileInstance = exports.ONE_HOUR_MS = exports.MIN_ENTRY_HEAP_BYTES = exports.GraphileCacheBudgetError = exports.graphileCache = exports.getCacheStats = exports.getCacheConfig = exports.FIVE_MINUTES_MS = exports.closeAllCaches = exports.clearMatchingEntries = exports.cacheGraphileInstance = exports.cacheEvents = exports.CacheEventEmitter = void 0;
|
|
4
4
|
// Main exports from graphile-cache package
|
|
5
5
|
var graphile_cache_1 = require("./graphile-cache");
|
|
6
6
|
// Event emitter for cache events
|
|
7
7
|
Object.defineProperty(exports, "CacheEventEmitter", { enumerable: true, get: function () { return graphile_cache_1.CacheEventEmitter; } });
|
|
8
8
|
Object.defineProperty(exports, "cacheEvents", { enumerable: true, get: function () { return graphile_cache_1.cacheEvents; } });
|
|
9
|
+
Object.defineProperty(exports, "cacheGraphileInstance", { enumerable: true, get: function () { return graphile_cache_1.cacheGraphileInstance; } });
|
|
9
10
|
// Clear matching entries
|
|
10
11
|
Object.defineProperty(exports, "clearMatchingEntries", { enumerable: true, get: function () { return graphile_cache_1.clearMatchingEntries; } });
|
|
11
12
|
Object.defineProperty(exports, "closeAllCaches", { enumerable: true, get: function () { return graphile_cache_1.closeAllCaches; } });
|
|
@@ -14,6 +15,8 @@ Object.defineProperty(exports, "getCacheConfig", { enumerable: true, get: functi
|
|
|
14
15
|
Object.defineProperty(exports, "getCacheStats", { enumerable: true, get: function () { return graphile_cache_1.getCacheStats; } });
|
|
15
16
|
// Cache instance and entry type
|
|
16
17
|
Object.defineProperty(exports, "graphileCache", { enumerable: true, get: function () { return graphile_cache_1.graphileCache; } });
|
|
18
|
+
Object.defineProperty(exports, "GraphileCacheBudgetError", { enumerable: true, get: function () { return graphile_cache_1.GraphileCacheBudgetError; } });
|
|
19
|
+
Object.defineProperty(exports, "MIN_ENTRY_HEAP_BYTES", { enumerable: true, get: function () { return graphile_cache_1.MIN_ENTRY_HEAP_BYTES; } });
|
|
17
20
|
// Time constants
|
|
18
21
|
Object.defineProperty(exports, "ONE_HOUR_MS", { enumerable: true, get: function () { return graphile_cache_1.ONE_HOUR_MS; } });
|
|
19
22
|
// Factory for creating PostGraphile v5 instances
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "graphile-cache",
|
|
3
|
-
"version": "4.16.
|
|
3
|
+
"version": "4.16.2",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "PostGraphile v5 LRU cache with automatic pool cleanup integration",
|
|
6
6
|
"main": "index.js",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"grafserv": "1.0.1",
|
|
36
36
|
"graphile-realtime-subscriptions": "^1.13.0",
|
|
37
37
|
"lru-cache": "^11.2.7",
|
|
38
|
-
"pg-cache": "^3.30.
|
|
38
|
+
"pg-cache": "^3.30.1",
|
|
39
39
|
"postgraphile": "5.1.4"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
@@ -53,5 +53,5 @@
|
|
|
53
53
|
"constructive",
|
|
54
54
|
"v5"
|
|
55
55
|
],
|
|
56
|
-
"gitHead": "
|
|
56
|
+
"gitHead": "eb44afc5ecdfa6e91aeb7ad8e24c9021b97ec027"
|
|
57
57
|
}
|