-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
api-runner-node.js
383 lines (344 loc) · 12.2 KB
/
api-runner-node.js
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
const Promise = require(`bluebird`)
const _ = require(`lodash`)
const chalk = require(`chalk`)
const tracer = require(`opentracing`).globalTracer()
const reporter = require(`./create-reporter`)
const getCache = require(`./get-cache`)
const apiList = require(`./api-node-docs`)
const createNodeId = require(`./create-node-id`)
const createContentDigest = require(`./create-content-digest`)
const {
buildObjectType,
buildUnionType,
buildInterfaceType,
buildInputObjectType,
} = require(`../schema/types/type-builders`)
const { emitter } = require(`../redux`)
const { getNonGatsbyCodeFrame } = require(`./stack-trace-utils`)
const { trackBuildError, decorateEvent } = require(`gatsby-telemetry`)
const { store } = require(`../redux`)
const { actions } = require(`../redux/actions`)
const { stripIndent } = require(`common-tags`)
const { dispatch } = store
const { log } = actions
// Bind action creators per plugin so we can auto-add
// metadata to actions they create.
const boundPluginActionCreators = {}
const doubleBind = (boundActionCreators, api, plugin, actionOptions) => {
const { traceId } = actionOptions
if (boundPluginActionCreators[plugin.name + api + traceId]) {
return boundPluginActionCreators[plugin.name + api + traceId]
} else {
const keys = Object.keys(boundActionCreators)
const doubleBoundActionCreators = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const boundActionCreator = boundActionCreators[key]
if (typeof boundActionCreator === `function`) {
doubleBoundActionCreators[key] = (...args) => {
// Let action callers override who the plugin is. Shouldn't be
// used that often.
if (args.length === 1) {
return boundActionCreator(args[0], plugin, actionOptions)
} else if (args.length === 2) {
return boundActionCreator(args[0], args[1], actionOptions)
}
return undefined // Lint
}
}
}
boundPluginActionCreators[
plugin.name + api + traceId
] = doubleBoundActionCreators
return doubleBoundActionCreators
}
}
const initAPICallTracing = parentSpan => {
const startSpan = (spanName, spanArgs = {}) => {
const defaultSpanArgs = { childOf: parentSpan }
return tracer.startSpan(spanName, _.merge(defaultSpanArgs, spanArgs))
}
return {
tracer,
parentSpan,
startSpan,
}
}
const runAPI = (plugin, api, args) => {
const gatsbyNode = require(`${plugin.resolve}/gatsby-node`)
if (gatsbyNode[api]) {
const parentSpan = args && args.parentSpan
const spanOptions = parentSpan ? { childOf: parentSpan } : {}
const pluginSpan = tracer.startSpan(`run-plugin`, spanOptions)
pluginSpan.setTag(`api`, api)
pluginSpan.setTag(`plugin`, plugin.name)
let pathPrefix = ``
const { store, emitter } = require(`../redux`)
const {
loadNodeContent,
getNodes,
getNode,
getNodesByType,
hasNodeChanged,
getNodeAndSavePathDependency,
} = require(`../db/nodes`)
const { boundActionCreators } = require(`../redux/actions`)
const doubleBoundActionCreators = doubleBind(
boundActionCreators,
api,
plugin,
{ ...args, parentSpan: pluginSpan }
)
if (store.getState().program.prefixPaths) {
pathPrefix = store.getState().config.pathPrefix
}
const namespacedCreateNodeId = id => createNodeId(id, plugin.name)
const tracing = initAPICallTracing(pluginSpan)
const cache = getCache(plugin.name)
// Ideally this would be more abstracted and applied to more situations, but right now
// this can be potentially breaking so targeting `createPages` API and `createPage` action
let actions = doubleBoundActionCreators
let apiFinished = false
if (api === `createPages`) {
let alreadyDisplayed = false
const createPageAction = actions.createPage
// create new actions object with wrapped createPage action
// doubleBoundActionCreators is memoized, so we can't just
// reassign createPage field as this would cause this extra logic
// to be used in subsequent APIs and we only want to target this `createPages` call.
actions = {
...actions,
createPage: (...args) => {
createPageAction(...args)
if (apiFinished && !alreadyDisplayed) {
const warning = [
stripIndent(`
Action ${chalk.bold(
`createPage`
)} was called outside of its expected asynchronous lifecycle ${chalk.bold(
`createPages`
)} in ${chalk.bold(plugin.name)}.
Ensure that you return a Promise from ${chalk.bold(
`createPages`
)} and are awaiting any asynchronous method invocations (like ${chalk.bold(
`graphql`
)} or http requests).
For more info and debugging tips: see ${chalk.bold(
`https://gatsby.dev/sync-actions`
)}
`),
]
const possiblyCodeFrame = getNonGatsbyCodeFrame()
if (possiblyCodeFrame) {
warning.push(possiblyCodeFrame)
}
const message = warning.join(`\n\n`)
dispatch(log({ message, type: `warn` }))
alreadyDisplayed = true
}
},
}
}
const apiCallArgs = [
{
...args,
pathPrefix,
boundActionCreators: actions,
actions,
loadNodeContent,
store,
emitter,
getCache,
getNodes,
getNode,
getNodesByType,
hasNodeChanged,
reporter,
getNodeAndSavePathDependency,
cache,
createNodeId: namespacedCreateNodeId,
createContentDigest,
tracing,
schema: {
buildObjectType,
buildUnionType,
buildInterfaceType,
buildInputObjectType,
},
},
plugin.pluginOptions,
]
// If the plugin is using a callback use that otherwise
// expect a Promise to be returned.
if (gatsbyNode[api].length === 3) {
return Promise.fromCallback(callback => {
const cb = (err, val) => {
pluginSpan.finish()
callback(err, val)
apiFinished = true
}
try {
gatsbyNode[api](...apiCallArgs, cb)
} catch (e) {
trackBuildError(api, {
error: e,
pluginName: `${plugin.name}@${plugin.version}`,
})
throw e
}
})
} else {
const result = gatsbyNode[api](...apiCallArgs)
pluginSpan.finish()
return Promise.resolve(result).then(res => {
apiFinished = true
return res
})
}
}
return null
}
let apisRunningById = new Map()
let apisRunningByTraceId = new Map()
let waitingForCasacadeToFinish = []
module.exports = async (api, args = {}, pluginSource) =>
new Promise(resolve => {
const { parentSpan } = args
const apiSpanArgs = parentSpan ? { childOf: parentSpan } : {}
const apiSpan = tracer.startSpan(`run-api`, apiSpanArgs)
apiSpan.setTag(`api`, api)
_.forEach(args.traceTags, (value, key) => {
apiSpan.setTag(key, value)
})
// Check that the API is documented.
// "FAKE_API_CALL" is used when code needs to trigger something
// to happen once the the API queue is empty. Ideally of course
// we'd have an API (returning a promise) for that. But this
// works nicely in the meantime.
if (!apiList[api] && api !== `FAKE_API_CALL`) {
const message = `api: "${api}" is not a valid Gatsby api`
dispatch(log({ message, type: `panic` }))
}
const { store } = require(`../redux`)
const plugins = store.getState().flattenedPlugins
// Get the list of plugins that implement this API.
// Also: Break infinite loops. Sometimes a plugin will implement an API and
// call an action which will trigger the same API being called.
// `onCreatePage` is the only example right now. In these cases, we should
// avoid calling the originating plugin again.
const implementingPlugins = plugins.filter(
plugin => plugin.nodeAPIs.includes(api) && plugin.name !== pluginSource
)
const apiRunInstance = {
api,
args,
pluginSource,
resolve,
span: apiSpan,
startTime: new Date().toJSON(),
traceId: args.traceId,
}
// Generate IDs for api runs. Most IDs we generate from the args
// but some API calls can have very large argument objects so we
// have special ways of generating IDs for those to avoid stringifying
// large objects.
let id
if (api === `setFieldsOnGraphQLNodeType`) {
id = `${api}${apiRunInstance.startTime}${args.type.name}${args.traceId}`
} else if (api === `onCreateNode`) {
id = `${api}${apiRunInstance.startTime}${
args.node.internal.contentDigest
}${args.traceId}`
} else if (api === `preprocessSource`) {
id = `${api}${apiRunInstance.startTime}${args.filename}${args.traceId}`
} else if (api === `onCreatePage`) {
id = `${api}${apiRunInstance.startTime}${args.page.path}${args.traceId}`
} else {
// When tracing is turned on, the `args` object will have a
// `parentSpan` field that can be quite large. So we omit it
// before calling stringify
const argsJson = JSON.stringify(_.omit(args, `parentSpan`))
id = `${api}|${apiRunInstance.startTime}|${
apiRunInstance.traceId
}|${argsJson}`
}
apiRunInstance.id = id
if (args.waitForCascadingActions) {
waitingForCasacadeToFinish.push(apiRunInstance)
}
apisRunningById.set(apiRunInstance.id, apiRunInstance)
if (apisRunningByTraceId.has(apiRunInstance.traceId)) {
const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
apisRunningByTraceId.set(apiRunInstance.traceId, currentCount + 1)
} else {
apisRunningByTraceId.set(apiRunInstance.traceId, 1)
}
let stopQueuedApiRuns = false
let onAPIRunComplete = null
if (api === `onCreatePage`) {
const path = args.page.path
const actionHandler = action => {
if (action.payload.path === path) {
stopQueuedApiRuns = true
}
}
emitter.on(`DELETE_PAGE`, actionHandler)
onAPIRunComplete = () => {
emitter.off(`DELETE_PAGE`, actionHandler)
}
}
Promise.mapSeries(implementingPlugins, plugin => {
if (stopQueuedApiRuns) {
return null
}
let pluginName =
plugin.name === `default-site-plugin`
? `gatsby-node.js`
: `Plugin ${plugin.name}`
return new Promise(resolve => {
resolve(runAPI(plugin, api, { ...args, parentSpan: apiSpan }))
}).catch(err => {
decorateEvent(`BUILD_PANIC`, {
pluginName: `${plugin.name}@${plugin.version}`,
})
const message = `${pluginName} returned an error ` + err
dispatch(log({ message, type: `panicOnBuild` }))
return null
})
}).then(results => {
if (onAPIRunComplete) {
onAPIRunComplete()
}
// Remove runner instance
apisRunningById.delete(apiRunInstance.id)
const currentCount = apisRunningByTraceId.get(apiRunInstance.traceId)
apisRunningByTraceId.set(apiRunInstance.traceId, currentCount - 1)
if (apisRunningById.size === 0) {
const { emitter } = require(`../redux`)
emitter.emit(`API_RUNNING_QUEUE_EMPTY`)
}
// Filter empty results
apiRunInstance.results = results.filter(result => !_.isEmpty(result))
// Filter out empty responses and return if the
// api caller isn't waiting for cascading actions to finish.
if (!args.waitForCascadingActions) {
apiSpan.finish()
resolve(apiRunInstance.results)
}
// Check if any of our waiters are done.
waitingForCasacadeToFinish = waitingForCasacadeToFinish.filter(
instance => {
// If none of its trace IDs are running, it's done.
const apisByTraceIdCount = apisRunningByTraceId.get(instance.traceId)
if (apisByTraceIdCount === 0) {
instance.span.finish()
instance.resolve(instance.results)
return false
} else {
return true
}
}
)
return
})
})