-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathplugin.ts
More file actions
691 lines (638 loc) · 22.3 KB
/
Copy pathplugin.ts
File metadata and controls
691 lines (638 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import jsonStableStringify from 'fast-json-stable-stringify';
import {
ASTVisitor,
DocumentNode,
ExecutionArgs,
getOperationAST,
GraphQLDirective,
Kind,
print,
TypeInfo,
visit,
visitWithTypeInfo,
} from 'graphql';
import {
ExecutionResult,
getDocumentString,
isAsyncIterable,
Maybe,
ObjMap,
OnExecuteDoneHookResult,
OnExecuteHookResult,
Plugin,
} from '@envelop/core';
import {
getDirective,
MapperKind,
mapSchema,
memoize1,
memoize4,
mergeIncrementalResult,
} from '@graphql-tools/utils';
import type { Cache, CacheEntityRecord } from './cache.js';
import { hashSHA256 } from './hash-sha256.js';
import { createInMemoryCache } from './in-memory-cache.js';
/**
* Function for building the response cache key based on the input parameters
*/
export type BuildResponseCacheKeyFunction = (params: {
/** Raw document string as sent from the client. */
documentString: string;
/** Variable values as sent form the client. */
variableValues: ExecutionArgs['variableValues'];
/** The name of the GraphQL operation that should be executed from within the document. */
operationName?: Maybe<string>;
/** optional sessionId for make unique cache keys based on the session. */
sessionId: Maybe<string>;
/** GraphQL Context */
context: ExecutionArgs['contextValue'];
}) => Promise<string>;
export type GetDocumentStringFunction = (executionArgs: ExecutionArgs) => string;
export type ShouldCacheResultFunction = (params: {
cacheKey: string;
result: ExecutionResult;
}) => boolean;
export type UseResponseCacheParameter<PluginContext extends Record<string, any> = {}> = {
cache?: Cache | ((ctx: Record<string, any>) => Cache);
/**
* Maximum age in ms. Defaults to `Infinity`. Set it to 0 for disabling the global TTL.
*/
ttl?: number;
/**
* Overwrite the ttl for query operations whose execution result contains a specific object type.
* Useful if the occurrence of a object time in the execution result should reduce or increase the TTL of the query operation.
* The TTL per type is always favored over the global TTL.
*/
ttlPerType?: Record<string, number>;
/**
* Overwrite the ttl for query operations whose selection contains a specific schema coordinate (e.g. Query.users).
* Useful if the selection of a specific field should reduce the TTL of the query operation.
*
* The default value is `{}` and it will be merged with a `{ 'Query.__schema': 0 }` object.
* In the unusual case where you actually want to cache introspection query operations,
* you need to provide the value `{ 'Query.__schema': undefined }`.
*/
ttlPerSchemaCoordinate?: Record<string, number | undefined>;
scopePerSchemaCoordinate?: Record<string, 'PRIVATE' | 'PUBLIC' | undefined>;
/**
* Allows to cache responses based on the resolved session id.
* Return a unique value for each session.
* Return `null` or `undefined` to mark the session as public/global.
* Creates a global session by default.
* @param context GraphQL Context
*
* **Global Example:**
* ```ts
* useResponseCache({
* session: () => null,
* });
* ```
*
* **User Specific with global fallback example:**
* ```ts
* useResponseCache({
* session: (context) => context.user?.id ?? null,
* });
* ```
*/
session(context: PluginContext): string | undefined | null;
/**
* Specify whether the cache should be used based on the context.
* By default any request uses the cache.
*/
enabled?(context: PluginContext): boolean;
/**
* Skip caching of following the types.
*/
ignoredTypes?: string[];
/**
* List of fields that are used to identify a entity.
* Defaults to `["id"]`
*/
idFields?: Array<string>;
/**
* List of SchemaCoordinates in format {ObjectType}.{FieldName} which are ignored during scan for entities.
* Defaults to `[]`
*/
ignoreIdFieldsBySchemaCoordinate?: Array<string>;
/**
* Whether the mutation execution result should be used for invalidating resources.
* Defaults to `true`
*/
invalidateViaMutation?: boolean;
/**
* Customize the behavior how the response cache key is computed from the document, variable values and sessionId.
* Defaults to `defaultBuildResponseCacheKey`
*/
buildResponseCacheKey?: BuildResponseCacheKeyFunction;
/**
* Function used for reading the document string that is used for building the response cache key from the execution arguments.
* By default, the useResponseCache plugin hooks into onParse and caches the original operation string in a WeakMap.
* If you are hard overriding parse you need to set this function, otherwise responses will not be cached or served from the cache.
* Defaults to `defaultGetDocumentString`
*
*/
getDocumentString?: GetDocumentStringFunction;
/**
* Include extension values that provide useful information, such as whether the cache was hit or which resources a mutation invalidated.
* Defaults to `true` if `process.env["NODE_ENV"]` is set to `"development"`, otherwise `false`.
*/
includeExtensionMetadata?: boolean;
/**
* Checks if the execution result should be cached or ignored. By default, any execution that
* raises any error is ignored.
* Use this function to customize the behavior, such as caching results that have an EnvelopError.
*/
shouldCacheResult?: ShouldCacheResultFunction;
};
/**
* Default function used for building the response cache key.
* It is exported here for advanced use-cases. E.g. if you want to short circuit and serve responses from the cache on a global level in order to completely by-pass the GraphQL flow.
*/
export const defaultBuildResponseCacheKey = (params: {
documentString: string;
variableValues: ExecutionArgs['variableValues'];
operationName?: Maybe<string>;
sessionId: Maybe<string>;
}): Promise<string> =>
hashSHA256(
[
params.documentString,
params.operationName ?? '',
jsonStableStringify(params.variableValues ?? {}),
params.sessionId ?? '',
].join('|'),
);
/**
* Default function used to check if the result should be cached.
*
* It is exported here for advanced use-cases. E.g. if you want to choose if
* results with certain error types should be cached.
*
* By default, results with errors (unexpected, EnvelopError, or GraphQLError) are not cached.
*/
export const defaultShouldCacheResult: ShouldCacheResultFunction = (params): boolean => {
if (params.result.errors) {
// eslint-disable-next-line no-console
console.warn('[useResponseCache] Failed to cache due to errors');
return false;
}
return true;
};
export function defaultGetDocumentString(executionArgs: ExecutionArgs): string {
return getDocumentString(executionArgs.document, print);
}
export type ResponseCacheExtensions =
| {
hit: true;
}
| {
hit: false;
didCache: false;
}
| {
hit: false;
didCache: true;
ttl: number;
}
| {
invalidatedEntities: CacheEntityRecord[];
};
export type ResponseCacheExecutionResult = ExecutionResult<
ObjMap<unknown>,
{ responseCache?: ResponseCacheExtensions }
>;
const getDocumentWithMetadataAndTTL = memoize4(function addTypeNameToDocument(
document: DocumentNode,
{
invalidateViaMutation,
ttlPerSchemaCoordinate,
}: {
invalidateViaMutation: boolean;
ttlPerSchemaCoordinate?: Record<string, number | undefined>;
},
schema: any,
idFieldByTypeName: Map<string, string>,
): [DocumentNode, number | undefined] {
const typeInfo = new TypeInfo(schema);
let ttl: number | undefined;
const visitor: ASTVisitor = {
OperationDefinition: {
enter(node): void | false {
if (!invalidateViaMutation && node.operation === 'mutation') {
return false;
}
if (node.operation === 'subscription') {
return false;
}
},
},
...(ttlPerSchemaCoordinate != null && {
Field(fieldNode) {
const parentType = typeInfo.getParentType();
if (parentType) {
const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate] as unknown;
ttl = calculateTtl(maybeTtl, ttl);
}
},
}),
SelectionSet(node, _key) {
const parentType = typeInfo.getParentType();
const idField = parentType && idFieldByTypeName.get(parentType.name);
return {
...node,
selections: [
{
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: '__typename',
},
alias: {
kind: Kind.NAME,
value: '__responseCacheTypeName',
},
},
...(idField
? [
{
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: idField },
alias: { kind: Kind.NAME, value: '__responseCacheId' },
},
]
: []),
...node.selections,
],
};
},
};
return [visit(document, visitWithTypeInfo(typeInfo, visitor)), ttl];
});
type CacheControlDirective = {
maxAge?: number;
scope?: 'PUBLIC' | 'PRIVATE';
};
export function useResponseCache<PluginContext extends Record<string, any> = {}>({
cache = createInMemoryCache(),
ttl: globalTtl = Infinity,
session,
enabled,
ignoredTypes = [],
ttlPerType = {},
ttlPerSchemaCoordinate = {},
scopePerSchemaCoordinate = {},
idFields = ['id'],
ignoreIdFieldsBySchemaCoordinate = [],
invalidateViaMutation = true,
buildResponseCacheKey = defaultBuildResponseCacheKey,
getDocumentString = defaultGetDocumentString,
shouldCacheResult = defaultShouldCacheResult,
includeExtensionMetadata = typeof process !== 'undefined'
? // eslint-disable-next-line dot-notation
process.env['NODE_ENV'] === 'development' || !!process.env['DEBUG']
: false,
}: UseResponseCacheParameter<PluginContext>): Plugin<PluginContext> {
const cacheFactory = typeof cache === 'function' ? memoize1(cache) : () => cache;
const ignoredTypesMap = new Set<string>(ignoredTypes);
const typePerSchemaCoordinateMap = new Map<string, string[]>();
enabled = enabled ? memoize1(enabled) : enabled;
// never cache Introspections
ttlPerSchemaCoordinate = { 'Query.__schema': 0, ...ttlPerSchemaCoordinate };
const documentMetadataOptions = {
queries: { invalidateViaMutation, ttlPerSchemaCoordinate },
mutations: { invalidateViaMutation }, // remove ttlPerSchemaCoordinate for mutations to skip TTL calculation
};
const idFieldByTypeName = new Map<string, string>();
let schema: any;
function isPrivate(typeName: string, data: Record<string, unknown>): boolean {
if (scopePerSchemaCoordinate[typeName] === 'PRIVATE') {
return true;
}
return Object.keys(data).some(
fieldName => scopePerSchemaCoordinate[`${typeName}.${fieldName}`] === 'PRIVATE',
);
}
return {
onSchemaChange({ schema: newSchema }) {
if (schema === newSchema) {
return;
}
schema = newSchema;
const directive = schema.getDirective('cacheControl') as unknown as
| GraphQLDirective
| undefined;
mapSchema(schema, {
...(directive && {
[MapperKind.COMPOSITE_TYPE]: type => {
const cacheControlAnnotations = getDirective(
schema,
type,
'cacheControl',
) as unknown as CacheControlDirective[] | undefined;
cacheControlAnnotations?.forEach(cacheControl => {
if (cacheControl.maxAge != null) {
ttlPerType[type.name] = cacheControl.maxAge * 1000;
}
if (cacheControl.scope) {
scopePerSchemaCoordinate[type.name] = cacheControl.scope;
}
});
return type;
},
}),
[MapperKind.FIELD]: (fieldConfig, fieldName, typeName) => {
const schemaCoordinates = `${typeName}.${fieldName}`;
const resultTypeNames = unwrapTypenames(fieldConfig.type);
typePerSchemaCoordinateMap.set(schemaCoordinates, resultTypeNames);
if (
idFields.includes(fieldName) &&
!idFieldByTypeName.has(typeName) &&
!ignoreIdFieldsBySchemaCoordinate?.includes(schemaCoordinates)
) {
idFieldByTypeName.set(typeName, fieldName);
}
if (directive) {
const cacheControlAnnotations = getDirective(
schema,
fieldConfig,
'cacheControl',
) as unknown as CacheControlDirective[] | undefined;
cacheControlAnnotations?.forEach(cacheControl => {
if (cacheControl.maxAge != null) {
ttlPerSchemaCoordinate[schemaCoordinates] = cacheControl.maxAge * 1000;
}
if (cacheControl.scope) {
scopePerSchemaCoordinate[schemaCoordinates] = cacheControl.scope;
}
});
}
return fieldConfig;
},
});
},
async onExecute(onExecuteParams) {
if (enabled && !enabled(onExecuteParams.args.contextValue)) {
return;
}
const identifier = new Map<string, CacheEntityRecord>();
const types = new Set<string>();
let currentTtl: number | undefined;
let skip = false;
const sessionId = session(onExecuteParams.args.contextValue);
function setExecutor({
execute,
onExecuteDone,
}: {
execute: typeof onExecuteParams.executeFn;
onExecuteDone?: OnExecuteHookResult<PluginContext>['onExecuteDone'];
}): OnExecuteHookResult<PluginContext> {
let executed = false;
onExecuteParams.setExecuteFn(args => {
executed = true;
return execute(args);
});
return {
onExecuteDone(params) {
if (!executed) {
// eslint-disable-next-line no-console
console.warn(
'[useResponseCache] The cached execute function was not called, another plugin might have overwritten it. Please check your plugin order.',
);
}
return onExecuteDone?.(params);
},
};
}
function processResult(data: any) {
if (data == null || typeof data !== 'object') {
return;
}
if (Array.isArray(data)) {
for (const item of data) {
processResult(item);
}
return;
}
const typename = data.__responseCacheTypeName;
delete data.__responseCacheTypeName;
const entityId = data.__responseCacheId;
delete data.__responseCacheId;
// Always process nested objects, even if we are skipping cache, to ensure the result is cleaned up
// of metadata fields added to the query document.
for (const fieldName in data) {
processResult(data[fieldName]);
}
if (!skip) {
if (ignoredTypesMap.has(typename) || (!sessionId && isPrivate(typename, data))) {
skip = true;
return;
}
types.add(typename);
if (typename in ttlPerType) {
const maybeTtl = ttlPerType[typename] as unknown;
currentTtl = calculateTtl(maybeTtl, currentTtl);
}
if (entityId != null) {
identifier.set(`${typename}:${entityId}`, { typename, id: entityId });
}
for (const fieldName in data) {
const fieldData = data[fieldName];
if (fieldData == null || (Array.isArray(fieldData) && fieldData.length === 0)) {
const inferredTypes = typePerSchemaCoordinateMap.get(`${typename}.${fieldName}`);
inferredTypes?.forEach(inferredType => {
if (inferredType in ttlPerType) {
const maybeTtl = ttlPerType[inferredType] as unknown;
currentTtl = calculateTtl(maybeTtl, currentTtl);
}
identifier.set(inferredType, { typename: inferredType });
});
}
}
}
}
function invalidateCache(
result: ExecutionResult,
setResult: (newResult: ExecutionResult) => void,
): void {
processResult(result.data);
const cacheInstance = cacheFactory(onExecuteParams.args.contextValue);
if (cacheInstance == null) {
// eslint-disable-next-line no-console
console.warn(
'[useResponseCache] Cache instance is not available for the context. Skipping invalidation.',
);
return;
}
cacheInstance.invalidate(identifier.values());
if (includeExtensionMetadata) {
setResult(
resultWithMetadata(result, {
invalidatedEntities: Array.from(identifier.values()),
}),
);
}
}
if (invalidateViaMutation !== false) {
const operationAST = getOperationAST(
onExecuteParams.args.document,
onExecuteParams.args.operationName,
);
if (operationAST?.operation === 'mutation') {
return setExecutor({
execute(args) {
const [document] = getDocumentWithMetadataAndTTL(
args.document,
documentMetadataOptions.mutations,
args.schema,
idFieldByTypeName,
);
return onExecuteParams.executeFn({ ...args, document });
},
onExecuteDone({ result, setResult }) {
if (isAsyncIterable(result)) {
return handleAsyncIterableResult(invalidateCache);
}
return invalidateCache(result, setResult);
},
});
}
}
const cacheKey = await buildResponseCacheKey({
documentString: getDocumentString(onExecuteParams.args),
variableValues: onExecuteParams.args.variableValues,
operationName: onExecuteParams.args.operationName,
sessionId,
context: onExecuteParams.args.contextValue,
});
const cacheInstance = cacheFactory(onExecuteParams.args.contextValue);
if (cacheInstance == null) {
// eslint-disable-next-line no-console
console.warn(
'[useResponseCache] Cache instance is not available for the context. Skipping cache lookup.',
);
}
const cachedResponse = (await cacheInstance.get(cacheKey)) as ResponseCacheExecutionResult;
if (cachedResponse != null) {
return setExecutor({
execute: () =>
includeExtensionMetadata
? resultWithMetadata(cachedResponse, { hit: true })
: cachedResponse,
});
}
function maybeCacheResult(
result: ExecutionResult,
setResult: (newResult: ExecutionResult) => void,
) {
processResult(result.data);
// we only use the global ttl if no currentTtl has been determined.
const finalTtl = currentTtl ?? globalTtl;
if (skip || !shouldCacheResult({ cacheKey, result }) || finalTtl === 0) {
if (includeExtensionMetadata) {
setResult(resultWithMetadata(result, { hit: false, didCache: false }));
}
return;
}
cacheInstance.set(cacheKey, result, identifier.values(), finalTtl);
if (includeExtensionMetadata) {
setResult(resultWithMetadata(result, { hit: false, didCache: true, ttl: finalTtl }));
}
}
return setExecutor({
execute(args) {
const [document, ttl] = getDocumentWithMetadataAndTTL(
args.document,
documentMetadataOptions.queries,
schema,
idFieldByTypeName,
);
currentTtl = ttl;
return onExecuteParams.executeFn({ ...args, document });
},
onExecuteDone({ result, setResult }) {
if (isAsyncIterable(result)) {
return handleAsyncIterableResult(maybeCacheResult);
}
return maybeCacheResult(result, setResult);
},
});
},
};
}
function handleAsyncIterableResult<PluginContext extends Record<string, any> = {}>(
handler: (result: ExecutionResult, setResult: (newResult: ExecutionResult) => void) => void,
): OnExecuteDoneHookResult<PluginContext> {
// When the result is an AsyncIterable, it means the query is using @defer or @stream.
// This means we have to build the final result by merging the incremental results.
// The merged result is then used to know if we should cache it and to calculate the ttl.
const result: ExecutionResult = {};
return {
onNext(payload) {
const { data, errors, extensions } = payload.result;
// This is the first result with the initial data payload sent to the client. We use it as the base result
if (data) {
result.data = data;
}
if (errors) {
result.errors = errors;
}
if (extensions) {
result.extensions = extensions;
}
if ('hasNext' in payload.result) {
const { incremental, hasNext } = payload.result;
if (incremental) {
for (const patch of incremental) {
mergeIncrementalResult({ executionResult: result, incrementalResult: patch });
}
}
if (!hasNext) {
// The query is complete, we can process the final result
handler(result, payload.setResult);
}
}
},
};
}
export function resultWithMetadata(
result: ExecutionResult,
metadata: ResponseCacheExtensions,
): ResponseCacheExecutionResult {
return {
...result,
extensions: {
...result.extensions,
responseCache: {
...(result as ResponseCacheExecutionResult).extensions?.responseCache,
...metadata,
},
},
};
}
function calculateTtl(typeTtl: unknown, currentTtl: number | undefined): number | undefined {
if (typeof typeTtl === 'number' && !Number.isNaN(typeTtl)) {
if (typeof currentTtl === 'number') {
return Math.min(currentTtl, typeTtl);
}
return typeTtl;
}
return currentTtl;
}
function unwrapTypenames(type: any): string[] {
if (type.ofType) {
return unwrapTypenames(type.ofType);
}
if (type._types) {
return type._types.map((t: any) => unwrapTypenames(t)).flat();
}
return [type.name];
}
export const cacheControlDirective = /* GraphQL */ `
enum CacheControlScope {
PUBLIC
PRIVATE
}
directive @cacheControl(maxAge: Int, scope: CacheControlScope) on FIELD_DEFINITION | OBJECT
`;