Skip to content

Commit

Permalink
Fix Hive Transform and additional resolvers import issues (#8007)
Browse files Browse the repository at this point in the history
* fix(hive-transform): usage reporting

* No autodISPOSE

* Fix Information

* Improvements on importing

* Fix arguments node

* lets go

* chore(dependencies): updated changesets for modified dependencies

* Go

* Go

* Fix artifacts

* Fix integrity

* Fix

* Fix TS issue

* Use the given schema

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
ardatan and github-actions[bot] authored Nov 27, 2024
1 parent a24859f commit 9f9f6fe
Show file tree
Hide file tree
Showing 15 changed files with 138 additions and 33 deletions.
5 changes: 5 additions & 0 deletions .changeset/@graphql-mesh_include-8007-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@graphql-mesh/include": patch
---
dependencies updates:
- Added dependency [`@graphql-mesh/utils@^0.103.4` ↗︎](https://www.npmjs.com/package/@graphql-mesh/utils/v/0.103.4) (to `dependencies`)
5 changes: 5 additions & 0 deletions .changeset/cuddly-spies-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-mesh/transform-hive': patch
---

Do not break the request even if the operation is not able to process
8 changes: 8 additions & 0 deletions .changeset/fresh-insects-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@omnigraph/json-schema': patch
'@omnigraph/openapi': patch
'@omnigraph/raml': patch
---

DEBUG logs were accidentially written to the output, now it correctly prints logs to the logger not
the output
6 changes: 6 additions & 0 deletions .changeset/silver-days-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-mesh/cli': patch
'@graphql-mesh/include': patch
---

Improvements on imports
5 changes: 5 additions & 0 deletions .changeset/thick-goats-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-mesh/utils': patch
---

Always pass a valid info
10 changes: 10 additions & 0 deletions packages/fusion/composition/tests/loaders.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { OperationTypeNode } from 'graphql';
import { createGatewayRuntime, useCustomFetch } from '@graphql-hive/gateway-runtime';
import type { Logger } from '@graphql-mesh/types';
import { loadJSONSchemaSubgraph } from '@omnigraph/json-schema';
import { composeSubgraphs } from '../src/compose';

describe('Loaders', () => {
const logger: Logger = {
log: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
child: () => logger,
};
it('works', async () => {
const loadedSubgraph = loadJSONSchemaSubgraph('TEST', {
endpoint: 'http://localhost/my-test-api',
Expand All @@ -24,6 +33,7 @@ describe('Loaders', () => {
})({
fetch,
cwd: process.cwd(),
logger,
});
const { supergraphSdl } = composeSubgraphs([
{
Expand Down
1 change: 1 addition & 0 deletions packages/include/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
},
"typings": "dist/typings/index.d.ts",
"dependencies": {
"@graphql-mesh/utils": "^0.103.4",
"dotenv": "^16.3.1",
"get-tsconfig": "^4.7.6",
"jiti": "^2.0.0",
Expand Down
32 changes: 19 additions & 13 deletions packages/include/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
// eslint-disable-next-line import/no-nodejs-modules
import Module from 'node:module';
import { createPathsMatcher, getTsconfig } from 'get-tsconfig';
import createJITI from 'jiti';
import { createJiti } from 'jiti';
import { defaultImportFn } from '@graphql-mesh/utils';

const jiti = createJITI(
const jiti = createJiti(
/**
* We intentionally provide an empty string here and let jiti handle the base URL.
*
* This is because `import.meta.url` is not available in CJS (and cant even be in the syntax)
* and `__filename` is not available in ESM.
*/
'',
{
debug: !!process.env.DEBUG,
},
);

/**
Expand All @@ -20,18 +24,20 @@ const jiti = createJITI(
*
* If the module at {@link path} is not found, `null` will be returned.
*/
export async function include<T = any>(path: string, nativeImport?: boolean): Promise<T> {
const module = await (nativeImport ? import(path) : jiti.import(path, {}));
if (!module) {
throw new Error('Included module is empty');
}
if (typeof module !== 'object') {
throw new Error(`Included module is not an object, is instead "${typeof module}"`);
}
if ('default' in module) {
return module.default as T;
export async function include<T = any>(path: string): Promise<T> {
try {
// JITI's tryNative tries native at first but with \`import\`
// So in CJS, this becomes \`require\`, but it still satisfies JITI's native import
return await defaultImportFn(path);
} catch {
const mod = await jiti.import<T>(path, {
default: true,
});
if (!mod) {
throw new Error(`Module at path "${path}" not found`);
}
return mod;
}
return module as T;
}

export interface RegisterTsconfigPathsOptions {
Expand Down
1 change: 1 addition & 0 deletions packages/legacy/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export async function graphqlMesh(
configName: cliParams.configName,
additionalPackagePrefixes: cliParams.additionalPackagePrefixes,
initialLoggerPrefix: cliParams.initialLoggerPrefix,
importFn: include,
});
logger = meshConfig.logger;

Expand Down
54 changes: 40 additions & 14 deletions packages/legacy/transforms/hive/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import type { ExecutionResult, GraphQLSchema } from 'graphql';
import { isSchema, Kind, visit, type ExecutionResult, type GraphQLSchema } from 'graphql';
import type { HiveClient, HivePluginOptions } from '@graphql-hive/core';
import { createHive } from '@graphql-hive/yoga';
import { process } from '@graphql-mesh/cross-helpers';
import { stringInterpolator } from '@graphql-mesh/string-interpolation';
import type { MeshTransform, MeshTransformOptions, YamlConfig } from '@graphql-mesh/types';
import type { DelegationContext } from '@graphql-tools/delegate';
import type { ExecutionRequest } from '@graphql-tools/utils';
import { mapMaybePromise, type ExecutionRequest } from '@graphql-tools/utils';

interface TransformationContext {
collectUsageCallback: ReturnType<HiveClient['collectUsage']>;
collectUsageCallback?: ReturnType<HiveClient['collectUsage']>;
request: ExecutionRequest;
}

export default class HiveTransform implements MeshTransform {
private hiveClient: HiveClient;
private logger: MeshTransformOptions<YamlConfig.HivePlugin>['logger'];
private schema: GraphQLSchema;
constructor({ config, pubsub, logger }: MeshTransformOptions<YamlConfig.HivePlugin>) {
this.logger = logger;
const enabled =
Expand Down Expand Up @@ -76,19 +77,31 @@ export default class HiveTransform implements MeshTransform {
agent,
usage,
reporting,
autoDispose: ['SIGINT', 'SIGTERM'],
autoDispose: false,
selfHosting: config.selfHosting,
});
const id = pubsub.subscribe('destroy', () => {
this.hiveClient
.dispose()
.catch(e => logger.error(`Hive client failed to dispose`, e))
.finally(() => pubsub.unsubscribe(id));
try {
mapMaybePromise(
this.hiveClient.dispose(),
() => {
pubsub.unsubscribe(id);
},
e => {
logger.error(`Hive client failed to dispose`, e);
pubsub.unsubscribe(id);
},
);
} catch (e) {
logger.error(`Failed to dispose hive client`, e);
pubsub.unsubscribe(id);
}
});
}

transformSchema(schema: GraphQLSchema) {
this.hiveClient.reportSchema({ schema });
this.schema = schema;
return schema;
}

Expand All @@ -97,8 +110,12 @@ export default class HiveTransform implements MeshTransform {
delegationContext: DelegationContext,
transformationContext: TransformationContext,
) {
transformationContext.collectUsageCallback = this.hiveClient.collectUsage();
transformationContext.request = request;
try {
transformationContext.collectUsageCallback = this.hiveClient.collectUsage();
transformationContext.request = request;
} catch (e) {
this.logger.error(`Failed to collect usage`, e);
}
return request;
}

Expand All @@ -110,18 +127,27 @@ export default class HiveTransform implements MeshTransform {
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- we dont really care about usage reporting result
try {
transformationContext
.collectUsageCallback(
.collectUsageCallback?.(
{
schema: delegationContext.transformedSchema,
document: transformationContext.request.document,
schema: this.schema,
document: visit(transformationContext.request.document, {
[Kind.FIELD](node) {
if (!node.arguments) {
return {
...node,
arguments: [],
};
}
},
}),
rootValue: transformationContext.request.rootValue,
contextValue: transformationContext.request.context,
variableValues: transformationContext.request.variables,
operationName: transformationContext.request.operationName,
},
result,
)
.catch(e => {
?.catch(e => {
this.logger.error(`Failed to report usage`, e);
});
} catch (e) {
Expand Down
28 changes: 28 additions & 0 deletions packages/legacy/utils/src/in-context-sdk.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import type {
ArgumentNode,
DocumentNode,
FieldNode,
GraphQLObjectType,
GraphQLResolveInfo,
GraphQLSchema,
OperationDefinitionNode,
OperationTypeNode,
SelectionNode,
SelectionSetNode,
} from 'graphql';
import { getNamedType, isLeafType, Kind, print } from 'graphql';
Expand Down Expand Up @@ -219,6 +221,7 @@ export function getInContextSDK(
onDelegateHook => onDelegateHook(onDelegatePayload),
onDelegateHookDones,
);
fixInfo(batchDelegationOptions.info, operationType as OperationTypeNode);
return mapMaybePromise(onDelegateResult$, () =>
handleIterationResult(
batchDelegateToSchema,
Expand Down Expand Up @@ -253,6 +256,7 @@ export function getInContextSDK(
onDelegateHook => onDelegateHook(onDelegatePayload),
onDelegateHookDones,
);
fixInfo(regularDelegateOptions.info, operationType as OperationTypeNode);
return mapMaybePromise(onDelegateResult$, () =>
handleIterationResult(
delegateToSchema,
Expand Down Expand Up @@ -333,3 +337,27 @@ function handleIterationResult<TDelegateFn extends (...args: any) => any>(
return mapMaybePromise(onDelegateDoneResult$, () => delegationResult);
});
}

function fixInfo(info: GraphQLResolveInfo, operationType: OperationTypeNode) {
(info.operation as OperationDefinitionNode) ||= {
kind: Kind.OPERATION_DEFINITION,
operation: operationType as OperationTypeNode,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [],
},
};
(info.operation.selectionSet as SelectionSetNode) ||= {
kind: Kind.SELECTION_SET,
selections: [],
};
info.operation.selectionSet.selections ||= [];
(info.operation.selectionSet.selections[0] as SelectionNode) ||= {
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: '__typename',
},
} as FieldNode;
((info.operation.selectionSet.selections[0] as FieldNode).arguments as ArgumentNode[]) ||= [];
}
5 changes: 3 additions & 2 deletions packages/loaders/json-schema/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { TransportGetSubgraphExecutor } from '@graphql-mesh/transport-common';
import transportRest, { type RESTTransportOptions } from '@graphql-mesh/transport-rest';
import type { MeshFetch } from '@graphql-mesh/types';
import type { Logger, MeshFetch } from '@graphql-mesh/types';
import {
loadGraphQLSchemaFromJSONSchemas,
loadNonExecutableGraphQLSchemaFromJSONSchemas,
Expand All @@ -15,12 +15,13 @@ export * from './getGraphQLSchemaFromDereferencedJSONSchema.js';
export type * from './types.js';

export function loadJSONSchemaSubgraph(name: string, options: JSONSchemaLoaderOptions) {
return (ctx: { fetch: MeshFetch; cwd: string }) => ({
return (ctx: { fetch: MeshFetch; cwd: string; logger: Logger }) => ({
name,
schema$: loadNonExecutableGraphQLSchemaFromJSONSchemas(name, {
...options,
fetch: ctx.fetch,
cwd: ctx.cwd,
logger: ctx.logger,
}),
});
}
Expand Down
5 changes: 3 additions & 2 deletions packages/loaders/openapi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { MeshFetch } from '@graphql-mesh/types';
import type { Logger, MeshFetch } from '@graphql-mesh/types';
import { loadNonExecutableGraphQLSchemaFromOpenAPI } from './loadGraphQLSchemaFromOpenAPI.js';
import type { OpenAPILoaderOptions } from './types.js';

Expand All @@ -8,12 +8,13 @@ export { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFr
export type { OpenAPILoaderOptions } from './types.js';

export function loadOpenAPISubgraph(name: string, options: OpenAPILoaderOptions) {
return (ctx: { fetch: MeshFetch; cwd: string }) => ({
return (ctx: { fetch: MeshFetch; cwd: string; logger: Logger }) => ({
name,
schema$: loadNonExecutableGraphQLSchemaFromOpenAPI(name, {
...options,
fetch: ctx.fetch,
cwd: ctx.cwd,
logger: ctx.logger,
}),
});
}
Expand Down
5 changes: 3 additions & 2 deletions packages/loaders/raml/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { MeshFetch } from '@graphql-mesh/types';
import type { Logger, MeshFetch } from '@graphql-mesh/types';
import { loadGraphQLSchemaFromRAML } from './loadGraphQLSchemaFromRAML.js';
import type { RAMLLoaderOptions } from './types.js';

Expand All @@ -8,12 +8,13 @@ export { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromR
export type { RAMLLoaderOptions } from './types.js';

export function loadRAMLSubgraph(name: string, options: RAMLLoaderOptions) {
return (ctx: { fetch: MeshFetch; cwd: string }) => ({
return (ctx: { fetch: MeshFetch; cwd: string; logger: Logger }) => ({
name,
schema$: loadGraphQLSchemaFromRAML(name, {
...options,
fetch: ctx.fetch,
cwd: ctx.cwd,
logger: ctx.logger,
}),
});
}
Expand Down
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6199,6 +6199,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "@graphql-mesh/include@workspace:packages/include"
dependencies:
"@graphql-mesh/utils": "npm:^0.103.4"
dotenv: "npm:^16.3.1"
get-tsconfig: "npm:^4.7.6"
glob: "npm:^11.0.0"
Expand Down

0 comments on commit 9f9f6fe

Please sign in to comment.