|
| 1 | +/** |
| 2 | + * @module fetch_p |
| 3 | + */ |
| 4 | + |
| 5 | +/** |
| 6 | + * This module patches the global fetch instance for NodeJS 18+ |
| 7 | + */ |
| 8 | +const AWSXRay = require('aws-xray-sdk-core'); |
| 9 | +const utils = AWSXRay.utils; |
| 10 | +const getLogger = AWSXRay.getLogger; |
| 11 | +require('./subsegment_fetch'); |
| 12 | + |
| 13 | +/** |
| 14 | + * Wrap fetch global instance for recent NodeJS to automatically capture information for the segment. |
| 15 | + * This patches the built-in fetch function globally. |
| 16 | + * @param {boolean} downstreamXRayEnabled - when true, adds a "traced:true" property to the subsegment |
| 17 | + * so the AWS X-Ray service expects a corresponding segment from the downstream service. |
| 18 | + * @param {function} subsegmentCallback - a callback that is called with the subsegment, the fetch request, |
| 19 | + * the fetch response and any error issued, allowing custom annotations and metadata to be added. |
| 20 | + * @alias module:fetch_p.captureFetchGlobal |
| 21 | + */ |
| 22 | +function captureFetchGlobal(downstreamXRayEnabled, subsegmentCallback) { |
| 23 | + if (globalThis.fetch === undefined) { |
| 24 | + throw new Error('Global fetch is not available in NodeJS'); |
| 25 | + } |
| 26 | + if (!globalThis.__fetch) { |
| 27 | + globalThis.__fetch = globalThis.fetch; |
| 28 | + globalThis.fetch = enableCapture(globalThis.__fetch, globalThis.Request, |
| 29 | + downstreamXRayEnabled, subsegmentCallback); |
| 30 | + } |
| 31 | + return globalThis.fetch; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Wrap fetch module to capture information for the segment. |
| 36 | + * This patches the fetch function distributed in node-fetch package. |
| 37 | + * @param {fetch} module - The fetch module |
| 38 | + * @param {boolean} downstreamXRayEnabled - when true, adds a "traced:true" property to the subsegment |
| 39 | + * so the AWS X-Ray service expects a corresponding segment from the downstream service. |
| 40 | + * @param {function} subsegmentCallback - a callback that is called with the subsegment, the fetch request, |
| 41 | + * the fetch response and any error issued, allowing custom annotations and metadata to be added. |
| 42 | + * @alias module:fetch_p.captureFetchModule |
| 43 | + */ |
| 44 | +function captureFetchModule(module, downstreamXRayEnabled, subsegmentCallback) { |
| 45 | + if (!module.default) { |
| 46 | + getLogger().warn('X-ray capture did not find fetch function in module'); |
| 47 | + return null; |
| 48 | + } |
| 49 | + if (!module.__fetch) { |
| 50 | + module.__fetch = module.default; |
| 51 | + module.default = enableCapture(module.__fetch, module.Request, |
| 52 | + downstreamXRayEnabled, subsegmentCallback); |
| 53 | + } |
| 54 | + return module.default; |
| 55 | +} |
| 56 | + |
| 57 | +const enableCapture = function enableCapture(baseFetchFunction, requestClass, downstreamXRayEnabled, subsegmentCallback) { |
| 58 | + |
| 59 | + const overridenFetchAsync = async (...args) => { |
| 60 | + const thisDownstreamXRayEnabled = !!downstreamXRayEnabled; |
| 61 | + const thisSubsegmentCallback = subsegmentCallback; |
| 62 | + // Standardize request information |
| 63 | + const request = typeof args[0] === 'object' ? |
| 64 | + args[0] : |
| 65 | + new requestClass(...args); |
| 66 | + |
| 67 | + // Facilitate the addition of Segment information via the request arguments |
| 68 | + const params = args.length > 1 ? args[1] : {}; |
| 69 | + |
| 70 | + // Short circuit if the HTTP is already being captured |
| 71 | + if (request.headers.has('X-Amzn-Trace-Id')) { |
| 72 | + return await baseFetchFunction(...args); |
| 73 | + } |
| 74 | + |
| 75 | + const url = new URL(request.url); |
| 76 | + const isAutomaticMode = AWSXRay.isAutomaticMode(); |
| 77 | + |
| 78 | + const parent = AWSXRay.resolveSegment(AWSXRay.resolveManualSegmentParams(params)); |
| 79 | + const hostname = url.hostname || url.host || 'Unknown host'; |
| 80 | + |
| 81 | + if (!parent) { |
| 82 | + let output = '[ host: ' + hostname + |
| 83 | + (request.method ? (', method: ' + request.method) : '') + |
| 84 | + ', path: ' + url.pathname + ' ]'; |
| 85 | + |
| 86 | + if (isAutomaticMode) { |
| 87 | + getLogger().info('RequestInit for request ' + output + |
| 88 | + ' is missing the sub/segment context for automatic mode. Ignoring.'); |
| 89 | + } else { |
| 90 | + getLogger().info('RequestInit for request ' + output + |
| 91 | + ' requires a segment object on the options params as "XRaySegment" for tracing in manual mode. Ignoring.'); |
| 92 | + } |
| 93 | + |
| 94 | + // Options are not modified, only parsed for logging. We can pass in the original arguments. |
| 95 | + return await baseFetchFunction(...args); |
| 96 | + } |
| 97 | + |
| 98 | + let subsegment; |
| 99 | + if (parent.notTraced) { |
| 100 | + subsegment = parent.addNewSubsegmentWithoutSampling(hostname); |
| 101 | + } else { |
| 102 | + subsegment = parent.addNewSubsegment(hostname); |
| 103 | + } |
| 104 | + |
| 105 | + subsegment.namespace = 'remote'; |
| 106 | + |
| 107 | + request.headers.set('X-Amzn-Trace-Id', |
| 108 | + 'Root=' + (parent.segment ? parent.segment : parent).trace_id + |
| 109 | + ';Parent=' + subsegment.id + |
| 110 | + ';Sampled=' + (subsegment.notTraced ? '0' : '1')); |
| 111 | + |
| 112 | + // Set up fetch call and capture any thrown errors |
| 113 | + const capturedFetch = async () => { |
| 114 | + const requestClone = request.clone(); |
| 115 | + let response; |
| 116 | + try { |
| 117 | + response = await baseFetchFunction(requestClone); |
| 118 | + |
| 119 | + if (thisSubsegmentCallback) { |
| 120 | + thisSubsegmentCallback(subsegment, requestClone, response); |
| 121 | + } |
| 122 | + |
| 123 | + const statusCode = response.status; |
| 124 | + if (statusCode === 429) { |
| 125 | + subsegment.addThrottleFlag(); |
| 126 | + } |
| 127 | + |
| 128 | + const cause = utils.getCauseTypeFromHttpStatus(statusCode); |
| 129 | + if (cause) { |
| 130 | + subsegment[cause] = true; |
| 131 | + } |
| 132 | + |
| 133 | + subsegment.addFetchRequestData(requestClone, response, thisDownstreamXRayEnabled); |
| 134 | + subsegment.close(); |
| 135 | + return response; |
| 136 | + } catch (e) { |
| 137 | + if (thisSubsegmentCallback) { |
| 138 | + thisSubsegmentCallback(subsegment, requestClone, response, e); |
| 139 | + } |
| 140 | + const madeItToDownstream = (e.code !== 'ECONNREFUSED'); |
| 141 | + subsegment.addErrorFlag(); |
| 142 | + subsegment.addFetchRequestData(requestClone, response, madeItToDownstream && thisDownstreamXRayEnabled); |
| 143 | + subsegment.close(e); |
| 144 | + throw (e); |
| 145 | + } |
| 146 | + }; |
| 147 | + |
| 148 | + if (isAutomaticMode) { |
| 149 | + const session = AWSXRay.getNamespace(); |
| 150 | + return await session.runPromise(async () => { |
| 151 | + AWSXRay.setSegment(subsegment); |
| 152 | + return await capturedFetch(); |
| 153 | + }); |
| 154 | + } else { |
| 155 | + return await capturedFetch(); |
| 156 | + } |
| 157 | + }; |
| 158 | + |
| 159 | + return overridenFetchAsync; |
| 160 | +}; |
| 161 | + |
| 162 | +module.exports.captureFetchGlobal = captureFetchGlobal; |
| 163 | +module.exports.captureFetchModule = captureFetchModule; |
| 164 | +module.exports._fetchEnableCapture = enableCapture; |
0 commit comments