Shim

A helper class for wrapping modules with segments.

Constructor

new Shim(agent, moduleName, resolvedName, shimName, pkgVersion)

Constructs a shim associated with the given agent instance.

Parameters:
NameTypeDescription
agentAgent

The agent this shim will use.

moduleNamestring

The name of the module being instrumented.

resolvedNamestring

The full path to the loaded module.

shimNamestring

Used to persist shim ids across different instances. This is

pkgVersionstring

version of package getting instrumented applicable to instrument that compliments each other across libraries(i.e - koa + koa-route/koa-router)

Members

(readonly) agent :Agent

The agent associated with this shim.

Type:
  • Agent

(readonly) logger :Logger

The logger for this shim.

Type:
  • Logger

(readonly) tracer :Tracer

The transaction tracer in use by the agent for the shim.

Type:
  • Tracer

Methods

applySegment(func, segment, full, context, args, inContextCBopt) → {*}

Sets the given segment as the active one for the duration of the function's execution.

  • applySegment(func, segment, full, context, args[, inContextCB])
Parameters:
NameTypeAttributesDescription
funcfunction

The function to execute in the context of the given segment.

segmentTraceSegment

The segment to make active for the duration of the function.

fullboolean

Indicates if the full lifetime of the segment is bound to this function.

context*

The this argument for the function.

argsArray.<*>

The arguments to be passed into the function.

inContextCBfunction<optional>

The function used to do more instrumentation work. This function is guaranteed to be executed with the segment associated with.

Returns:

Whatever value func returned.

Type: 
*

argsToArray() → {Array}

Like Shim#toArray, but converts arguments to an array.

This is the preferred function, when used with .apply, for converting the arguments object into an actual Array as it will not cause deopts.

Returns:

An array containing the elements of arguments.

Type: 
Array

assignId(shimName)

Assigns id to shim instance. If shimName is present it will reuse an id otherwise it'll create a unique id.

Parameters:
NameTypeDescription
shimNamestring

Used to persist shim ids across different instances.

assignOriginal(wrapped, original, forceOrig)

Assigns the shim id and original on the wrapped item. TODO: Once all wrapping is converted to proxies, we won't need to set this property as the trap on 'get' will return the original for symbols.original. For now, we have to prevent setting this on original.

Parameters:
NameTypeDescription
wrapped*

wrapped item

original*
  • The item being wrapped.
forceOrigboolean

flag to indicate to overwrite original function

bindCallbackSegment(spec, args, cbIdx, parentSegmentopt)

Replaces the callback in an arguments array with one that has been bound to the given segment.

  • bindCallbackSegment(spec, args, cbIdx [, segment])
  • bindCallbackSegment(spec, obj, property [, segment])
Parameters:
NameTypeAttributesDescription
specSpec

spec to original wrapped function, used to call after method with arguments passed to callback

argsArray | object

The arguments array to pull the cb from.

cbIdxnumber | string

The index of the callback.

parentSegmentTraceSegment<optional>

The segment to use as the callback segment's parent. Defaults to the currently active segment.

bindPromise(promisenon-null, segmentnon-null) → {Promise}

Binds the given segment to the completion of the Promise. Updates segment timing and resets opaque state.

Parameters:
NameTypeDescription
promisePromise

The Promise to bind.

segmentTraceSegment

The segment to bind to the Promise.

Returns:

The promise to continue with.

Type: 
Promise

bindSegment(nodule, propertyopt, segmentopt, nullable, fullopt) → {object|function}

Binds the execution of a function to a single segment.

  • bindSegment(nodule , property [, segment [, full]])
  • bindSegment(func [, segment [, full]])

If called with a nodule and a property, the wrapped property will be put back on the nodule. Otherwise, the wrapped function is just returned.

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the property or a single function to bind to a segment.

propertystring<optional>

The property to bind. If omitted, the nodule parameter is assumed to be the function to bind the segment to.

segmentTraceSegment<optional>
<nullable>

The segment to bind the execution of the function to. If omitted or null the currently active segment will be bound instead.

fullboolean<optional>

Indicates if the full lifetime of the segment is bound to this function.

Returns:

The first parameter after wrapping.

Type: 
object | function

copySegmentParameters(segment, parameters)

Copies the given parameters onto the segment, respecting the current agent configuration.

