Skip to content

Commit

Permalink
Add recordErrorIf and recordSuccessIf callbacks (#85)
Browse files Browse the repository at this point in the history
* add recordErrorIf and recordOkIf callbacks as parameters

* make sure types are exported

* resolve merge conflict

* relax modulePath getter conditions so it can fit how NestJS reports decorators
  • Loading branch information
keturiosakys authored Jul 14, 2023
1 parent abb6b7c commit 0fe41c0
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 21 deletions.
2 changes: 1 addition & 1 deletion packages/lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function getModulePath(): string | undefined {
*/
const wrappedFunctionPath =
stack.find((call) => {
if (call.name === "__decorateClass") return true;
if (call.name?.includes("__decorate")) return true;
})?.file ?? stack[2]?.file;

const containsFileProtocol = wrappedFunctionPath.includes("file://");
Expand Down
108 changes: 88 additions & 20 deletions packages/lib/src/wrappers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ if (typeof window === "undefined") {
// Function Wrapper
// This seems to be the preferred way for defining functions in TypeScript
// rome-ignore lint/suspicious/noExplicitAny:
type FunctionSig = (...args: any[]) => any;
export type FunctionSig = (...args: any[]) => any;

type AnyFunction<T extends FunctionSig> = (
...params: Parameters<T>
Expand All @@ -36,7 +36,7 @@ type AnyFunction<T extends FunctionSig> = (
breaks the language server plugin */
interface AutometricsWrapper<T extends AnyFunction<T>> extends AnyFunction<T> {}

export type AutometricsOptions = {
export type AutometricsOptions<F extends FunctionSig> = {
/**
* Name of your function. Only necessary if using the decorator/wrapper on the
* client side where builds get minified.
Expand All @@ -59,8 +59,41 @@ export type AutometricsOptions = {
* handler that passes requests off to other functions. (default: `false`)
*/
trackConcurrency?: boolean;
/**
* A custom callback function that determines whether a function return should
* be considered an error by Autometrics. This may be most useful in
* top-level functions such as the HTTP handler which would catch any errors
* thrown called from inside the handler.
*
* @example
* ```typescript
* async function createUser(payload: User) {
* // ...
* }
*
* // This will record an error if the handler response status is 4xx or 5xx
* const recordErrorIf = (res) => res.status >= 400;
*
* app.post("/users", autometrics({ recordErrorIf }, createUser)
* ```
*/
recordErrorIf?: ReportErrorCondition<F>;
/**
* A custom callback function that determines whether a function result
* should be considered a success (regardless if it threw an error). This
* may be most useful when you want to ignore certain errors that are thrown
* by the function.
*
*/
recordSuccessIf?: ReportSuccessCondition;
};

export type ReportErrorCondition<F extends FunctionSig> = (
result: Awaited<ReturnType<F>>,
) => boolean;

export type ReportSuccessCondition = (result: Error) => boolean;

/**
* Autometrics wrapper for **functions** (requests handlers or database methods)
* that automatically instruments the wrapped function with OpenTelemetry metrics.
Expand Down Expand Up @@ -118,14 +151,16 @@ export type AutometricsOptions = {
*
*/
export function autometrics<F extends FunctionSig>(
functionOrOptions: F | AutometricsOptions,
functionOrOptions: F | AutometricsOptions<F>,
fnInput?: F,
): AutometricsWrapper<F> {
let functionName: string;
let moduleName: string;
let fn: F;
let objective: Objective | undefined;
let trackConcurrency = false;
let recordErrorIf: ReportErrorCondition<F> | undefined;
let recordSuccessIf: ReportSuccessCondition | undefined;

if (typeof functionOrOptions === "function") {
fn = functionOrOptions;
Expand All @@ -150,6 +185,14 @@ export function autometrics<F extends FunctionSig>(
if ("trackConcurrency" in functionOrOptions) {
trackConcurrency = functionOrOptions.trackConcurrency;
}

if ("recordErrorIf" in functionOrOptions) {
recordErrorIf = functionOrOptions.recordErrorIf;
}

if ("recordSuccessIf" in functionOrOptions) {
recordSuccessIf = functionOrOptions.recordSuccessIf;
}
}

if (!functionName) {
Expand Down Expand Up @@ -256,25 +299,50 @@ export function autometrics<F extends FunctionSig>(
}
};

const recordSuccess = (returnValue: Awaited<ReturnType<F>>) => {
try {
if (recordErrorIf?.(returnValue)) {
onError();
} else {
onSuccess();
}
} catch (callbackError) {
onSuccess();
console.trace("Error in recordErrorIf function: ", callbackError);
}
};

const recordError = (error: Error) => {
try {
if (recordSuccessIf?.(error)) {
onSuccess();
} else {
onError();
}
} catch (callbackError) {
onError();
console.trace("Error in recordSuccessIf function: ", callbackError);
}
};

function instrumentedFunction() {
try {
const result = fn.apply(this, params);
if (isPromise<ReturnType<F>>(result)) {
return result
.then((res: Awaited<ReturnType<typeof result>>) => {
onSuccess();
return res;
const returnValue: ReturnType<F> = fn.apply(this, params);
if (isPromise<ReturnType<F>>(returnValue)) {
return returnValue
.then((result: Awaited<ReturnType<typeof returnValue>>) => {
recordSuccess(result);
return result;
})
.catch((err: unknown) => {
onError();
throw err;
.catch((error: Error) => {
recordError(error);
throw error;
});
}

onSuccess();
return result;
recordSuccess(returnValue);
return returnValue;
} catch (error) {
onError();
recordError(error);
throw error;
}
}
Expand All @@ -291,13 +359,13 @@ export function autometrics<F extends FunctionSig>(
}

export type AutometricsClassDecoratorOptions = Omit<
AutometricsOptions,
AutometricsOptions<FunctionSig>,
"functionName"
>;

type AutometricsDecoratorOptions<T> = T extends Function
type AutometricsDecoratorOptions<F> = F extends FunctionSig
? AutometricsClassDecoratorOptions
: AutometricsOptions;
: AutometricsOptions<FunctionSig>;

/**
* Autometrics decorator that can be applied to either a class or class method
Expand Down Expand Up @@ -394,7 +462,7 @@ export function Autometrics<T extends Function | Object>(
* @param autometricsOptions
*/
export function getAutometricsMethodDecorator(
autometricsOptions?: AutometricsOptions,
autometricsOptions?: AutometricsOptions<FunctionSig>,
) {
return function (
_target: Object,
Expand Down

0 comments on commit 0fe41c0

Please sign in to comment.