/
api-runner-node.js
766 lines (667 loc) · 22.6 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
const Promise = require(`bluebird`)
const _ = require(`lodash`)
const chalk = require(`chalk`)
const { bindActionCreators: origBindActionCreators } = require(`redux`)
const memoize = require(`memoizee`)
const bindActionCreators = memoize(origBindActionCreators)
const tracer = require(`opentracing`).globalTracer()
const reporter = require(`gatsby-cli/lib/reporter`)
const stackTrace = require(`stack-trace`)
const { codeFrameColumns } = require(`@babel/code-frame`)
const fs = require(`fs-extra`)
const { getCache } = require(`./get-cache`)
import { createNodeId } from "./create-node-id"
const {
createContentDigest: _createContentDigest,
} = require(`gatsby-core-utils`)
import {
buildObjectType,
buildUnionType,
buildInterfaceType,
buildInputObjectType,
buildEnumType,
buildScalarType,
} from "../schema/types/type-builders"
const { emitter, store } = require(`../redux`)
const { getNodes, getNode, getNodesByType } = require(`../datastore`)
const { getNodeAndSavePathDependency, loadNodeContent } = require(`./nodes`)
const { getPublicPath } = require(`./get-public-path`)
const { importGatsbyPlugin } = require(`./import-gatsby-plugin`)
const { getNonGatsbyCodeFrameFormatted } = require(`./stack-trace-utils`)
const { trackBuildError, decorateEvent } = require(`gatsby-telemetry`)
import errorParser from "./api-runner-error-parser"
import { wrapNode, wrapNodes } from "./detect-node-mutations"
import { reportOnce } from "./report-once"
// Override createContentDigest to remove autogenerated data from nodes to
// ensure consistent digests.
function createContentDigest(node) {
if (!node?.internal?.type) {
// this doesn't look like a node, so let's just pass it as-is
return _createContentDigest(node)
}
return _createContentDigest({
...node,
internal: {
...node.internal,
// Remove auto-generated fields that'd prevent
// creating a consistent contentDigest.
contentDigest: undefined,
owner: undefined,
fieldOwners: undefined,
ignoreType: undefined,
counter: undefined,
},
fields: undefined,
})
}
if (!process.env.BLUEBIRD_DEBUG && !process.env.BLUEBIRD_LONG_STACK_TRACES) {
// Unless specified - disable longStackTraces
// as this have severe perf penalty ( http://bluebirdjs.com/docs/api/promise.longstacktraces.html )
// This is mainly for `gatsby develop` due to NODE_ENV being set to development
// which cause bluebird to enable longStackTraces
// `gatsby build` (with NODE_ENV=production) already doesn't enable longStackTraces
Promise.config({ longStackTraces: false })
}
const nodeMutationsWrappers = {
getNode(id) {
return wrapNode(getNode(id))
},
getNodes() {
return wrapNodes(getNodes())
},
getNodesByType(type) {
return wrapNodes(getNodesByType(type))
},
getNodeAndSavePathDependency(id) {
return wrapNode(getNodeAndSavePathDependency(id))
},
}
// 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, deferNodeMutation } = actionOptions
const defer = deferNodeMutation ? `defer-node-mutation` : ``
const actionKey = plugin.name + api + traceId + defer
if (boundPluginActionCreators[actionKey]) {
return boundPluginActionCreators[actionKey]
} 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) => {
if (args.length === 0) {
return boundActionCreator(plugin, actionOptions)
}
// Let action callers override who the plugin is. Shouldn't be
// used that often.
else if (args.length === 1) {
return boundActionCreator(args[0], plugin, actionOptions)
} else if (args.length === 2) {
return boundActionCreator(args[0], args[1], actionOptions)
}
reportOnce(
`Unhandled redux action: ${key}, in plugin: ${plugin.name}`
)
return undefined
}
}
}
boundPluginActionCreators[actionKey] = 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 deferredAction =
type =>
(...args) => {
// Regular createNode returns a Promise, but when deferred we need
// to wrap it in another which we resolve when it's actually called
if (type === `createNode`) {
return new Promise(resolve => {
emitter.emit(`ENQUEUE_NODE_MUTATION`, {
type,
payload: args,
resolve,
})
})
}
return emitter.emit(`ENQUEUE_NODE_MUTATION`, {
type,
payload: args,
})
}
const NODE_MUTATION_ACTIONS = [
`createNode`,
`deleteNode`,
`touchNode`,
`createParentChildLink`,
`createNodeField`,
]
const deferActions = actions => {
const deferred = { ...actions }
NODE_MUTATION_ACTIONS.forEach(action => {
deferred[action] = deferredAction(action)
})
return deferred
}
/**
* Create a local reporter
* Used to override reporter methods with activity methods
*/
function getLocalReporter({ activity, reporter }) {
// If we have an activity, bind panicOnBuild to the activities method to
// join them
if (activity) {
return { ...reporter, panicOnBuild: activity.panicOnBuild.bind(activity) }
}
return reporter
}
function getErrorMapWithPluginName(pluginName, errorMap) {
const entries = Object.entries(errorMap)
return entries.reduce((memo, [key, val]) => {
memo[`${pluginName}_${key}`] = val
return memo
}, {})
}
function extendLocalReporterToCatchPluginErrors({
reporter,
pluginName,
runningActivities,
}) {
let setErrorMap
let error = reporter.error
let panic = reporter.panic
let panicOnBuild = reporter.panicOnBuild
if (pluginName && reporter?.setErrorMap) {
setErrorMap = errorMap =>
reporter.setErrorMap(getErrorMapWithPluginName(pluginName, errorMap))
error = (errorMeta, error) => {
reporter.error(errorMeta, error, pluginName)
}
panic = (errorMeta, error) => {
reporter.panic(errorMeta, error, pluginName)
}
panicOnBuild = (errorMeta, error) => {
reporter.panicOnBuild(errorMeta, error, pluginName)
}
}
return {
...reporter,
setErrorMap,
error,
panic,
panicOnBuild,
// If you change arguments here, update reporter.ts as well
activityTimer: (text, activityArgs = {}) => {
let args = [text, activityArgs]
if (pluginName && setErrorMap) {
args = [...args, pluginName]
}
// eslint-disable-next-line prefer-spread
const activity = reporter.activityTimer.apply(reporter, args)
const originalStart = activity.start
const originalEnd = activity.end
activity.start = () => {
originalStart.apply(activity)
runningActivities.add(activity)
}
activity.end = () => {
originalEnd.apply(activity)
runningActivities.delete(activity)
}
return activity
},
// If you change arguments here, update reporter.ts as well
createProgress: (text, total = 0, start = 0, activityArgs = {}) => {
let args = [text, total, start, activityArgs]
if (pluginName && setErrorMap) {
args = [...args, pluginName]
}
// eslint-disable-next-line prefer-spread
const activity = reporter.createProgress.apply(reporter, args)
const originalStart = activity.start
const originalEnd = activity.end
const originalDone = activity.done
activity.start = () => {
originalStart.apply(activity)
runningActivities.add(activity)
}
activity.end = () => {
originalEnd.apply(activity)
runningActivities.delete(activity)
}
activity.done = () => {
originalDone.apply(activity)
runningActivities.delete(activity)
}
return activity
},
}
}
const getUninitializedCache = plugin => {
const message =
`Usage of "cache" instance in "onPreInit" API is not supported as ` +
`this API runs before cache initialization` +
(plugin && plugin !== `default-site-plugin` ? ` (called in ${plugin})` : ``)
return {
// GatsbyCache
async get() {
throw new Error(message)
},
async set() {
throw new Error(message)
},
async del() {
throw new Error(message)
},
}
}
const availableActionsCache = new Map()
let publicPath
const runAPI = async (plugin, api, args, activity) => {
const gatsbyNode = await importGatsbyPlugin(plugin, `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)
const {
publicActions,
restrictedActionsAvailableInAPI,
} = require(`../redux/actions`)
let availableActions
if (availableActionsCache.has(api)) {
availableActions = availableActionsCache.get(api)
} else {
availableActions = {
...publicActions,
...(restrictedActionsAvailableInAPI[api] || {}),
}
availableActionsCache.set(api, availableActions)
}
let boundActionCreators = bindActionCreators(
availableActions,
store.dispatch
)
if (args.deferNodeMutation) {
boundActionCreators = deferActions(boundActionCreators)
}
const doubleBoundActionCreators = doubleBind(
boundActionCreators,
api,
plugin,
{ ...args, parentSpan: pluginSpan, activity }
)
const { config, program } = store.getState()
const pathPrefix = (program.prefixPaths && config.pathPrefix) || ``
if (typeof publicPath === `undefined`) {
publicPath = getPublicPath({ ...config, ...program }, ``)
}
const namespacedCreateNodeId = id => createNodeId(id, plugin.name)
const tracing = initAPICallTracing(pluginSpan)
// See https://github.com/gatsbyjs/gatsby/issues/11369
const cache =
api === `onPreInit`
? getUninitializedCache(plugin.name)
: 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 = [
reporter.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 = getNonGatsbyCodeFrameFormatted()
if (possiblyCodeFrame) {
warning.push(possiblyCodeFrame)
}
reporter.warn(warning.join(`\n\n`))
alreadyDisplayed = true
}
},
}
}
const localReporter = getLocalReporter({ activity, reporter })
const runningActivities = new Set()
const extendedLocalReporter = extendLocalReporterToCatchPluginErrors({
reporter: localReporter,
pluginName: plugin.name,
runningActivities,
})
const endInProgressActivitiesCreatedByThisRun = () => {
runningActivities.forEach(activity => activity.end())
}
const shouldDetectNodeMutations = [
`sourceNodes`,
`onCreateNode`,
`createResolvers`,
`createSchemaCustomization`,
`setFieldsOnGraphQLNodeType`,
].includes(api)
const apiCallArgs = [
{
...args,
parentSpan: pluginSpan,
basePath: pathPrefix,
pathPrefix: publicPath,
actions,
loadNodeContent,
store,
emitter,
getCache,
getNodes: shouldDetectNodeMutations
? nodeMutationsWrappers.getNodes
: getNodes,
getNode: shouldDetectNodeMutations
? nodeMutationsWrappers.getNode
: getNode,
getNodesByType: shouldDetectNodeMutations
? nodeMutationsWrappers.getNodesByType
: getNodesByType,
reporter: extendedLocalReporter,
getNodeAndSavePathDependency: shouldDetectNodeMutations
? nodeMutationsWrappers.getNodeAndSavePathDependency
: getNodeAndSavePathDependency,
cache,
createNodeId: namespacedCreateNodeId,
createContentDigest,
tracing,
schema: {
buildObjectType,
buildUnionType,
buildInterfaceType,
buildInputObjectType,
buildEnumType,
buildScalarType,
},
},
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()
apiFinished = true
endInProgressActivitiesCreatedByThisRun()
callback(err, val)
}
try {
gatsbyNode[api](...apiCallArgs, cb)
} catch (e) {
trackBuildError(api, {
error: e,
pluginName: `${plugin.name}@${plugin.version}`,
})
throw e
}
})
} else {
try {
return await gatsbyNode[api](...apiCallArgs)
} finally {
pluginSpan.finish()
apiFinished = true
endInProgressActivitiesCreatedByThisRun()
}
}
}
return null
}
const apisRunningById = new Map()
const apisRunningByTraceId = new Map()
let waitingForCasacadeToFinish = []
function apiRunnerNode(api, args = {}, { pluginSource, activity } = {}) {
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.
let implementingPlugins = plugins.filter(
plugin => plugin.nodeAPIs.includes(api) && plugin.name !== pluginSource
)
if (api === `sourceNodes` && args.pluginName) {
implementingPlugins = implementingPlugins.filter(
plugin => plugin.name === args.pluginName
)
}
// If there's no implementing plugins, return early.
if (implementingPlugins.length === 0) {
return null
}
return new Promise(resolve => {
const { parentSpan, traceId, traceTags, waitForCascadingActions } = args
const apiSpanArgs = parentSpan ? { childOf: parentSpan } : {}
const apiSpan = tracer.startSpan(`run-api`, apiSpanArgs)
apiSpan.setTag(`api`, api)
_.forEach(traceTags, (value, key) => {
apiSpan.setTag(key, value)
})
const apiRunInstance = {
api,
args,
pluginSource,
resolve,
span: apiSpan,
startTime: new Date().toJSON(),
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}${traceId}`
} else if (api === `onCreateNode`) {
id = `${api}${apiRunInstance.startTime}${args.node.internal.contentDigest}${traceId}`
} else if (api === `preprocessSource`) {
id = `${api}${apiRunInstance.startTime}${args.filename}${traceId}`
} else if (api === `onCreatePage`) {
id = `${api}${apiRunInstance.startTime}${args.page.path}${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 (waitForCascadingActions) {
waitingForCasacadeToFinish.push(apiRunInstance)
}
if (apisRunningById.size === 0) {
emitter.emit(`API_RUNNING_START`)
}
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)
}
}
let apiRunPromiseOptions = {}
let runPromise
if (
api === `sourceNodes` &&
process.env.GATSBY_EXPERIMENTAL_PARALLEL_SOURCING
) {
runPromise = Promise.map
apiRunPromiseOptions.concurrency = 20
} else {
runPromise = Promise.mapSeries
apiRunPromiseOptions = undefined
}
runPromise(
implementingPlugins,
plugin => {
if (stopQueuedApiRuns) {
return null
}
return importGatsbyPlugin(plugin, `gatsby-node`).then(gatsbyNode => {
const pluginName =
plugin.name === `default-site-plugin`
? `gatsby-node.js`
: plugin.name
// TODO: rethink createNode API to handle this better
if (
api === `onCreateNode` &&
gatsbyNode?.shouldOnCreateNode && // Don't bail if this api is not exported
!gatsbyNode.shouldOnCreateNode(
{ node: args.node },
plugin.pluginOptions
)
) {
// Do not try to schedule an async event for this node for this plugin
return null
}
return new Promise(resolve => {
resolve(
runAPI(plugin, api, { ...args, parentSpan: apiSpan }, activity)
)
}).catch(err => {
decorateEvent(`BUILD_PANIC`, {
pluginName: `${plugin.name}@${plugin.version}`,
})
const localReporter = getLocalReporter({ activity, reporter })
const file = stackTrace
.parse(err)
.find(file => /gatsby-node/.test(file.fileName))
let codeFrame = ``
const structuredError = errorParser({ err })
if (file) {
const { fileName, lineNumber: line, columnNumber: column } = file
const trimmedFileName = fileName.match(/^(async )?(.*)/)[2]
try {
const code = fs.readFileSync(trimmedFileName, {
encoding: `utf-8`,
})
codeFrame = codeFrameColumns(
code,
{
start: {
line,
column,
},
},
{
highlightCode: true,
}
)
} catch (_e) {
// sometimes stack trace point to not existing file
// particularly when file is transpiled and path actually changes
// (like pointing to not existing `src` dir or original typescript file)
}
structuredError.location = {
start: { line: line, column: column },
}
structuredError.filePath = fileName
}
structuredError.context = {
...structuredError.context,
pluginName,
api,
codeFrame,
}
localReporter.panicOnBuild(structuredError)
return null
})
})
},
apiRunPromiseOptions
).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) {
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 (!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
})
})
}
module.exports = apiRunnerNode