Parameters:
NameTypeDescription
segmentTraceSegment

The segment to copy the parameters onto.

parametersobject

The parameters to copy.

createSegment(name, recorderopt, nullable, parentopt) → (nullable) {TraceSegment}

Creates a new segment.

  • createSegment(opts)
  • createSegment(name [, recorder] [, parent])
Parameters:
NameTypeAttributesDescription
namestring

The name to give the new segment.

recorderfunction<optional>
<nullable>

Optional. A function which will record the segment as a metric. Default is to not record the segment.

parentTraceSegment<optional>

Optional. The segment to use as the parent. Default is to use the currently active segment.

Returns:

A new trace segment if a transaction is active, else null is returned.

Type: 
TraceSegment

defineProperties(obj, props)

Adds several properties to the given object.

Parameters:
NameTypeDescription
objobject

The object to add the properties to.

propsobject

A mapping of properties to values to add.

defineProperty(obj, name, value)

Defines a read-only property on the given object.

Parameters:
NameTypeDescription
objobject

The object to add the property to.

namestring

The name of the property to add.

value* | function

The value to set. If a function is given, it is used as a getter, otherwise the value is directly set as an unwritable property.

execute(nodule, spec)

Entry point for executing a spec.

Parameters:
NameTypeDescription
noduleobject | function

Class or module containing the function to wrap.

specSpec

Spec

getActiveSegment(objopt) → (nullable) {TraceSegment}

Retrieves the segment associated with the given object, or the currently active segment if no object is given.

  • getActiveSegment([obj])

An active segment is one whose transaction is still active (e.g. has not ended yet).

Parameters:
NameTypeAttributesDescription
obj*<optional>

The object to retrieve a segment from.

Returns:

The trace segment associated with the given object or the currently active segment if no object is provided or no segment is associated with the object.

Type: 
TraceSegment

getName(obj) → {string}

Determine the name of an object.

Parameters:
NameTypeDescription
obj*

The object to get a name for.

Returns:

The name of the object if it has one, else <anonymous>.

Type: 
string

getOriginal(nodule, propertyopt) → {object|function}

Retrieves the original method for a wrapped function.

  • getOriginal(nodule, property)
  • getOriginal(func)
Parameters:
NameTypeAttributesDescription
noduleobject | function

The source of the property to get the original of, or a function to unwrap.

propertystring<optional>

A property on nodule to get the original value of.

Returns:

The original value for the given item.

Type: 
object | function

getOriginalOnce(nodule, propertyopt) → {object|function}

Retrieves the value of symbols.original on the wrapped function. Unlike getOriginal this just looks in the direct wrapped function

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source of the property to get the original of, or a function to unwrap.

propertystring<optional>

A property on nodule to get the original value of.

Returns:

The original value for the given item.

Type: 
object | function

getSegment(objopt) → (nullable) {TraceSegment}

Retrieves the segment associated with the given object, or the current segment if no object is given.

  • getSegment([obj])
Parameters:
NameTypeAttributesDescription
obj*<optional>

The object to retrieve a segment from.

Returns:

The trace segment associated with the given object or the current segment if no object is provided or no segment is associated with the object.

Type: 
TraceSegment

interceptPromise(prom, cb) → {Promise}

Executes the given callback when the promise is finalized, whether it is resolved or rejected.

Parameters:
NameTypeDescription
promPromise

Some kind of promise. Must have a then method.

cbfunction

A function to call when the promise resolves.

Returns:

A new promise to replace the original one.

Type: 
Promise

isArray(obj) → {boolean}

Determines if the given object exists and is an array.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is an array, else false.

Type: 
boolean

isAsyncFunction(fn, (function)) → {boolean}

Determines if function is an async function. Note it does not test if the return value of function is a promise or async function

Parameters:
NameTypeDescription
fn
(function)

function to test if async

Returns:

True if the function is an async function

Type: 
boolean

isBoolean(obj) → {boolean}

Determines if the given object is a boolean literal.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is a boolean literal, else false.

Type: 
boolean

isFunction(obj) → {boolean}

Determines if the given object exists and is a function.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is a function, else false.

Type: 
boolean

isNull(val) → {boolean}

Determines if the given value is null.

Parameters:
NameTypeDescription
val*

The value to check.

Returns:

