Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update wonder-stuff-sentry to Sentry v9 #1122

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shaggy-mugs-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@khanacademy/wonder-stuff-sentry": major
---

Migrate the `KindErrorData` integration to be compatible with @sentry/types@9
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ coverage
**/*.template
**/package.json
**/*.md
docs/assets/main.js
docs/**
packages/eslint-plugin-khan/demo
8 changes: 6 additions & 2 deletions packages/wonder-stuff-sentry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,16 @@
"@khanacademy/wonder-stuff-core": "^1.5.4"
},
"devDependencies": {
"@khanacademy/ws-dev-build-settings": "^2.0.1"
"@khanacademy/ws-dev-build-settings": "^2.0.1",
"@sentry/core": "9"
},
"peerDependencies": {
"@sentry/core": "9"
},
"browser": {
"dist/es/index.js": "./dist/browser/es/index.js",
"dist/index.js": "./dist/browser/index.js"
},
"author": "",
"license": "MIT"
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: I would expect this to be a moved file also? Is the other snapshot not deleted?

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`KindErrorData #constructor when not built for production should throw if options are invalid ({
kindTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-kind',
groupByTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-group-by',
concatenatedMessageTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-concatenated-message'
}) 1`] = `"Invalid options"`;

exports[`KindErrorData #constructor when not built for production should throw if options are invalid ({ concatenatedMessageTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) 1`] = `"Invalid options"`;

exports[`KindErrorData #constructor when not built for production should throw if options are invalid ({ groupByTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) 1`] = `"Invalid options"`;

exports[`KindErrorData #constructor when not built for production should throw if options are invalid ({ kindTagName: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) 1`] = `"Invalid options"`;
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import * as CollateSentryData from "../collate-sentry-data";
import {DefaultKindErrorDataOptions} from "../default-kind-error-data-options";
import {EmptySentryData} from "../empty-sentry-data";
import {KindErrorData} from "../kind-error-data";
import {kindErrorDataIntegration} from "../kind-error-data-integration";

jest.mock("../collate-sentry-data");

const mockClient: any = 0;

describe("KindErrorData", () => {
const NODE_ENV = process.env.NODE_ENV;
afterEach(() => {
Expand Down Expand Up @@ -33,7 +35,7 @@ describe("KindErrorData", () => {
// Arrange

// Act
const act = () => new KindErrorData(badOptions);
const act = () => kindErrorDataIntegration(badOptions);

// Assert
expect(act).toThrowErrorMatchingSnapshot();
Expand Down Expand Up @@ -61,7 +63,7 @@ describe("KindErrorData", () => {
// Arrange

// Act
const act = () => new KindErrorData(badOptions);
const act = () => kindErrorDataIntegration(badOptions);

// Assert
expect(act).not.toThrowError("Invalid options");
Expand All @@ -81,7 +83,7 @@ describe("KindErrorData", () => {
const act = new Promise((resolve: any, reject: any) => {
try {
// Should not resolve!
resolve(new KindErrorData(badOptions));
resolve(kindErrorDataIntegration(badOptions));
} catch (e: any) {
reject(e);
}
Expand All @@ -103,77 +105,7 @@ describe("KindErrorData", () => {
});
});

describe("#setupOnce", () => {
it("should register a global event processor", () => {
// Arrange
const addGlobalEventProcessorMock = jest.fn();
const underTest = new KindErrorData();

// Act
underTest.setupOnce(addGlobalEventProcessorMock, jest.fn());

// Assert
expect(addGlobalEventProcessorMock).toHaveBeenCalledWith(
expect.any(Function),
);
});

describe("registered event processor", () => {
it("should return the event if the integration is not returned from the hub", () => {
// Arrange
const addGlobalEventProcessorMock = jest.fn();
const getHub = () => ({
getIntegration: () => undefined,
});
const underTest = new KindErrorData();
underTest.setupOnce(addGlobalEventProcessorMock, getHub);
const registeredProcessor =
addGlobalEventProcessorMock.mock.calls[0][0];
const event = {
kind: "event",
event_id: "event-id",
} as const;

// Act
const result = registeredProcessor(event);

// Assert
expect(result).toBe(event);
});

it("should call enhanceEventWithErrorData", () => {
// Arrange
const underTest = new KindErrorData();
const addGlobalEventProcessorMock = jest.fn();
const getHub = () => ({
getIntegration: jest.fn().mockReturnValue(underTest),
});
const enhanceSpy = jest
.spyOn(underTest, "enhanceEventWithErrorData")
// @ts-expect-error [FEI-5011] - TS2559 - Type '"ENHANCED"' has no properties in common with type 'SentryEvent'.
.mockReturnValue("ENHANCED");
underTest.setupOnce(addGlobalEventProcessorMock, getHub);
const registeredProcessor =
addGlobalEventProcessorMock.mock.calls[0][0];
const event = {
kind: "event",
event_id: "event-id",
} as const;
const hint = {
event_id: "event-id",
} as const;

// Act
const result = registeredProcessor(event, hint);

// Assert
expect(enhanceSpy).toHaveBeenCalledWith(event, hint);
expect(result).toBe("ENHANCED");
});
});
});

describe("#enhanceEventWithErrorData", () => {
describe("#processEvent", () => {
it.each([
null,
undefined,
Expand All @@ -184,7 +116,7 @@ describe("KindErrorData", () => {
"should return the event if the original exception (%s) is not an Error",
(originalException: any) => {
// Arrange
const underTest = new KindErrorData();
const underTest = kindErrorDataIntegration();
const event = {
kind: "event",
event_id: "event-id",
Expand All @@ -195,7 +127,11 @@ describe("KindErrorData", () => {
} as const;

// Act
const result = underTest.enhanceEventWithErrorData(event, hint);
const result = underTest.processEvent?.(
event,
hint,
mockClient,
);

// Assert
expect(result).toBe(event);
Expand All @@ -204,14 +140,14 @@ describe("KindErrorData", () => {

it("should return the event if there is no hint", () => {
// Arrange
const underTest = new KindErrorData();
const underTest = kindErrorDataIntegration();
const event = {
kind: "event",
event_id: "event-id",
} as const;

// Act
const result = underTest.enhanceEventWithErrorData(event);
const result = underTest.processEvent?.(event, {}, mockClient);

// Assert
expect(result).toBe(event);
Expand All @@ -224,7 +160,7 @@ describe("KindErrorData", () => {
groupByTagName: "GROUP",
kindTagName: "KIND",
} as const;
const underTest = new KindErrorData(options);
const underTest = kindErrorDataIntegration(options);
const event = {
kind: "event",
event_id: "event-id",
Expand All @@ -238,7 +174,7 @@ describe("KindErrorData", () => {
.mockReturnValue(EmptySentryData);

// Act
underTest.enhanceEventWithErrorData(event, hint);
underTest.processEvent?.(event, hint, mockClient);

// Assert
expect(collateSentryDataSpy).toHaveBeenCalledWith(
Expand All @@ -254,7 +190,7 @@ describe("KindErrorData", () => {
groupByTagName: "GROUP",
kindTagName: "KIND",
} as const;
const underTest = new KindErrorData(options);
const underTest = kindErrorDataIntegration(options);
const event = {
kind: "event",
event_id: "event-id",
Expand Down Expand Up @@ -290,7 +226,7 @@ describe("KindErrorData", () => {

// Act
// @ts-expect-error [FEI-5011] - TS2345 - Argument of type '{ readonly kind: "event"; readonly event_id: "event-id"; readonly tags: { readonly tag1: "originalValue1"; readonly tag2: "originalValue2"; }; readonly contexts: { readonly context1: { readonly key1: "originalValue1"; }; readonly context2: { ...; }; }; readonly fingerprint: readonly [...]; }' is not assignable to parameter of type 'SentryEvent'.
const result = underTest.enhanceEventWithErrorData(event, hint);
const result = underTest.processEvent?.(event, hint, mockClient);

// Assert
expect(result).toStrictEqual({
Expand Down
2 changes: 1 addition & 1 deletion packages/wonder-stuff-sentry/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export {KindSentryError} from "./kind-sentry-error";
export {KindErrorData} from "./kind-error-data";
export {kindErrorDataIntegration} from "./kind-error-data";

export type {
KindErrorDataOptions,
Expand Down
121 changes: 121 additions & 0 deletions packages/wonder-stuff-sentry/src/kind-error-data-integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import {Errors} from "@khanacademy/wonder-stuff-core";
import {Integration, Event, EventHint} from "@sentry/core";
import type {KindErrorDataOptions} from "./types";

import {collateSentryData} from "./collate-sentry-data";
import {DefaultKindErrorDataOptions} from "./default-kind-error-data-options";
import {isTagKeyValid} from "./is-tag-key-valid";
import {KindSentryError} from "./kind-sentry-error";

type InvalidTags = {
invalidKindTag?: string;
invalidGroupByTag?: string;
invalidConcatenatedMessageTag?: string;
};

const INTEGRATION_NAME = "KindErrorData";

function buildOptionsWithDefaults(
options?: Partial<KindErrorDataOptions>,
): KindErrorDataOptions {
const _options = {
...DefaultKindErrorDataOptions,
...options,
};

if (process.env.NODE_ENV !== "production") {
// Let's make sure we got valid options.
const invalidTagNames: InvalidTags = {};
if (!isTagKeyValid(_options.kindTagName)) {
invalidTagNames.invalidKindTag = _options.kindTagName;
}
if (!isTagKeyValid(_options.groupByTagName)) {
invalidTagNames.invalidGroupByTag = _options.groupByTagName;
}
if (!isTagKeyValid(_options.concatenatedMessageTagName)) {
invalidTagNames.invalidConcatenatedMessageTag =
_options.concatenatedMessageTagName;
}
if (Object.keys(invalidTagNames).length) {
throw new KindSentryError("Invalid options", Errors.InvalidInput, {
sentryData: {
contexts: {
invalidTagNames: {
...invalidTagNames,
},
},
},
});
}
}

return _options;
}

/**
* Attaches extracted information from the Error object to extra field in the Event
*/
function enhanceEventWithErrorData(
options: KindErrorDataOptions,
event: Event,
hint?: EventHint,
): Event {
const maybeError = hint?.originalException;
// We only enhance events of type error.
if (!(maybeError instanceof Error)) {
return event;
}

// Collate the data we want to collect.
const {tags, contexts, fingerprint} = collateSentryData(
options,
maybeError,
);

// Now that we have data, we need to attach it to the event.
/**
* Tags help categorize things.
*/
event.tags = {
...event.tags,
...tags,
};

/**
* Each context creates a new headed section in the sentry report.
* Useful for grouping specific context together.
*
* We now output all the contexts to the scope.
*/
const updatedContexts = {
...event.contexts,
...contexts,
} as const;
/**
* NOTE: If you don't see Sentry serializing the right depth in your
* contexts, increase the `normalizeDepth` option of the Sentry
* configuration; it defaults to 3, which is not always enough.
*/
event.contexts = updatedContexts;

/**
* Fingerprint helps group like messages that otherwise would not
* get grouped.
*/
event.fingerprint = [...(event.fingerprint ?? []), ...fingerprint];

return event;
}

export function kindErrorDataIntegration(
options?: Partial<KindErrorDataOptions>,
): Integration {
const _options = buildOptionsWithDefaults(options);

return {
name: INTEGRATION_NAME,
processEvent(event, hint, client) {
return enhanceEventWithErrorData(_options, event, hint);
},
};
}
Loading
Loading