UNPKG

@graphql-hive/router-runtime

Version:
263 lines (254 loc) 11 kB
import { UnifiedGraphHandlerOpts, UnifiedGraphHandlerResult, UnifiedGraphPlugin, Instrumentation as Instrumentation$2 } from '@graphql-mesh/fusion-runtime'; import { DisposableSymbols } from '@whatwg-node/disposablestack'; import { MaybePromise } from '@whatwg-node/promise-helpers'; import { Plugin, YogaInitialContext, Instrumentation as Instrumentation$1 } from 'graphql-yoga'; import { MeshFetch, KeyValueCache, MeshFetchRequestInit, Logger as Logger$1 } from '@graphql-mesh/types'; import { FetchInstrumentation } from '@graphql-mesh/utils'; import { ExecutionRequest, MaybePromise as MaybePromise$1 } from '@graphql-tools/utils'; import { GraphQLResolveInfo } from 'graphql/type'; import { QueryPlan } from '@graphql-hive/router-query-planner'; declare function unifiedGraphHandler(opts: UnifiedGraphHandlerOpts): UnifiedGraphHandlerResult; type MaybeLazy<T> = T | (() => T); type AttributeValue = any; type Attributes = AttributeValue[] | { [key: string | number]: AttributeValue; }; interface LogWriter { write(level: LogLevel, attrs: Attributes | null | undefined, msg: string | null | undefined): void | Promise<void>; flush?(): void | Promise<void>; } type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error'; interface LoggerOptions { /** * The minimum log level to log. * * Providing `false` will disable all logging. * * Provided function will always be invoked to get the current log level. * * @default env.LOG_LEVEL || env.DEBUG ? 'debug' : 'info' */ level?: MaybeLazy<LogLevel | false>; /** A prefix to include in every log's message. */ prefix?: string; /** * The attributes to include in all logs. Is mainly used to pass the parent * attributes when creating {@link Logger.child child loggers}. */ attrs?: Attributes; /** * The log writers to use when writing logs. * * @default env.LOG_JSON ? [new JSONLogWriter()] : [new ConsoleLogWriter()] */ writers?: [LogWriter, ...LogWriter[]]; } declare class Logger implements AsyncDisposable { #private; constructor(opts?: LoggerOptions); /** The prefix that's prepended to each log message. */ get prefix(): string | undefined; /** * The attributes that are added to each log. If the log itself contains * attributes with keys existing in {@link attrs}, the log's attributes will * override. */ get attrs(): Attributes | undefined; /** The current {@link LogLevel} of the logger. You can change the level using the {@link setLevel} method. */ get level(): false | LogLevel; /** * Sets the new {@link LogLevel} of the logger. All subsequent logs, and {@link child child loggers} whose * level did not change, will respect the new level. */ setLevel(level: MaybeLazy<LogLevel | false>): void; write(level: LogLevel, attrs: Attributes | null | undefined, msg: string | null | undefined): void; flush(): Promise<void> | undefined; [DisposableSymbols.asyncDispose](): Promise<void | undefined>; child(prefix: string): Logger; child(attrs: Attributes, prefix?: string): Logger; log(level: LogLevel): void; log(level: LogLevel, attrs: MaybeLazy<Attributes>): void; log(level: LogLevel, msg: string, ...interpol: unknown[]): void; log(level: LogLevel, attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; trace(): void; trace(attrs: MaybeLazy<Attributes>): void; trace(msg: string, ...interpol: unknown[]): void; trace(attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; debug(): void; debug(attrs: MaybeLazy<Attributes>): void; debug(msg: string, ...interpol: unknown[]): void; debug(attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; info(): void; info(attrs: MaybeLazy<Attributes>): void; info(msg: string, ...interpol: unknown[]): void; info(attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; warn(): void; warn(attrs: MaybeLazy<Attributes>): void; warn(msg: string, ...interpol: unknown[]): void; warn(attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; error(): void; error(attrs: MaybeLazy<Attributes>): void; error(msg: string, ...interpol: unknown[]): void; error(attrs: MaybeLazy<Attributes>, msg: string, ...interpol: unknown[]): void; } type TopicDataMap = { [topic: string]: any; }; type PubSubListener<Data extends TopicDataMap, Topic extends keyof Data> = (data: Data[Topic]) => void; interface PubSub<M extends TopicDataMap = TopicDataMap> { /** * Publish {@link data} for a {@link topic}. * @returns `void` or a `Promise` that resolves when the data has been successfully published */ publish<Topic extends keyof M>(topic: Topic, data: M[Topic]): MaybePromise<void>; /** * A distinct list of all topics that are currently subscribed to. * Can be a promise to accomodate distributed systems where subscribers exist on other * locations and we need to know about all of them. */ subscribedTopics(): MaybePromise<Iterable<keyof M>>; /** * Subscribe and listen to a {@link topic} receiving its data. * * If the {@link listener} is provided, it will be called whenever data is emitted for the {@link topic}, * * @returns an unsubscribe function or a `Promise<unsubscribe function>` that resolves when the subscription is successfully established. the unsubscribe function returns `void` or a `Promise` that resolves on successful unsubscribe and subscription cleanup * * If the {@link listener} is not provided, * * @returns an `AsyncIterable` that yields data for the given {@link topic} */ subscribe<Topic extends keyof M>(topic: Topic): AsyncIterable<M[Topic]>; subscribe<Topic extends keyof M>(topic: Topic, listener: PubSubListener<M, Topic>): MaybePromise<() => MaybePromise<void>>; /** * Closes active subscriptions and disposes of all resources. Publishing and subscribing after disposal * is not possible and will throw an error if attempted. */ dispose(): MaybePromise<void>; /** @see {@link dispose} */ [DisposableSymbols.asyncDispose](): Promise<void>; } interface GatewayConfigContext { /** * WHATWG compatible Fetch implementation. */ fetch: MeshFetch; /** * The logger to use throught Hive and its plugins. */ log: Logger; /** * Current working directory. * Note that working directory does not exist in serverless environments and will therefore be empty. */ cwd: string; /** * Event bus for pub/sub. */ pubsub?: PubSub; /** * Cache Storage */ cache?: KeyValueCache; } interface GatewayContext extends GatewayConfigContext, YogaInitialContext { /** * Environment agnostic HTTP headers provided with the request. */ headers: Record<string, string>; /** * Runtime context available within WebSocket connections. */ connectionParams?: Record<string, string>; } type GatewayPlugin<TPluginContext extends Record<string, any> = Record<string, any>, TContext extends Record<string, any> = Record<string, any>> = Plugin<Partial<TPluginContext> & GatewayContext & TContext, GatewayConfigContext> & UnifiedGraphPlugin<Partial<TPluginContext> & GatewayContext & TContext> & { onFetch?: OnFetchHook<Partial<TPluginContext> & TContext>; onCacheGet?: OnCacheGetHook; onCacheSet?: OnCacheSetHook; onCacheDelete?: OnCacheDeleteHook; /** * An Instrumentation instance that will wrap each phases of the request pipeline. * This should be used primarily as an observability tool (for monitoring, tracing, etc...). * * Note: The wrapped functions in instrumentation should always be called. Use hooks to * conditionally skip a phase. */ instrumentation?: Instrumentation<TPluginContext & TContext & GatewayContext>; }; interface OnFetchHookPayload<TContext> { url: string; setURL(url: URL | string): void; options: MeshFetchRequestInit; setOptions(options: MeshFetchRequestInit): void; /** * The context is not available in cases where "fetch" is done in * order to pull a supergraph or do some internal work. * * The logger will be available in all cases. */ context: (GatewayContext & TContext) | { log: Logger; }; /** @deprecated Please use `log` from the {@link context} instead. */ logger: Logger$1; info: GraphQLResolveInfo; fetchFn: MeshFetch; setFetchFn: (fetchFn: MeshFetch) => void; executionRequest?: ExecutionRequest; endResponse: (response$: MaybePromise$1<Response>) => void; } interface OnFetchHookDonePayload { response: Response; setResponse: (response: Response) => void; } type OnFetchHookDone = (payload: OnFetchHookDonePayload) => MaybePromise$1<void>; type OnFetchHook<TContext> = (payload: OnFetchHookPayload<TContext>) => MaybePromise$1<void | OnFetchHookDone>; type OnCacheGetHook = (payload: OnCacheGetHookEventPayload) => MaybePromise$1<OnCacheGetHookResult | void>; interface OnCacheGetHookEventPayload { cache: KeyValueCache; key: string; ttl?: number; } interface OnCacheGetHookResult { onCacheHit?: OnCacheHitHook; onCacheMiss?: OnCacheMissHook; onCacheGetError?: OnCacheErrorHook; } type OnCacheErrorHook = (payload: OnCacheErrorHookPayload) => void; interface OnCacheErrorHookPayload { error: Error; } type OnCacheHitHook = (payload: OnCacheHitHookEventPayload) => void; interface OnCacheHitHookEventPayload { value: any; } type OnCacheMissHook = () => void; type OnCacheSetHook = (payload: OnCacheSetHookEventPayload) => MaybePromise$1<OnCacheSetHookResult | void>; interface OnCacheSetHookResult { onCacheSetDone?: () => void; onCacheSetError?: OnCacheErrorHook; } interface OnCacheSetHookEventPayload { cache: KeyValueCache; key: string; value: any; ttl?: number; } type OnCacheDeleteHook = (payload: OnCacheDeleteHookEventPayload) => MaybePromise$1<OnCacheDeleteHookResult | void>; interface OnCacheDeleteHookResult { onCacheDeleteDone?: () => void; onCacheDeleteError?: OnCacheErrorHook; } interface OnCacheDeleteHookEventPayload { cache: KeyValueCache; key: string; } type Instrumentation<TContext extends Record<string, any>> = Instrumentation$1<TContext> & Instrumentation$2 & FetchInstrumentation; interface QueryPlanOptions { /** Callback when the query plan has been successfuly generated. */ onQueryPlan?(queryPlan: QueryPlan): void; /** Exposing the query plan inside the GraphQL result extensions. */ expose?: boolean | ((request: Request) => boolean); } declare function useQueryPlan(opts?: QueryPlanOptions): GatewayPlugin; export { type QueryPlanOptions, unifiedGraphHandler, useQueryPlan };