True if the value is null, else false.

Type: 
boolean

isNumber(obj) → {boolean}

Determines if the given object is a number literal.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is a number literal, else false.

Type: 
boolean

isObject(obj) → {boolean}

Determines if the given object is an Object.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is an Object, else false.

Type: 
boolean

isPromise(obj) → {boolean}

Determines if the given object is a promise instance.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is a promise, else false.

Type: 
boolean

isString(obj) → {boolean}

Determines if the given object exists and is a string.

Parameters:
NameTypeDescription
obj*

The object to check.

Returns:

True if the object is a string, else false.

Type: 
boolean

isWrapped(nodule, propertyopt) → {boolean}

Determines if the specified function or property exists and is wrapped.

  • isWrapped(nodule, property)
  • isWrapped(func)
Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the property or a single function to check.

propertystring<optional>

The property to check. If omitted, the nodule parameter is assumed to be the function to check.

Returns:

True if the item exists and has been wrapped.

Type: 
boolean

normalizeIndex(arrayLength, idx) → (nullable) {number}

Ensures the given index is a valid index inside the array.

A negative index value is converted to a positive one by adding it to the array length before checking it.

Parameters:
NameTypeDescription
arrayLengthnumber

The length of the array this index is for.

idxnumber

The index to normalize.

Returns:

The adjusted index value if it is valid, else null.

Type: 
number

once(fn) → {function}

Wraps a function such that it will only be executed once.

Parameters:
NameTypeDescription
fnfunction

The function to wrap in an execution guard.

Returns:

A function which will execute fn at most once.

Type: 
function

prefixRouteParameters(params) → {object|undefined}

Method for prefixing Route (aka URL) parameters with request.parameters.route

