Skip to content

Commit

Permalink
Support Hive's experimental persisted documents (#7530)
Browse files Browse the repository at this point in the history
* types

* persisted docs in hive plugin

* changeset

* impl and use

* changeset

* omit persisteddocs from hiverportingoptions

* disable usage reporting if just persisted documents are configured

* support truthy debug env vars

* ok eslint go away

* chore(dependencies): updated changesets for modified dependencies

* chore(dependencies): updated changesets for modified dependencies

* Add allowArbitraryDocuments option

* Add persisted documents plugin

* Documentation

* Fix links

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Arda TANRIKULU <ardatanrikulu@gmail.com>
  • Loading branch information
3 people authored Aug 20, 2024
1 parent 13fa835 commit db41f96
Show file tree
Hide file tree
Showing 18 changed files with 384 additions and 28 deletions.
25 changes: 25 additions & 0 deletions .changeset/chilly-foxes-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@graphql-mesh/serve-cli': minor
---

Support Hive's experimental persisted documents

### Using CLI options

```sh
mesh-serve supergraph [schemaPathOrUrl] --hive-persisted-documents-endpoint "https://cdn.graphql-hive.com/<target_id>" --hive-persisted-documents-token <cdn_access_token>
```

### Using config file

```ts
import { defineConfig } from '@graphql-mesh/serve-cli'

export const serveConfig = defineConfig({
persistedDocuments: {
type: 'hive',
endpoint: 'https://cdn.graphql-hive.com/<target_id>',
token: '<cdn_access_token>'
}
})
```
5 changes: 5 additions & 0 deletions .changeset/happy-eels-speak.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-mesh/plugin-hive': patch
---

Support truthy DEBUG environment variables (1, t, true, y, yes)
36 changes: 36 additions & 0 deletions .changeset/sour-lemons-think.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
'@graphql-mesh/types': minor
'@graphql-mesh/plugin-hive': minor
---

Support Hive's experimental persisted documents

```ts
import { useMeshHive } from '@graphql-mesh/plugin-hive'

// Usage Reporting
useMeshHive({
token: '<hive_registry_token>'
})

// Persisted Documents
useMeshHive({
experimental__persistedDocuments: {
cdn: {
endpoint: 'https://cdn.graphql-hive.com/<target_id>',
accessToken: '<cdn_access_token>'
}
}
})

// Usage Reporting and Persisted Documents
useMeshHive({
token: '<hive_registry_token>',
experimental__persistedDocuments: {
cdn: {
endpoint: 'https://cdn.graphql-hive.com/<target_id>',
accessToken: '<cdn_access_token>'
}
}
})
```
17 changes: 17 additions & 0 deletions .changeset/tidy-rocks-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@graphql-mesh/serve-runtime': minor
---

Support Hive's experimental persisted documents

