UNPKG

@graphql-hive/yoga

Version:
290 lines (289 loc) • 15.3 kB
import { GraphQLError, Kind, parse, } from 'graphql'; import { _createLRUCache, } from 'graphql-yoga'; import { addHiveTypenames, autoDisposeSymbol, createHive as createHiveClient, hideInjectedTypenames, isAsyncIterable, isHiveClient, } from '@graphql-hive/core'; import { Logger } from '@graphql-hive/logger'; import { version } from './version.js'; export { atLeastOnceSampler, createSchemaFetcher, createServicesFetcher, createSupergraphSDLFetcher, } from '@graphql-hive/core'; /** * graphql-yoga@5 exposes a `YogaLogger` as `yoga.logger` (`logger.info(msg, ...args)`), while * graphql-yoga@6 exposes a Hive `Logger` as `yoga.log` (`log.info(attrs, msg)`). */ function yogaLog(yoga, level, msg, attrs) { var _a, _b; const server = yoga; if (server.log) { if (attrs) { server.log[level](attrs, msg); } else { server.log[level](msg); } return; } if (attrs) { (_a = server.logger) === null || _a === void 0 ? void 0 : _a[level](msg, attrs); } else { (_b = server.logger) === null || _b === void 0 ? void 0 : _b[level](msg); } } export function createHive(clientOrOptions) { return createHiveClient(Object.assign(Object.assign({}, clientOrOptions), { agent: Object.assign({ name: 'hive-client-yoga', version }, clientOrOptions.agent) })); } export function useHive(clientOrOptions) { var _a; var _b; const parsedDocumentCache = _createLRUCache(); let latestSchema = null; const contextualCache = new WeakMap(); let hive; let yoga; let onYogaInit; let onYogaInitDefered = new Promise(res => (onYogaInit = () => { res(); onYogaInitDefered = null; })); const fieldLevelMetricsEnabled = isHiveClient(clientOrOptions) ? false : (typeof clientOrOptions.usage === 'object' && ((_a = clientOrOptions.usage) === null || _a === void 0 ? void 0 : _a.fieldLevelMetricsEnabled)) || false; const operationCache = fieldLevelMetricsEnabled ? _createLRUCache({ max: isHiveClient(clientOrOptions) ? 10000 : ((_b = clientOrOptions.cache) !== null && _b !== void 0 ? _b : 10000), }) : null; return { onYogaInit(payload) { yoga = payload.yoga; onYogaInit(); }, onSchemaChange({ schema }) { hive.reportSchema({ schema }); latestSchema = schema; operationCache === null || operationCache === void 0 ? void 0 : operationCache.clear(); }, onParams(context) { // we set the params if there is either a query or documentId in the request if ((context.params.query || 'documentId' in context.params) && latestSchema) { contextualCache.set(context.context, { callback: hive.collectUsage(), paramsArgs: context.params, }); } }, // Capture the original parsed document before execution plugins transform it, // so usage reporting reflects the client operation. onParse(parseCtx) { return ctx => { const result = ctx.result; if (result.kind === Kind.DOCUMENT) { const record = contextualCache.get(ctx.context); if (record) { // set the documents on thee operation context to be used in other callbacks record.parsedDocument = result; parsedDocumentCache.set(parseCtx.params.source, result); } } }; }, onExecute({ args, executeFn, setExecuteFn }) { var _a; const record = contextualCache.get(args.contextValue); if (fieldLevelMetricsEnabled && operationCache && latestSchema) { // Validation must run against the client document. Add the metadata fields only // to the document passed to execution and cache that transformed document. const query = (record === null || record === void 0 ? void 0 : record.paramsArgs.query) || ((_a = args.document.loc) === null || _a === void 0 ? void 0 : _a.source.body); const cachedDocument = query ? operationCache.get(query) : undefined; const modifiedDocument = cachedDocument === true ? args.document : cachedDocument || addHiveTypenames(args.document, latestSchema); if (query && cachedDocument === undefined) { operationCache.set(query, args.document === modifiedDocument || modifiedDocument); } if (args.document !== modifiedDocument) { setExecuteFn(executionArgs => executeFn(Object.assign(Object.assign({}, executionArgs), { document: modifiedDocument }))); } } return { onExecuteDone({ args, result }) { var _a; if (!record) { return; } record.executionArgs = args; if (!isAsyncIterable(result)) { if (result.data && fieldLevelMetricsEnabled) { hideInjectedTypenames(result.data); } args.contextValue.waitUntil(record.callback.finish(Object.assign(Object.assign({}, record.executionArgs), { // pass the original parsed document to the callback so the operation name and structure match the original document: (_a = record.parsedDocument) !== null && _a !== void 0 ? _a : record.executionArgs.document }), result, record.documentId)); return; } const errors = []; return { onNext(ctx) { if (ctx.result.data && fieldLevelMetricsEnabled) { hideInjectedTypenames(ctx.result.data); } if (!ctx.result.errors) { return; } errors.push(...ctx.result.errors); }, onEnd() { var _a; var _b, _c; args.contextValue.waitUntil(record.callback.finish(Object.assign(Object.assign({}, args), { // pass the original parsed document to the callback so the operation name and structure match the original document: (_c = (_b = record.parsedDocument) !== null && _b !== void 0 ? _b : (_a = record.executionArgs) === null || _a === void 0 ? void 0 : _a.document) !== null && _c !== void 0 ? _c : args.document }), errors.length ? { errors } : {}, record.documentId)); }, }; }, }; }, onSubscribe(context) { // In GraphQL.js 16 `onSubscribe` is called even if the schema does not contain a subscription type. // In GraphQL.js 17 there is a new validation rule [`KnownOperationTypes`](https://github.com/graphql/graphql-js/pull/3601) // that prevents `onSubscribe` being called if the schema has no subscription type. // We want to avoid running SDK code here as it would raise an exception in the schema coordinate collection. if (!context.args.schema.getSubscriptionType()) { return; } const record = contextualCache.get(context.args.contextValue); return { onSubscribeResult() { var _a; var _b, _c; const persistedDocumentId = record === null || record === void 0 ? void 0 : record.documentId; hive.collectSubscriptionUsage({ args: Object.assign(Object.assign(Object.assign({}, context.args), record === null || record === void 0 ? void 0 : record.executionArgs), { document: (_c = (_b = record === null || record === void 0 ? void 0 : record.parsedDocument) !== null && _b !== void 0 ? _b : (_a = record === null || record === void 0 ? void 0 : record.executionArgs) === null || _a === void 0 ? void 0 : _a.document) !== null && _c !== void 0 ? _c : context.args.document }), experimental__persistedDocumentHash: persistedDocumentId, }); }, }; }, onResultProcess({ serverContext, result }) { const record = contextualCache.get(serverContext); if (!record || Array.isArray(result) || isAsyncIterable(result) || record.executionArgs) { return; } // Report if execution was skipped due to response cache ( Symbol.for('servedFromResponseCache') in context.result) if (record.paramsArgs.query && latestSchema && Symbol.for('servedFromResponseCache') in result) { try { let document = parsedDocumentCache.get(record.paramsArgs.query); if (document === undefined) { document = parse(record.paramsArgs.query); parsedDocumentCache.set(record.paramsArgs.query, document); } serverContext.waitUntil(record.callback.finish({ document, schema: latestSchema, variableValues: record.paramsArgs.variables, operationName: record.paramsArgs.operationName, contextValue: serverContext, }, result, record.documentId)); } catch (err) { yogaLog(yoga, 'error', err); } } }, onPluginInit({ addPlugin }) { var _a; hive = isHiveClient(clientOrOptions) ? clientOrOptions : createHive(Object.assign(Object.assign({}, clientOrOptions), { logger: (_a = clientOrOptions.logger) !== null && _a !== void 0 ? _a : new Logger({ writers: [ { write(level, attrs, msg) { level = level === 'trace' ? 'debug' : level; if (!onYogaInitDefered) { yogaLog(yoga, level, msg, attrs); return; } // Defer logs until yoga instance is initialized // Ideally, onPluginInit would provide us access to the logger instance // See https://github.com/graphql-hive/graphql-yoga/issues/4048#issuecomment-3576258603 void onYogaInitDefered.then(() => { if (yoga) { yogaLog(yoga, level, msg, attrs); } }); }, }, ], }), agent: clientOrOptions.agent ? Object.assign({ // Hive Plugin should respect the given FetchAPI, note that this is not `yoga.fetch` fetch: (...args) => yoga.fetchAPI.fetch(...args) }, clientOrOptions.agent) : undefined })); void hive.info(); const persistedDocuments = hive.persistedDocuments; if (persistedDocuments) { // not using @graphql-yoga/plugin-persisted-operations because its majors are tied to // graphql-yoga majors (v3 breaks on yoga 6, v4 requires yoga 6) and we support both addPlugin({ async onParams({ params, request, context, setParams, }) { if (params.query) { if (!(await persistedDocuments.allowArbitraryDocuments(request))) { throw new GraphQLError('No persisted document provided.', { extensions: { code: 'PERSISTED_DOCUMENT_REQUIRED' }, }); } return; } const key = 'documentId' in params && typeof params.documentId === 'string' ? params.documentId : new URL(request.url).searchParams.get('documentId'); let document = null; if (key) { try { document = await persistedDocuments.resolve(key, { waitUntil: context.waitUntil, }); } catch (error) { if (error && typeof error === 'object' && 'code' in error && error.code === 'INVALID_DOCUMENT_ID' && 'message' in error && typeof error.message === 'string') { throw new GraphQLError(error.message, { extensions: { code: 'INVALID_DOCUMENT_ID' }, }); } throw error; } } if (!key || !document) { throw new GraphQLError('Persisted document not found.', { extensions: { code: 'PERSISTED_DOCUMENT_NOT_FOUND' }, }); } // after we resolve the document we need to update the cache record to contain the resolved document const record = contextualCache.get(context); if (record) { record.documentId = key; record.paramsArgs = Object.assign(Object.assign({}, record.paramsArgs), { query: document }); } setParams({ query: document, operationName: params.operationName, variables: params.variables, extensions: params.extensions, }); }, }); } }, onDispose() { if (hive[autoDisposeSymbol]) { return hive.dispose(); } }, }; }