Many web frameworks support adding parameters to routes when defining your API structure, and this function updates those parameters names to be prefixed by request.parameters.route. This is to avoid collision with reserved attribute names, as parameters used to be blindly stored on router span attributes (see https://github.com/newrelic/node-newrelic/issues/1574) in addition to being prefixed by request.parameters.

Route parameters used to be stored under request.parameters.* just like query parameters pre v10, but we now prefix with request.parameter.route to avoid collision in the event an application uses the same name for a query and route parameter. Additionally, we now store the same key on the attributes of the base segment, trace, and router span.

Exported on shim to be used in our Next.js instrumentation, as that instrumentation does not follow the same pattern as all the other web frameworks we support.

Parameters:
NameTypeDescription
paramsobject

Object containing route/url parameter key/value pairs

Returns:

the updated object, key will now be request.parameters.route.key, value remains untouched

Type: 
object | undefined

proxy(source, properties, dest)

Proxies all set/get actions for each given property on dest onto source.

Parameters:
NameTypeDescription
source*

The object on which all the set/get actions will actually occur.

propertiesstring | Array.<string>

All of the properties to proxy.

dest*

The object which is proxying the source's properties.

record(nodule, propertiesopt, recordNamer) → {object|function}

Wraps a function with segment creation and binding.

  • record(nodule, properties, recordNamer)
  • record(func, recordNamer)

This is shorthand for calling Shim#wrap and manually creating a segment.

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the properties to record, or a single function to record.

propertiesstring | Array.<string><optional>

One or more properties to record. If omitted, the nodule parameter is assumed to be the function to record.

recordNamerRecorderFunction

A function which returns a record descriptor that gives the name and type of record we'll make.

Returns:

The first parameter, possibly wrapped.

Type: 
object | function

setActiveSegment(segment) → {TraceSegment}

Explicitly sets the active segment to the one passed in. This method should only be used if there is no function to tie a segment's timing to.

  • setActiveSegment(segment)
Parameters:
NameTypeDescription
segmentTraceSegment

The segment to set as the active segment.

Returns:
  • The segment set as active on the context.
Type: 
TraceSegment

setDefaults(objnullable, defaults) → {object}

Performs a shallow copy of each property from defaults only if obj does not already have that property, or the value of the key on obj is null.

Parameters:
NameTypeAttributesDescription
objobject<nullable>

The object to copy the defaults onto.

defaultsobject

A mapping of keys to default values.

Returns:

The obj with the default values copied onto it. If obj was falsey, then a new object with the defaults copied onto it is returned instead.

Type: 
object

shimRequire(filePath) → (nullable) {*}

Loads a node module from the instrumented library's own root directory.

Parameters:
NameTypeDescription
filePathstring

A relative path inside the module's directory.

Returns:

The result of loading the given module. If the module fails to load, null is returned instead.

Type: 
*

storeSegment(objnon-null, segmentopt)

Associates a segment with the given object.

  • storeSegment(obj [, segment])

If no segment is provided, the currently active segment is used.

Parameters:
NameTypeAttributesDescription
obj*

The object to retrieve a segment from.

segmentTraceSegment<optional>

The segment to link the object to.

toArray(obj) → {Array.<*>}

Converts an array-like object into an array.

Parameters:
NameTypeDescription
obj*

The array-like object (i.e. arguments).

Returns:

An instance of Array containing the elements of the array-like.

Type: 
Array.<*>

unwrap(nodule, propertiesopt) → {object|function}

Unwraps one item, revealing the underlying value. If item is wrapped multiple times, the unwrap will not occur as we cannot safely unwrap.

  • unwrap(nodule, property)
  • unwrap(func)

If called with a nodule and properties, the unwrapped value will be put back on the nodule. Otherwise, the unwrapped function is just returned.

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the properties to unwrap, or a single function to unwrap.

propertiesstring | Array.<string><optional>

One or more properties to unwrap. If omitted, the nodule parameter is assumed to be the function to unwrap.

Returns:

The first parameter after unwrapping.

Type: 
object | function

wrap(nodule, propertiesopt, spec, argsopt) → {object|function}

Executes the provided spec on one or more objects.

  • wrap(nodule, properties, spec [, args])
  • wrap(func, spec [, args])

When called with a nodule and one or more properties, the spec will be executed on each property listed and the return value put back on the nodule.

When called with just a function, the spec will be executed on the function and the return value of the spec simply passed back.

The wrapped version will have the same prototype as the original method.

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the properties to wrap, or a single function to wrap.

propertiesstring | Array.<string><optional>

One or more properties to wrap. If omitted, the nodule parameter is assumed to be the function to wrap.

specSpec | WrapFunction

The spec for wrapping these items.

argsArray.<*><optional>

Optional extra arguments to be sent to the spec when executing it.

Returns:

The first parameter to this function, after wrapping it or its properties.

Type: 
object | function

wrapClass(nodule, propertiesopt, spec, argsopt) → {object|function}

Wraps a class constructor using a subclass with pre- and post-construction hooks.

  • wrapClass(nodule, properties, spec [, args])
  • wrapClass(func, spec [, args])
Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the properties to wrap, or a single function to wrap.

propertiesstring | Array.<string><optional>

One or more properties to wrap. If omitted, the nodule parameter is assumed to be the constructor to wrap.

specClassWrapSpec | ConstructorHookFunction

The spec for wrapping the returned value from the properties or a post hook.

argsArray.<*><optional>

Optional extra arguments to be sent to the spec when executing it.

Returns:

The first parameter to this function, after wrapping it or its properties.

Type: 
object | function

wrapExport(nodule, spec) → {*}

Wraps the actual module being instrumented to change what require returns.

  • wrapExport(nodule, spec)
Parameters:
NameTypeDescription
nodule*

The original export to replace with our new one.

specWrapFunction

A wrapper function. The return value from this spec is what will replace the export.

Returns:

The return value from spec.

Type: 
*

wrapReturn(nodule, propertiesopt, spec, argsopt) → {object|function}

Executes the provided spec with the return value of the given properties.

  • wrapReturn(nodule, properties, spec [, args])
  • wrapReturn(func, spec [, args])

If the wrapper is executed with new then the wrapped function will also be called with new. This feature should only be used with factory methods disguised as classes. Normally Shim#wrapClass should be used to wrap constructors instead.

Parameters:
NameTypeAttributesDescription
noduleobject | function

The source for the properties to wrap, or a single function to wrap.

propertiesstring | Array.<string><optional>

One or more properties to wrap. If omitted, the nodule parameter is assumed to be the function to wrap.

specSpec | function

The spec for wrapping the returned value from the properties.

argsArray.<*><optional>

Optional extra arguments to be sent to the spec when executing it.

Returns:

The first parameter to this function, after wrapping it or its properties.

Type: 
object | function