-
Notifications
You must be signed in to change notification settings - Fork 242
/
IntrospectAndCompose.ts
172 lines (156 loc) 路 5.01 KB
/
IntrospectAndCompose.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import {
composeAndValidate,
compositionHasErrors,
ServiceDefinition,
} from '@apollo/federation';
import { Logger } from 'apollo-server-types';
import CallableInstance from 'callable-instance';
import { HeadersInit } from 'node-fetch';
import {
GraphQLDataSource,
RemoteGraphQLDataSource,
ServiceEndpointDefinition,
SupergraphSdlHook,
SupergraphSdlUpdateFunction,
} from '..';
import {
getServiceDefinitionsFromRemoteEndpoint,
Service,
} from '../loadServicesFromRemoteEndpoint';
import { waitUntil } from '../utilities/waitUntil';
export interface IntrospectAndComposeOptions {
serviceList: ServiceEndpointDefinition[];
introspectionHeaders?:
| HeadersInit
| ((
service: ServiceEndpointDefinition,
) => Promise<HeadersInit> | HeadersInit);
buildService?: (definition: ServiceEndpointDefinition) => GraphQLDataSource;
pollIntervalInMs?: number;
logger?: Logger;
}
type State =
| { phase: 'initialized' }
| { phase: 'polling'; pollingPromise?: Promise<void> }
| { phase: 'stopped' };
export class IntrospectAndCompose extends CallableInstance<
Parameters<SupergraphSdlHook>,
ReturnType<SupergraphSdlHook>
> {
private update?: SupergraphSdlUpdateFunction;
private serviceList: Service[];
private introspectionHeaders?:
| HeadersInit
| ((
service: ServiceEndpointDefinition,
) => Promise<HeadersInit> | HeadersInit);
private buildService?: (
definition: ServiceEndpointDefinition,
) => GraphQLDataSource;
private serviceSdlCache: Map<string, string> = new Map();
private pollIntervalInMs?: number;
private timerRef: NodeJS.Timeout | null = null;
private state: State;
private logger?: Logger;
constructor(options: IntrospectAndComposeOptions) {
super('instanceCallableMethod');
// this.buildService needs to be assigned before this.serviceList is built
this.buildService = options.buildService;
this.pollIntervalInMs = options.pollIntervalInMs;
this.serviceList = options.serviceList.map((serviceDefinition) => ({
...serviceDefinition,
dataSource: this.createDataSource(serviceDefinition),
}));
this.introspectionHeaders = options.introspectionHeaders;
this.logger = options.logger;
this.state = { phase: 'initialized' };
}
// @ts-ignore noUsedLocals
private async instanceCallableMethod(
...[{ update }]: Parameters<SupergraphSdlHook>
) {
this.update = update;
const initialSupergraphSdl = await this.updateSupergraphSdl();
// Start polling after we resolve the first supergraph
if (this.pollIntervalInMs) {
this.beginPolling();
}
return {
supergraphSdl: initialSupergraphSdl,
cleanup: async () => {
if (this.state.phase === 'polling') {
await this.state.pollingPromise;
}
this.state = { phase: 'stopped' };
if (this.timerRef) {
this.timerRef.unref();
clearInterval(this.timerRef);
this.timerRef = null;
}
},
};
}
private async updateSupergraphSdl() {
const result = await getServiceDefinitionsFromRemoteEndpoint({
serviceList: this.serviceList,
getServiceIntrospectionHeaders: async (service) => {
return typeof this.introspectionHeaders === 'function'
? await this.introspectionHeaders(service)
: this.introspectionHeaders;
},
serviceSdlCache: this.serviceSdlCache,
});
if (!result.isNewSchema) {
return null;
}
return this.createSupergraphFromServiceList(result.serviceDefinitions!);
}
private createDataSource(
serviceDef: ServiceEndpointDefinition,
): GraphQLDataSource {
return (
this.buildService?.(serviceDef) ??
new RemoteGraphQLDataSource({
url: serviceDef.url,
})
);
}
private createSupergraphFromServiceList(serviceList: ServiceDefinition[]) {
const compositionResult = composeAndValidate(serviceList);
if (compositionHasErrors(compositionResult)) {
const { errors } = compositionResult;
throw Error(
"A valid schema couldn't be composed. The following composition errors were found:\n" +
errors.map((e) => '\t' + e.message).join('\n'),
);
} else {
const { supergraphSdl } = compositionResult;
return supergraphSdl;
}
}
private beginPolling() {
this.state = { phase: 'polling' };
this.poll();
}
private poll() {
this.timerRef = setTimeout(async () => {
if (this.state.phase === 'polling') {
const [pollingPromise, donePolling] = waitUntil();
this.state.pollingPromise = pollingPromise;
try {
const maybeNewSupergraphSdl = await this.updateSupergraphSdl();
if (maybeNewSupergraphSdl) {
this.update?.(maybeNewSupergraphSdl);
}
} catch (e) {
this.logger?.error(
'IntrospectAndCompose failed to update supergraph with the following error: ' +
(e.message ?? e),
);
}
donePolling!();
}
this.poll();
}, this.pollIntervalInMs!);
}
}