Skip to content

Commit 99484ce

Browse files
authored
refactor: Updated instances in instrumentation of Array.forEach for a more performant for...of or for index loop (#3463)
1 parent f804940 commit 99484ce

File tree

22 files changed

+145
-152
lines changed

22 files changed

+145
-152
lines changed

lib/instrumentation-tracker.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,9 @@ class InstrumentationTracker {
211211
default: {
212212
// Add the same name to all found instrumentations. This definitely
213213
// happens when the security agent is enabled.
214-
missingResolvedName.forEach((item) => {
214+
for (const item of missingResolvedName) {
215215
item.instrumentation.resolvedName = resolvedName
216-
})
216+
}
217217
}
218218
}
219219
}

lib/instrumentation/@google/genai.js

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ function addLlmMeta({ agent, transaction }) {
5757
*
5858
* @param {object} params input params
5959
* @param {Agent} params.agent NR agent instance
60-
* @param {Shim} params.shim the current shim instance
6160
* @param {TraceSegment} params.segment active segment from chat completion
6261
* @param {object} params.request chat completion params
6362
* @param {object} params.response chat completion response
@@ -66,7 +65,6 @@ function addLlmMeta({ agent, transaction }) {
6665
*/
6766
function recordChatCompletionMessages({
6867
agent,
69-
shim,
7068
segment,
7169
request,
7270
response,
@@ -97,20 +95,21 @@ function recordChatCompletionMessages({
9795
const inputMessages = Array.isArray(request.contents) ? request.contents : [request.contents]
9896
const responseMessage = response?.candidates?.[0]?.content
9997
const messages = responseMessage !== undefined ? [...inputMessages, responseMessage] : inputMessages
100-
messages.forEach((message, index) => {
98+
for (let i = 0; i < messages.length; i++) {
99+
const message = messages[i]
101100
const completionMsg = new LlmChatCompletionMessage({
102101
agent,
103102
segment,
104103
transaction,
105104
request,
106105
response,
107-
index,
106+
index: i,
108107
completionId: completionSummary.id,
109108
message
110109
})
111110

112111
recordEvent({ agent, type: 'LlmChatCompletionMessage', msg: completionMsg })
113-
})
112+
}
114113

115114
recordEvent({ agent, type: 'LlmChatCompletionSummary', msg: completionSummary })
116115

@@ -120,7 +119,7 @@ function recordChatCompletionMessages({
120119
}
121120
}
122121

123-
function instrumentStream ({ agent, shim, request, response, segment, transaction }) {
122+
function instrumentStream ({ shim, request, response, segment, transaction }) {
124123
let err
125124
let content
126125
let modelVersion
@@ -167,7 +166,6 @@ function instrumentStream ({ agent, shim, request, response, segment, transactio
167166

168167
recordChatCompletionMessages({
169168
agent: shim.agent,
170-
shim,
171169
segment,
172170
transaction,
173171
request,
@@ -208,7 +206,6 @@ module.exports = function initialize(agent, googleGenAi, moduleName, shim) {
208206
after({ error: err, result: response, segment, transaction }) {
209207
recordChatCompletionMessages({
210208
agent,
211-
shim,
212209
segment,
213210
transaction,
214211
request,
@@ -241,7 +238,7 @@ module.exports = function initialize(agent, googleGenAi, moduleName, shim) {
241238
name: GEMINI.COMPLETION,
242239
promise: true,
243240
after({ result: response, segment, transaction }) {
244-
instrumentStream({ agent, shim, request, response, segment, transaction })
241+
instrumentStream({ shim, request, response, segment, transaction })
245242
addLlmMeta({ agent, transaction })
246243
}
247244
})

lib/instrumentation/aws-sdk/v3/bedrock.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,8 @@ function recordChatCompletionMessages({
138138

139139
// Record context message(s)
140140
const promptContextMessages = bedrockCommand.prompt
141-
promptContextMessages.forEach((contextMessage, promptIndex) => {
141+
for (let i = 0; i < promptContextMessages.length; i++) {
142+
const contextMessage = promptContextMessages[i]
142143
const msg = new LlmChatCompletionMessage({
143144
agent,
144145
segment,
@@ -147,27 +148,28 @@ function recordChatCompletionMessages({
147148
content: contextMessage.content,
148149
role: contextMessage.role,
149150
bedrockResponse,
150-
index: promptIndex,
151+
index: i,
151152
completionId: summary.id
152153
})
153154
recordEvent({ agent, type: 'LlmChatCompletionMessage', msg })
154-
})
155+
}
155156

156-
bedrockResponse.completions.forEach((content, completionIndex) => {
157+
for (let i = 0; i < bedrockResponse.completions.length; i++) {
158+
const content = bedrockResponse.completions[i]
157159
const chatCompletionMessage = new LlmChatCompletionMessage({
158160
agent,
159161
segment,
160162
transaction,
161163
bedrockCommand,
162164
bedrockResponse,
163165
isResponse: true,
164-
index: promptContextMessages.length + completionIndex,
166+
index: promptContextMessages.length + i,
165167
content,
166168
role: 'assistant',
167169
completionId: summary.id
168170
})
169171
recordEvent({ agent, type: 'LlmChatCompletionMessage', msg: chatCompletionMessage })
170-
})
172+
}
171173

172174
recordEvent({ agent, type: 'LlmChatCompletionSummary', msg: summary })
173175

@@ -214,9 +216,9 @@ function recordEmbeddingMessage({
214216
isError: err !== null
215217
}))
216218

217-
embeddings.forEach((embedding) => {
219+
for (const embedding of embeddings) {
218220
recordEvent({ agent, type: 'LlmEmbedding', msg: embedding })
219-
})
221+
}
220222

221223
if (err) {
222224
const llmError = new LlmError({ bedrockResponse, err, embedding: embeddings.length === 1 ? embeddings[0] : undefined })

lib/instrumentation/bunyan.js

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,7 @@ function augmentLogData(originalLog, agent, nameFromLevel) {
3838

3939
// Add the metadata to the object being logged
4040
const metadata = agent.getLinkingMetadata(true)
41-
Object.keys(metadata).forEach((m) => {
42-
newLog[m] = metadata[m]
43-
})
44-
45-
return newLog
41+
return Object.assign({}, newLog, metadata)
4642
}
4743

4844
function createLoggerWrapper(shim, fn, fnName, bunyanLogger, nameFromLevel) {

lib/instrumentation/core/child_process.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,12 @@ function initialize(agent, childProcess, moduleName, shim) {
5656

5757
function makePromisifyCompatible(shim, childProcess) {
5858
const originalExec = shim.getOriginal(childProcess.exec)
59-
Object.getOwnPropertySymbols(originalExec).forEach((symbol) => {
59+
for (const symbol of Object.getOwnPropertySymbols(originalExec)) {
6060
childProcess.exec[symbol] = originalExec[symbol]
61-
})
61+
}
6262

6363
const originalExecFile = shim.getOriginal(childProcess.execFile)
64-
Object.getOwnPropertySymbols(originalExecFile).forEach((symbol) => {
64+
for (const symbol of Object.getOwnPropertySymbols(originalExecFile)) {
6565
childProcess.execFile[symbol] = originalExecFile[symbol]
66-
})
66+
}
6767
}

lib/instrumentation/core/fs.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ function initialize(agent, fs, moduleName, shim) {
5555
shim.record(fs, methods, recordFs)
5656

5757
const originalExists = shim.getOriginal(fs.exists)
58-
Object.getOwnPropertySymbols(originalExists).forEach((symbol) => {
58+
for (const symbol of Object.getOwnPropertySymbols(originalExists)) {
5959
fs.exists[symbol] = originalExists[symbol]
60-
})
60+
}
6161

6262
fs.realpath.native = shim.getOriginal(fs.realpath).native
6363

lib/instrumentation/core/timers.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ function initialize(_agent, timers, _moduleName, shim) {
2222
* @param {Array<Timers,global>} pkgs array with references to timers and global
2323
*/
2424
function instrumentTimerMethods(shim, pkgs) {
25-
pkgs.forEach((nodule) => {
25+
for (const nodule of pkgs) {
2626
if (shim.isWrapped(nodule.setTimeout)) {
2727
return
2828
}
@@ -31,7 +31,7 @@ function instrumentTimerMethods(shim, pkgs) {
3131
shim.record(nodule, asynchronizers, recordAsynchronizers)
3232
shim.wrap(nodule, 'clearTimeout', wrapClearTimeout)
3333
makeWrappedPromisifyCompatible(shim, nodule)
34-
})
34+
}
3535
}
3636

3737
/**
@@ -86,7 +86,7 @@ function makeWrappedPromisifyCompatible(shim, nodule) {
8686
*/
8787
function copySymbols(shim, nodule, name) {
8888
const originalFunction = shim.getOriginal(nodule[name])
89-
Object.getOwnPropertySymbols(originalFunction).forEach((symbol) => {
89+
for (const symbol of Object.getOwnPropertySymbols(originalFunction)) {
9090
nodule[name][symbol] = originalFunction[symbol]
91-
})
91+
}
9292
}

lib/instrumentation/grpc-js/grpc.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,9 @@ function wrapStart(shim, original) {
7070
const outboundAgentHeaders = Object.create(null)
7171
if (shim.agent.config.distributed_tracing.enabled) {
7272
transaction.insertDistributedTraceHeaders(outboundAgentHeaders)
73-
Object.keys(outboundAgentHeaders).forEach((key) => {
74-
nrMetadata.add(key, outboundAgentHeaders[key])
75-
})
73+
for (const [key, value] of Object.entries(outboundAgentHeaders)) {
74+
nrMetadata.add(key, value)
75+
}
7676
} else {
7777
shim.logger.debug('Distributed tracing disabled by instrumentation.')
7878
}
@@ -192,9 +192,9 @@ function wrapRegister(shim, original) {
192192

193193
function acceptDTHeaders(stream, transaction) {
194194
const metadata = stream.metadata
195-
Object.entries(metadata.getMap()).forEach(([key, value]) => {
195+
for (const [key, value] of Object.entries(metadata.getMap())) {
196196
transaction.trace.attributes.addAttribute(DESTINATION, `request.headers.${key}`, value)
197-
})
197+
}
198198

199199
const headers = Object.create(null)
200200
headers.tracestate = metadata.get('tracestate').join(',')

lib/instrumentation/koa/route-instrumentation.js

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,21 @@ const { MiddlewareSpec } = require('../../shim/specs')
1111
module.exports = function instrumentRoute(shim, route) {
1212
shim.setFramework(shim.KOA)
1313

14-
METHODS.forEach(function wrap(method) {
15-
shim.wrap(route, method, function wrapMethod(shim, methodFn) {
16-
return function wrappedMethod() {
17-
const middleware = methodFn.apply(route, arguments)
18-
return shim.recordMiddleware(
19-
middleware,
20-
new MiddlewareSpec({
21-
route: arguments[0],
22-
next: shim.LAST,
23-
name: shim.getName(arguments[1]),
24-
promise: true,
25-
req: function getReq(shim, fn, fnName, args) {
26-
return args[0] && args[0].req
27-
}
28-
})
29-
)
30-
}
31-
})
14+
shim.wrap(route, METHODS, function wrapMethod(shim, methodFn) {
15+
return function wrappedMethod() {
16+
const middleware = methodFn.apply(route, arguments)
17+
return shim.recordMiddleware(
18+
middleware,
19+
new MiddlewareSpec({
20+
route: arguments[0],
21+
next: shim.LAST,
22+
name: shim.getName(arguments[1]),
23+
promise: true,
24+
req: function getReq(shim, fn, fnName, args) {
25+
return args[0] && args[0].req
26+
}
27+
})
28+
)
29+
}
3230
})
3331
}

lib/instrumentation/langchain/vectorstore.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ function recordVectorSearch({
5252

5353
recordEvent({ agent, shim, type: 'LlmVectorSearch', pkgVersion, msg: vectorSearch })
5454

55-
output.forEach((document, sequence) => {
55+
for (let sequence = 0; sequence < output.length; sequence++) {
56+
const document = output[sequence]
5657
const vectorSearchResult = new LangChainVectorSearchResult({
5758
agent,
5859
segment,
@@ -70,7 +71,7 @@ function recordVectorSearch({
7071
pkgVersion,
7172
msg: vectorSearchResult
7273
})
73-
})
74+
}
7475

7576
if (err) {
7677
agent.errors.add(

0 commit comments

Comments
 (0)