```ts
import { createServeRuntime } from '@graphql-mesh/serve-runtime'

createServeRuntime({
persistedDocuments: {
type: 'hive',
endpoint: 'https://cdn.graphql-hive.com/<target_id>',
token: '<cdn_access_token>'
}
})
```
45 changes: 42 additions & 3 deletions packages/legacy/types/src/config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2025,7 +2025,7 @@
},
"token": {
"type": "string",
"description": "Access Token"
"description": "Access Token for Usage Reporting"
},
"agent": {
"$ref": "#/definitions/HiveAgentOptions",
Expand All @@ -2042,9 +2042,12 @@
"selfHosting": {
"$ref": "#/definitions/HiveSelfHostingOptions",
"description": "Options for self-hosting\n[See more](https://github.com/kamilkisiela/graphql-hive/tree/main/packages/libraries/client#self-hosting)"
},
"experimental__persistedDocuments": {
"$ref": "#/definitions/HivePersistedDocumentsConfiguration",
"description": "Experimental persisted documents configuration\n[See more](https://the-guild.dev/graphql/hive/docs/features/app-deployments#persisted-documents-on-graphql-server-and-gateway)"
}
},
"required": ["token"]
}
},
"HiveAgentOptions": {
"additionalProperties": false,
Expand Down Expand Up @@ -2198,6 +2201,42 @@
},
"required": ["graphqlEndpoint", "applicationUrl"]
},
"HivePersistedDocumentsConfiguration": {
"additionalProperties": false,
"type": "object",
"title": "HivePersistedDocumentsConfiguration",
"properties": {
"cdn": {
"$ref": "#/definitions/HivePersistedDocumentsConfigurationCDN",
"description": "Point to your own instance of GraphQL Hive API\n\nUsed by schema reporting and token info."
},
"allowArbitraryDocuments": {
"type": "boolean",
"description": "Whether arbitrary documents should be allowed along-side persisted documents. false by default"
},
"cache": {
"type": "integer",
"description": "Maximum amount of operations that shall be kept in memory after being loaded from the CDN. 10 seconds by default"
}
},
"required": ["cdn"]
},
"HivePersistedDocumentsConfigurationCDN": {
"additionalProperties": false,
"type": "object",
"title": "HivePersistedDocumentsConfigurationCDN",
"properties": {
"endpoint": {
"type": "string",
"description": "CDN endpoint"
},
"accessToken": {
"type": "string",
"description": "Access Token for Persisted Documents CDN"
}
},
"required": ["endpoint", "accessToken"]
},
"HTTPCachePlugin": {
"additionalProperties": false,
"type": "object",
Expand Down
35 changes: 33 additions & 2 deletions packages/legacy/types/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1874,13 +1874,14 @@ export interface HivePlugin {
*/
enabled?: boolean | string;
/**
* Access Token
* Access Token for Usage Reporting
*/
token: string;
token?: string;
agent?: HiveAgentOptions;
usage?: HiveUsageOptions;
reporting?: HiveReportingOptions;
selfHosting?: HiveSelfHostingOptions;
experimental__persistedDocuments?: HivePersistedDocumentsConfiguration;
}
/**
* Agent Options
Expand Down Expand Up @@ -1998,6 +1999,36 @@ export interface HiveSelfHostingOptions {
*/
usageEndpoint?: string;
}
/**
* Experimental persisted documents configuration
* [See more](https://the-guild.dev/graphql/hive/docs/features/app-deployments#persisted-documents-on-graphql-server-and-gateway)
*/
export interface HivePersistedDocumentsConfiguration {
cdn: HivePersistedDocumentsConfigurationCDN;
/**
* Whether arbitrary documents should be allowed along-side persisted documents. false by default
*/
allowArbitraryDocuments?: boolean;
/**
* Maximum amount of operations that shall be kept in memory after being loaded from the CDN. 10 seconds by default
*/
cache?: number;
}
/**
* Point to your own instance of GraphQL Hive API
*
* Used by schema reporting and token info.
*/
export interface HivePersistedDocumentsConfigurationCDN {
/**
* CDN endpoint
*/
endpoint: string;
/**
* Access Token for Persisted Documents CDN
*/
accessToken: string;
}
export interface HTTPCachePlugin {
/**
* If the following patterns match the request URL, the response will be cached. (Any of: String, URLPatternObj)
Expand Down
21 changes: 14 additions & 7 deletions packages/plugins/hive/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,21 @@ export default function useMeshHive<TContext>(
: true;

if (!enabled) {
pluginOptions.logger?.warn('Reporting is disabled');
pluginOptions.logger?.warn('Plugin is disabled');
return {};
}

const token = stringInterpolator.parse(pluginOptions.token, {
env: process.env,
});
if (!token) {
pluginOptions.logger?.warn('Reporting is disabled because the "token" was not provided');
return {};
if (token) {
pluginOptions.logger?.info('Reporting enabled');
}

pluginOptions.logger?.info('Reporting enabled');
const persistedDocuments = pluginOptions.experimental__persistedDocuments;
if (persistedDocuments) {
pluginOptions.logger?.info('Persisted documents enabled');
}

let usage: HivePluginOptions['usage'] = true;
if (pluginOptions.usage) {
Expand Down Expand Up @@ -105,15 +107,20 @@ export default function useMeshHive<TContext>(
};
}
const hiveClient = createHive({
enabled: true,
debug: !!process.env.DEBUG,
enabled:
// eslint-disable-next-line no-unneeded-ternary -- for brevity
persistedDocuments && !token
? false // disable usage reporting if just persisted documents are configured
: true,
debug: ['1', 't', 'true', 'y', 'yes'].includes(process.env.DEBUG),
token,
agent,
usage,
reporting,
selfHosting,
// Mesh already disposes the client below on Mesh's `destroy` event
autoDispose: false,
experimental__persistedDocuments: persistedDocuments,
});
// TODO: Remove later after v0
// Pubsub.destroy will no longer
Expand Down
37 changes: 35 additions & 2 deletions packages/plugins/hive/yaml-config.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ type HivePlugin @md {
"""
enabled: BooleanOrString
"""
Access Token
Access Token for Usage Reporting
"""
token: String!
token: String
"""
Agent Options
"""
Expand All @@ -29,6 +29,11 @@ type HivePlugin @md {
[See more](https://github.com/kamilkisiela/graphql-hive/tree/main/packages/libraries/client#self-hosting)
"""
selfHosting: HiveSelfHostingOptions
"""
Experimental persisted documents configuration
[See more](https://the-guild.dev/graphql/hive/docs/features/app-deployments#persisted-documents-on-graphql-server-and-gateway)
"""
experimental__persistedDocuments: HivePersistedDocumentsConfiguration
}

type HiveAgentOptions {
Expand Down Expand Up @@ -138,3 +143,31 @@ type HiveSelfHostingOptions {
"""
usageEndpoint: String
}

type HivePersistedDocumentsConfiguration {
"""
Point to your own instance of GraphQL Hive API
Used by schema reporting and token info.
"""
cdn: HivePersistedDocumentsConfigurationCDN!
"""
Whether arbitrary documents should be allowed along-side persisted documents. false by default
"""
allowArbitraryDocuments: Boolean
"""
Maximum amount of operations that shall be kept in memory after being loaded from the CDN. 10 seconds by default
"""
cache: Int
}

type HivePersistedDocumentsConfigurationCDN {
"""
CDN endpoint
"""
endpoint: String!
"""
Access Token for Persisted Documents CDN
"""
accessToken: String!
}
15 changes: 10 additions & 5 deletions packages/serve-cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,14 @@ import cluster from 'node:cluster';
import { availableParallelism, release } from 'node:os';
import parseDuration from 'parse-duration';
import { Command, InvalidArgumentError, Option } from '@commander-js/extra-typings';
import type {
MeshServeConfigProxy,
MeshServeConfigSubgraph,
MeshServeConfigSupergraph,
} from '@graphql-mesh/serve-runtime';
import type { MeshServeConfigProxy, MeshServeConfigSubgraph, MeshServeConfigSupergraph } from '@graphql-mesh/serve-runtime';
import type { Logger } from '@graphql-mesh/types';
import { DefaultLogger } from '@graphql-mesh/utils';
import { addCommands } from './commands/index.js';
import { defaultConfigPaths } from './config.js';
import type { ServerConfig } from './server';


export type MeshServeCLIConfig = (
| MeshServeCLISupergraphConfig
| MeshServeCLISubgraphConfig
Expand Down Expand Up @@ -179,6 +176,14 @@ let cli = new Command()
'Hive registry token for usage metrics reporting',
).env('HIVE_REGISTRY_TOKEN'),
)
.option(
'--hive-persisted-documents-endpoint <endpoint>',
'[EXPERIMENTAL] Hive CDN endpoint for fetching the persisted documents. requires the "--hive-persisted-documents-token <token>" option',
)
.option(
'--hive-persisted-documents-token <token>',
'[EXPERIMENTAL] Hive persisted documents CDN endpoint. requires the "--hive-persisted-documents-endpoint <endpoint>" option',
)
.addOption(
new Option(
'--apollo-graph-ref <graphRef>',
Expand Down
22 changes: 20 additions & 2 deletions packages/serve-cli/src/commands/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,16 @@ export const addCommand: AddCommand = (ctx, cli) =>
).env('HIVE_CDN_KEY'),
)
.action(async function proxy(endpoint) {
const { hiveCdnKey, hiveRegistryToken, maskedErrors, polling, nativeImport, ...opts } =
this.optsWithGlobals<CLIGlobals>();
const {
hiveCdnKey,
hiveRegistryToken,
maskedErrors,
polling,
nativeImport,
hivePersistedDocumentsEndpoint,
hivePersistedDocumentsToken,
...opts
} = this.optsWithGlobals<CLIGlobals>();
const loadedConfig = await loadConfig({
log: ctx.log,
configPath: opts.configPath,
Expand Down Expand Up @@ -87,6 +95,16 @@ export const addCommand: AddCommand = (ctx, cli) =>
}
: {}),
...(polling ? { pollingInterval: polling } : {}),
...(hivePersistedDocumentsEndpoint
? {
persistedDocuments: {
type: 'hive',
endpoint:
hivePersistedDocumentsEndpoint || loadedConfig.persistedDocuments?.endpoint,
token: hivePersistedDocumentsToken || loadedConfig.persistedDocuments?.token,
},
}
: {}),
proxy,
schema,
logging: loadedConfig.logging ?? ctx.log,
Expand Down
Loading

0 comments on commit db41f96

Please sign in to comment.