chore: Move tracing decorators into the codebase (#4623)
* Vendorize tracing, finally fix service name issues * Upgrade datadaog-metrics, rename decorators -> tracing * lint
This commit is contained in:
@@ -5,7 +5,7 @@ import winston from "winston";
|
||||
import env from "@server/env";
|
||||
import Metrics from "@server/logging/Metrics";
|
||||
import Sentry from "@server/logging/sentry";
|
||||
import * as Tracing from "./tracing";
|
||||
import * as Tracing from "./tracer";
|
||||
|
||||
const isProduction = env.ENVIRONMENT === "production";
|
||||
|
||||
|
||||
@@ -29,13 +29,8 @@ class Metrics {
|
||||
return;
|
||||
}
|
||||
|
||||
const instanceId = process.env.INSTANCE_ID || process.env.HEROKU_DYNO_ID;
|
||||
|
||||
if (!instanceId) {
|
||||
throw new Error(
|
||||
"INSTANCE_ID or HEROKU_DYNO_ID must be set when using DataDog"
|
||||
);
|
||||
}
|
||||
const instanceId =
|
||||
process.env.INSTANCE_ID || process.env.HEROKU_DYNO_ID || process.pid;
|
||||
|
||||
return ddMetrics.gauge(key, value, [...tags, `instance:${instanceId}`]);
|
||||
}
|
||||
|
||||
92
server/logging/tracer.ts
Normal file
92
server/logging/tracer.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import tracer, { Span } from "dd-trace";
|
||||
import env from "@server/env";
|
||||
|
||||
type PrivateDatadogContext = {
|
||||
req: Record<string, any> & {
|
||||
_datadog?: {
|
||||
span?: Span;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// If the DataDog agent is installed and the DD_API_KEY environment variable is
|
||||
// in the environment then we can safely attempt to start the DD tracer
|
||||
if (env.DD_API_KEY) {
|
||||
tracer.init({
|
||||
version: env.VERSION,
|
||||
service: env.DD_SERVICE,
|
||||
env: env.ENVIRONMENT,
|
||||
});
|
||||
}
|
||||
|
||||
const getCurrentSpan = (): Span | null => tracer.scope().active();
|
||||
|
||||
/**
|
||||
* Add tags to a span to have more context about how and why it was running.
|
||||
* If added to the root span, tags are searchable and filterable.
|
||||
*
|
||||
* @param tags An object with the tags to add to the span
|
||||
* @param span An optional span object to add the tags to. If none provided,the current span will be used.
|
||||
*/
|
||||
export function addTags(tags: Record<string, any>, span?: Span | null): void {
|
||||
if (tracer) {
|
||||
const currentSpan = span || getCurrentSpan();
|
||||
|
||||
if (!currentSpan) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentSpan.addTags(tags);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The root span is an undocumented internal property that DataDog adds to `context.req`.
|
||||
* The root span is required in order to add searchable tags.
|
||||
* Unfortunately, there is no API to access the root span directly.
|
||||
* See: node_modules/dd-trace/src/plugins/util/web.js
|
||||
*
|
||||
* @param context A Koa context object
|
||||
*/
|
||||
export function getRootSpanFromRequestContext(
|
||||
context: PrivateDatadogContext
|
||||
): Span | null {
|
||||
// eslint-disable-next-line no-undef
|
||||
return context?.req?._datadog?.span ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the resource of the active APM span. This method wraps addTags to allow
|
||||
* safe use in environments where APM is disabled.
|
||||
*
|
||||
* @param name The name of the resource
|
||||
*/
|
||||
export function setResource(name: string) {
|
||||
if (tracer) {
|
||||
addTags({
|
||||
"resource.name": `${name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the current active span as an error. This method wraps addTags to allow
|
||||
* safe use in environments where APM is disabled.
|
||||
*
|
||||
* @param error The error to add to the current span
|
||||
*/
|
||||
export function setError(error: Error, span?: Span) {
|
||||
if (tracer) {
|
||||
addTags(
|
||||
{
|
||||
errorMessage: error.message,
|
||||
"error.type": error.name,
|
||||
"error.msg": error.message,
|
||||
"error.stack": error.stack,
|
||||
},
|
||||
span
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default tracer;
|
||||
@@ -1,46 +1,212 @@
|
||||
import { init, tracer, addTags, markAsError } from "@theo.gravity/datadog-apm";
|
||||
// MIT License
|
||||
|
||||
// Copyright (c) 2020 GameChanger Media
|
||||
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
import { SpanOptions } from "dd-trace";
|
||||
import DDTags from "dd-trace/ext/tags";
|
||||
import env from "@server/env";
|
||||
import tracer, { setError } from "./tracer";
|
||||
|
||||
export * as APM from "@theo.gravity/datadog-apm";
|
||||
type DDTag = typeof DDTags[keyof typeof DDTags];
|
||||
|
||||
// If the DataDog agent is installed and the DD_API_KEY environment variable is
|
||||
// in the environment then we can safely attempt to start the DD tracer
|
||||
if (env.DD_API_KEY) {
|
||||
init(
|
||||
{
|
||||
version: env.VERSION,
|
||||
service: process.env.DD_SERVICE || "outline",
|
||||
},
|
||||
{
|
||||
useMock: env.ENVIRONMENT === "test",
|
||||
type Tags = {
|
||||
[tag in DDTag]?: any;
|
||||
} & {
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
interface Constructor {
|
||||
new (...args: any[]): any;
|
||||
}
|
||||
|
||||
interface TraceConfig {
|
||||
className?: string;
|
||||
methodName?: string;
|
||||
serviceName?: string;
|
||||
spanName?: string;
|
||||
resourceName?: string;
|
||||
isRoot?: boolean;
|
||||
/** Cause the span to show up in trace search and analytics */
|
||||
makeSearchable?: boolean;
|
||||
tags?: Tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* This decorator will cause an individual function to be traced by the APM.
|
||||
*
|
||||
* @param config Optional configuration for the span that will be created for this trace.
|
||||
*/
|
||||
export const traceFunction = (config: TraceConfig) => <
|
||||
F extends (...args: any[]) => any,
|
||||
P extends Parameters<F>,
|
||||
R extends ReturnType<F>
|
||||
>(
|
||||
target: F
|
||||
): F =>
|
||||
env.ENVIRONMENT === "test"
|
||||
? target
|
||||
: (function wrapperFn(this: any, ...args: P): R {
|
||||
const {
|
||||
className,
|
||||
methodName = target.name,
|
||||
spanName = "DEFAULT_SPAN_NAME",
|
||||
makeSearchable: useAnalytics,
|
||||
tags,
|
||||
} = config;
|
||||
const childOf = config.isRoot
|
||||
? undefined
|
||||
: tracer.scope().active() || undefined;
|
||||
const resourceName = config.resourceName
|
||||
? config.resourceName
|
||||
: className
|
||||
? `${className}.${methodName}`
|
||||
: methodName;
|
||||
const spanOptions: SpanOptions = {
|
||||
childOf,
|
||||
tags: {
|
||||
[DDTags.RESOURCE_NAME]: resourceName,
|
||||
...tags,
|
||||
},
|
||||
};
|
||||
|
||||
const span = tracer.startSpan(spanName, spanOptions);
|
||||
|
||||
if (!span) {
|
||||
return target.call(this, ...args);
|
||||
}
|
||||
|
||||
if (config.serviceName) {
|
||||
span.setTag(
|
||||
DDTags.SERVICE_NAME,
|
||||
`${env.DD_SERVICE}-${config.serviceName}`
|
||||
);
|
||||
}
|
||||
|
||||
if (useAnalytics) {
|
||||
span.setTag(DDTags.ANALYTICS, true);
|
||||
}
|
||||
|
||||
// The callback fn needs to be wrapped in an arrow fn as the activate fn clobbers `this`
|
||||
return tracer.scope().activate(span, () => {
|
||||
const output = target.call(this, ...args);
|
||||
|
||||
if (output && typeof output.then === "function") {
|
||||
output
|
||||
.catch((error: Error) => {
|
||||
setError(error, span);
|
||||
})
|
||||
.finally(() => {
|
||||
span.finish();
|
||||
});
|
||||
} else {
|
||||
span.finish();
|
||||
}
|
||||
|
||||
return output;
|
||||
});
|
||||
} as F);
|
||||
|
||||
const traceMethod = (config?: TraceConfig) =>
|
||||
function <R, A extends any[], F extends (...args: A) => R>(
|
||||
target: any,
|
||||
_propertyKey: string,
|
||||
descriptor: PropertyDescriptor
|
||||
): TypedPropertyDescriptor<F> {
|
||||
const wrappedFn = descriptor.value;
|
||||
|
||||
if (wrappedFn) {
|
||||
const className = target.name || target.constructor.name; // target.name is needed if the target is the constructor itself
|
||||
const methodName = wrappedFn.name;
|
||||
descriptor.value = traceFunction({ ...config, className, methodName })(
|
||||
wrappedFn
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the resource of the active APM span. This method wraps addTags to allow
|
||||
* safe use in environments where APM is disabled.
|
||||
*
|
||||
* @param name The name of the resource
|
||||
*/
|
||||
export function setResource(name: string) {
|
||||
if (tracer) {
|
||||
addTags({
|
||||
"resource.name": `${name}`,
|
||||
return descriptor;
|
||||
};
|
||||
|
||||
const traceClass = (config?: TraceConfig) =>
|
||||
function <T extends Constructor>(constructor: T): void {
|
||||
const protoKeys = Reflect.ownKeys(constructor.prototype);
|
||||
protoKeys.forEach((key) => {
|
||||
if (key === "constructor") {
|
||||
return;
|
||||
}
|
||||
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
constructor.prototype,
|
||||
key
|
||||
);
|
||||
|
||||
// eslint-disable-next-line no-undef
|
||||
if (typeof key === "string" && typeof descriptor?.value === "function") {
|
||||
Object.defineProperty(
|
||||
constructor.prototype,
|
||||
key,
|
||||
traceMethod(config)(constructor, key, descriptor)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const staticKeys = Reflect.ownKeys(constructor);
|
||||
staticKeys.forEach((key) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(constructor, key);
|
||||
|
||||
// eslint-disable-next-line no-undef
|
||||
if (typeof key === "string" && typeof descriptor?.value === "function") {
|
||||
Object.defineProperty(
|
||||
constructor,
|
||||
key,
|
||||
traceMethod(config)(constructor, key, descriptor)
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Mark the current active span as an error. This method wraps addTags to allow
|
||||
* safe use in environments where APM is disabled.
|
||||
* This decorator will cause the methods of a class, or an individual method, to be traced by the APM.
|
||||
*
|
||||
* @param error The error to add
|
||||
* @param config Optional configuration for the span that will be created for this trace.
|
||||
*/
|
||||
export function setError(error: Error) {
|
||||
if (tracer) {
|
||||
markAsError(error);
|
||||
// Going to rely on inferrence do its thing for this function
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
||||
export function trace(config?: TraceConfig) {
|
||||
function traceDecorator(target: Constructor): void;
|
||||
function traceDecorator<T>(
|
||||
target: Record<string, any>,
|
||||
propertyKey: string | symbol,
|
||||
descriptor: TypedPropertyDescriptor<T>
|
||||
): void;
|
||||
function traceDecorator(
|
||||
a: Constructor | Record<string, any>,
|
||||
b?: any,
|
||||
c?: any
|
||||
): void {
|
||||
if (typeof a === "function") {
|
||||
// Need to cast as there is no safe runtime way to check if a function is a constructor
|
||||
traceClass(config)(a as Constructor);
|
||||
} else {
|
||||
traceMethod(config)(a, b, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default tracer;
|
||||
return traceDecorator;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user