@graphql-hive/gateway
Version:
377 lines (372 loc) • 15.5 kB
TypeScript
import { Command } from '@commander-js/extra-typings';
import { GatewayConfigContext, GatewayConfigSupergraph, GatewayHiveReportingOptions, GatewayGraphOSReportingOptions, GatewayConfigSubgraph, GatewayConfigProxy, GatewayPlugin } from '@graphql-hive/gateway-runtime';
export * from '@graphql-hive/gateway-runtime';
import { Logger } from '@graphql-hive/logger';
export * from '@graphql-hive/logger';
import { AWSSignv4PluginOptions } from '@graphql-hive/plugin-aws-sigv4';
import { OpenTelemetryGatewayPluginOptions } from '@graphql-hive/plugin-opentelemetry';
import { PubSub } from '@graphql-hive/pubsub';
export * from '@graphql-hive/pubsub';
import UpstashRedisCache from '@graphql-mesh/cache-upstash-redis';
export { default as UpstashRedisCache } from '@graphql-mesh/cache-upstash-redis';
import { JWTAuthPluginOptions } from '@graphql-mesh/plugin-jwt-auth';
export * from '@graphql-mesh/plugin-jwt-auth';
import { PrometheusPluginOptions } from '@graphql-mesh/plugin-prometheus';
export * from '@graphql-mesh/plugin-prometheus';
export { default as usePrometheus } from '@graphql-mesh/plugin-prometheus';
import { YamlConfig, KeyValueCache } from '@graphql-mesh/types';
import { GraphiQLRenderer } from 'graphql-yoga';
export * from '@graphql-hive/pubsub/nats';
export * from '@graphql-hive/pubsub/redis';
export { default as useRateLimit } from '@graphql-mesh/plugin-rate-limit';
export { default as useHttpCache } from '@graphql-mesh/plugin-http-cache';
export { default as useSnapshot } from '@graphql-mesh/plugin-snapshot';
export { default as CloudflareKVCacheStorage } from '@graphql-mesh/cache-cfw-kv';
export { default as RedisCacheStorage } from '@graphql-mesh/cache-redis';
export { default as LocalForageCacheStorage } from '@graphql-mesh/cache-localforage';
export { default as WSTransport, WSTransportOptions } from '@graphql-mesh/transport-ws';
export { default as HTTPCallbackTransport, HTTPCallbackTransportOptions } from '@graphql-mesh/transport-http-callback';
export { default as HTTPTransport, HTTPTransportOptions } from '@graphql-mesh/transport-http';
interface ServerConfig {
/**
* Host to listen on.
*
* @default '127.0.0.1' on Windows, otherwise '0.0.0.0'
*/
host?: string;
/**
* Port to listen on.
*
* @default 4000
*/
port?: number;
/**
* SSL Credentials for the HTTPS Server.
*
* If this is provided, Gateway will be over secure HTTPS instead of unsecure HTTP.
*/
sslCredentials?: ServerConfigSSLCredentials;
/**
* The size of the HTTP headers to allow
*
* @default 16384
*/
maxHeaderSize?: number;
/**
* Whether to disable setting up a WebSocket server.
*
* @default false
*/
disableWebsockets?: boolean;
/**
* Sets the maximum time in milliseconds allowed to receive the
* _entire_ request from the client (headers + body). It does not limit
* the total duration of the request lifecycle - once the body is fully
* received, this timer is cancelled and your handler can run indefinitely.
*
* For a hard end-to-end deadline, use {@link requestDeadline} instead.
*
* @default 300000 (5 minutes)
*/
requestTimeout?: number;
/**
* Sets a hard end-to-end time limit in milliseconds for the
* entire request lifecycle — from connection to response completion.
*
* Unlike {@link requestTimeout}, this timer is NOT cancelled when the body
* is received; it runs until the response is finished or the socket
* is destroyed.
*
* WARNING: in Bun, streamed responses (e.g. defer/stream) are not covered by
* this deadline. The timer only applies until the Response object is created;
* once streaming begins, the body can continue past the deadline.
*/
requestDeadline?: number;
/**
* Sets the number of milliseconds to wait before timing out a
* connection due to inactivity in Node's HTTP server
*
* This setting has no effect in Bun, use {@link requestTimeout} instead.
*
* @default "Node's default (5 seconds)"
*/
keepAliveTimeout?: number;
}
interface ServerConfigSSLCredentials {
key_file_name?: string;
cert_file_name?: string;
ca_file_name?: string;
passphrase?: string;
dh_params_file_name?: string;
ssl_ciphers?: string;
ssl_prefer_low_memory_usage?: boolean;
}
type GatewayCLIConfig<TContext extends Record<string, any> = Record<string, any>> = (GatewayCLISupergraphConfig<TContext> | GatewayCLISubgraphConfig<TContext> | GatewayCLIProxyConfig<TContext>) & ServerConfig & {
/**
* Count of workers to spawn.
*/
fork?: number;
/**
* GraphQL schema polling interval in milliseconds.
*
* If cache is provided in the config, the {@link supergraph} will be cached setting the TTL to this interval in seconds.
*
* @default 10_000
*/
pollingInterval?: number;
/**
* Whether to render the legacy GraphiQL interface.
*
* @default false
*/
renderLegacyGraphiQL?: boolean;
} & GatewayCLIBuiltinPluginConfig;
interface GatewayCLISupergraphConfig<TContext extends Record<string, any> = Record<string, any>> extends Omit<GatewayConfigSupergraph<TContext>, 'supergraph' | 'cache' | 'reporting'> {
/**
* SDL, path or an URL to the Federation Supergraph.
*
* Alternatively, CDN options for pulling a remote Federation Supergraph.
*
* @default 'supergraph.graphql'
*/
supergraph?: GatewayConfigSupergraph<TContext>['supergraph'];
/** Usage reporting options. */
reporting?: GatewayCLIHiveReportingOptions | GatewayGraphOSReportingOptions;
}
interface GatewayCLIHiveReportingOptions extends Omit<GatewayHiveReportingOptions, 'target' | 'token'> {
/**
* The target to which the usage data should be reported to.
*
* @default env.HIVE_USAGE_TARGET
*/
target?: GatewayHiveReportingOptions['target'];
/**
* Hive registry access token for usage metrics reporting.
*
* @default env.HIVE_USAGE_ACCESS_TOKEN || env.HIVE_REGISTRY_TOKEN
*/
token?: GatewayHiveReportingOptions['token'];
}
interface GatewayCLISubgraphConfig<TContext extends Record<string, any> = Record<string, any>> extends Omit<GatewayConfigSubgraph<TContext>, 'subgraph' | 'cache'> {
/**
* SDL, path or an URL to the Federation Supergraph.
*
* Alternatively, CDN options for pulling a remote Federation Supergraph.
*
* @default 'subgraph.graphql'
*/
subgraph?: GatewayConfigSubgraph<TContext>['subgraph'];
}
interface GatewayCLIProxyConfig<TContext extends Record<string, any> = Record<string, any>> extends Omit<GatewayConfigProxy<TContext>, 'proxy' | 'cache'> {
/**
* HTTP executor to proxy all incoming requests to another HTTP endpoint.
*/
proxy?: GatewayConfigProxy<TContext>['proxy'];
}
type KeyValueCacheFactoryFn = (ctx: {
log: Logger;
pubsub: PubSub;
cwd: string;
}) => KeyValueCache;
interface GatewayCLIBuiltinPluginConfig {
/**
* Configure JWT Auth
*
* @see https://graphql-hive.com/docs/gateway/authorization-authentication
*/
jwt?: JWTAuthPluginOptions;
/**
* Configure Prometheus metrics
*
* @see https://graphql-hive.com/docs/gateway/monitoring-tracing
*/
prometheus?: Exclude<PrometheusPluginOptions, GatewayConfigContext>;
/**
* Configure OpenTelemetry
*
* @see https://graphql-hive.com/docs/gateway/monitoring-tracing
*/
openTelemetry?: Exclude<OpenTelemetryGatewayPluginOptions, GatewayConfigContext>;
/**
* Configure Rate Limiting
*
* @see https://graphql-hive.com/docs/gateway/other-features/security/rate-limiting
*/
rateLimiting?: boolean | YamlConfig.RateLimitPluginConfig['config'] | YamlConfig.RateLimitPluginConfig;
/**
* Enable and configure AWS Sigv4 signing
*/
awsSigv4?: AWSSignv4PluginOptions;
/**
* Enable Just-In-Time compilation of GraphQL documents.
*
* @see https://github.com/zalando-incubator/graphql-jit?tab=readme-ov-file#benchmarks
*/
jit?: boolean;
cache?: KeyValueCache | KeyValueCacheFactoryFn | GatewayCLILocalforageCacheConfig | GatewayCLIRedisCacheConfig | GatewayCLICloudflareKVCacheConfig | GatewayCLIUpstashRedisCacheConfig;
/**
* Limit the number of tokens in a GraphQL document.
*
* Passing `true` will enable the feature with the default limit of `1000` tokens.
*
* If you would like more configuration options, please disable this feature and
* use the [`@escape.tech/graphql-armor-max-tokens` plugin](https://escape.tech/graphql-armor/docs/plugins/max-tokens/#with-envelopcore-from-the-guild-org) instead.
*
* @default false
*/
maxTokens?: boolean | number;
/**
* Limit the depth of a GraphQL document.
*
* Passing `true` will enable the feature with the default limit of `6` levels.
*
* If you would like more configuration options, please disable this feature and
* use the [`@escape.tech/graphql-armor-max-depth` plugin](https://escape.tech/graphql-armor/docs/plugins/max-depth/#with-envelopcore-from-the-guild-org) instead
*
* @default false
*/
maxDepth?: boolean | number;
/**
* Prevent returning field suggestions and leaking your schema to unauthorized actors.
*
* If you would like more configuration options, please disable this feature and
* use the [`@escape.tech/graphql-armor-block-field-suggestions` plugin](https://escape.tech/graphql-armor/docs/plugins/block-field-suggestions/#with-envelopcore-from-the-guild-org) instead
*
* @default false
*/
blockFieldSuggestions?: boolean;
}
type GatewayCLILocalforageCacheConfig = YamlConfig.LocalforageConfig & {
type: 'localforage';
};
type GatewayCLIRedisCacheConfig = (YamlConfig.RedisConfigSingle | YamlConfig.RedisConfigSentinel) & {
type: 'redis';
};
type GatewayCLICloudflareKVCacheConfig = YamlConfig.CFWorkersKVCacheConfig & {
type: 'cfw-kv';
};
type GatewayCLIUpstashRedisCacheConfig = {
type: 'upstash-redis';
} & ConstructorParameters<typeof UpstashRedisCache>[0];
/**
* Type helper for defining the config.
*/
declare function defineConfig<TContext extends Record<string, any> = Record<string, any>>(config: GatewayCLIConfig<TContext>): GatewayCLIConfig<TContext>;
/** The context of the running program. */
interface CLIContext {
/** @default new DefaultLogger() */
log: Logger;
/** @default 'Hive Gateway' */
productName: string;
/** @default 'Unify and accelerate your data graph across diverse services with Hive Gateway, which seamlessly integrates with Apollo Federation.' */
productDescription: string;
/** @default '@graphql-hive/gateway' */
productPackageName: string;
/** @default 'Hive Gateway logo' */
productLogo?: string;
/** @default https://the-guild.dev/graphql/hive/docs/gateway */
productLink: string;
/** @default 'hive-gateway' */
/**
* A safe binary executable name, should not contain any special
* characters or white-spaces.
*
* @default 'hive-gateway'
*/
binName: string;
/** @default 'gateway.config' */
configFileName: string;
/** @default globalThis.__VERSION__ */
version: string;
}
/** Inferred program options from the root command {@link cli}. */
type CLIGlobals = CLI extends Command<any, infer O> ? O : never;
type CLI = typeof cli;
type AddCommand = (ctx: CLIContext, cli: CLI) => void;
declare const defaultOptions: {
fork: number;
host: string;
port: number;
pollingInterval: number;
renderGraphiQL: GraphiQLRenderer;
playgroundName: string;
};
/** Root cli for the gateway. */
declare let cli: Command<[], {
fork?: number | undefined;
configPath?: string | undefined;
host?: string | undefined;
port?: number | undefined;
polling?: number | undefined;
renderLegacyGraphiql?: true | undefined;
maskedErrors: string | boolean | string[] | [];
opentelemetry?: string | true | undefined;
opentelemetryExporterType: "otlp-http" | "otlp-grpc";
hiveRegistryToken?: string | undefined;
hiveUsageTarget?: string | undefined;
hiveTarget?: string | undefined;
hiveAccessToken?: string | undefined;
hiveUsageAccessToken?: string | undefined;
hiveTraceAccessToken?: string | undefined;
hiveTraceEndpoint: string;
hivePersistedDocumentsEndpoint?: string | undefined;
hivePersistedDocumentsToken?: string | undefined;
hivePersistedDocumentsCacheTtl?: number | undefined;
hivePersistedDocumentsCacheNotFoundTtl?: number | undefined;
hiveCdnEndpoint?: string | undefined;
hiveCdnKey?: string | undefined;
apolloGraphRef?: string | undefined;
apolloKey?: string | undefined;
disableWebsockets?: true | undefined;
jit?: true | undefined;
}, {}>;
declare function run(userCtx: Partial<CLIContext>): Promise<Command<[], {
fork?: number | undefined;
configPath?: string | undefined;
host?: string | undefined;
port?: number | undefined;
polling?: number | undefined;
renderLegacyGraphiql?: true | undefined;
maskedErrors: string | boolean | string[] | [];
opentelemetry?: string | true | undefined;
opentelemetryExporterType: "otlp-http" | "otlp-grpc";
hiveRegistryToken?: string | undefined;
hiveUsageTarget?: string | undefined;
hiveTarget?: string | undefined;
hiveAccessToken?: string | undefined;
hiveUsageAccessToken?: string | undefined;
hiveTraceAccessToken?: string | undefined;
hiveTraceEndpoint: string;
hivePersistedDocumentsEndpoint?: string | undefined;
hivePersistedDocumentsToken?: string | undefined;
hivePersistedDocumentsCacheTtl?: number | undefined;
hivePersistedDocumentsCacheNotFoundTtl?: number | undefined;
hiveCdnEndpoint?: string | undefined;
hiveCdnKey?: string | undefined;
apolloGraphRef?: string | undefined;
apolloKey?: string | undefined;
disableWebsockets?: true | undefined;
jit?: true | undefined;
}, {}>>;
declare function handleNodeWarnings(): void;
declare function enableModuleCachingIfPossible(): void;
/**
* This is an internal API and might have breaking changes in the future.
* So use it with caution.
*/
declare function getBuiltinPluginsFromConfig(config: GatewayCLIBuiltinPluginConfig, ctx: {
cache: KeyValueCache;
log: Logger;
pubsub: PubSub;
cwd: string;
}): Promise<GatewayPlugin[]>;
/**
* This is an internal API and might have breaking changes in the future.
* So use it with caution.
*/
declare function getCacheInstanceFromConfig(config: GatewayCLIBuiltinPluginConfig, ctx: {
log: Logger;
pubsub: PubSub;
cwd: string;
}): Promise<KeyValueCache>;
export { type AddCommand, type CLI, type CLIContext, type CLIGlobals, type GatewayCLIBuiltinPluginConfig, type GatewayCLICloudflareKVCacheConfig, type GatewayCLIConfig, type GatewayCLIHiveReportingOptions, type GatewayCLILocalforageCacheConfig, type GatewayCLIProxyConfig, type GatewayCLIRedisCacheConfig, type GatewayCLISubgraphConfig, type GatewayCLISupergraphConfig, type GatewayCLIUpstashRedisCacheConfig, type KeyValueCacheFactoryFn, defaultOptions, defineConfig, enableModuleCachingIfPossible, getBuiltinPluginsFromConfig, getCacheInstanceFromConfig, handleNodeWarnings, run };