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

feat(gatsby): Support non-serializable SDK options #4064

Merged
merged 11 commits into from
Oct 22, 2021
64 changes: 55 additions & 9 deletions packages/gatsby/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,63 @@
const Sentry = require('@sentry/gatsby');

// To avoid confusion, you must set the Sentry configuration in one
Copy link
Member

Choose a reason for hiding this comment

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

I think this behaviour is still too complicated. Let's just make it so that if sentry.config.{js, ts} is defined, that will always take priority over the plugin params (and then we can just log a warning if plugin params are also used).

Copy link
Member

Choose a reason for hiding this comment

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

We can then also rm -rf all this enabled logic.

Copy link
Member Author

Choose a reason for hiding this comment

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

Simplified the logic. We can't get rid of the isSentryInitialized because the gatsby-browser script's scope is in the browser, so we need to still check for the Sentry instance. But, we are no longer playing around with the enabled.

// place: either in `gatsby-config.js` (without non-serializable
// option support) or in `sentry.config.js` (supporting them).
// Defining them in `sentry.config.js` makes the SDK to initialize
// before this script is run, so we want to make sure to disable
// the SDK if both places contain options and warn the user about
// it. If the SDK hasn't been initialized at this point, we know
// there aren't any options set in `sentry.config.js`, so it's safe
// to initialize it here.

exports.onClientEntry = function(_, pluginParams) {
if (pluginParams === undefined) {
const isIntialized = isSentryInitialized();
if (!areSentryOptionsDefined(pluginParams)) {
if (isIntialized) {
window.Sentry = Sentry; // For backwards compatibility
} else {
// eslint-disable-next-line no-console
console.error(
'Sentry Logger [Error]: No config for the Gatsby SDK was found. Learn how to configure it on\n' +
'https://docs.sentry.io/platforms/javascript/guides/gatsby/',
);
}
return;
}

Sentry.init({
// eslint-disable-next-line no-undef
release: __SENTRY_RELEASE__,
// eslint-disable-next-line no-undef
dsn: __SENTRY_DSN__,
...pluginParams,
});
if (isIntialized) {
// eslint-disable-next-line no-console
console.error(
'Sentry Logger [Error]: The SDK has been disabled because your Sentry config must live in one place.\n' +
'Consider moving it all to your `sentry.config.js`.',
);
// TODO: link to the docs where the new approach is documented
window.__SENTRY__.hub.getClient().getOptions().enabled = false;
iker-barriocanal marked this conversation as resolved.
Show resolved Hide resolved
} else {
Sentry.init({
// eslint-disable-next-line no-undef
release: __SENTRY_RELEASE__,
// eslint-disable-next-line no-undef
dsn: __SENTRY_DSN__,
...pluginParams,
});
}

window.Sentry = Sentry;
window.Sentry = Sentry; // For backwards compatibility
};

function isSentryInitialized() {
// Although `window` should exist because we're in the browser (where this script
// is run), and `__SENTRY__.hub` is created when importing the Gatsby SDK, double
// check that in case something weird happens.
return !!(window && window.__SENTRY__ && window.__SENTRY__.hub && window.__SENTRY__.hub.getClient());
}

function areSentryOptionsDefined(params) {
if (params == undefined) return false;
// Even if there aren't any options, there's a `plugins` property defined as an empty array
if (Object.keys(params).length == 1 && Array.isArray(params.plugins) && params.plugins.length == 0) {
return false;
}
return true;
}
42 changes: 41 additions & 1 deletion packages/gatsby/gatsby-node.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const fs = require('fs');

const sentryRelease = JSON.stringify(
// Always read first as Sentry takes this as precedence
process.env.SENTRY_RELEASE ||
Expand All @@ -15,8 +17,9 @@ const sentryRelease = JSON.stringify(
);

const sentryDsn = JSON.stringify(process.env.SENTRY_DSN || '');
const SENTRY_USER_CONFIG = './sentry.config.js';
iker-barriocanal marked this conversation as resolved.
Show resolved Hide resolved

exports.onCreateWebpackConfig = ({ plugins, actions }) => {
exports.onCreateWebpackConfig = ({ plugins, getConfig, actions }) => {
actions.setWebpackConfig({
plugins: [
plugins.define({
Expand All @@ -25,4 +28,41 @@ exports.onCreateWebpackConfig = ({ plugins, actions }) => {
}),
],
});

// To configure the SDK `sentry.config.js` is prioritized over `gatsby-config.js`,
// since it isn't possible to set non-serializable parameters in the latter.
// Prioritization here means what `init` is being run first.
iker-barriocanal marked this conversation as resolved.
Show resolved Hide resolved
if (!fs.existsSync(SENTRY_USER_CONFIG)) {
// We don't want to warn users here, yet they may have their config in `gatsby-config.js`.
return;
}
// `setWebpackConfig` merges the Webpack config, ignoring some props like `entry`. See
// https://www.gatsbyjs.com/docs/reference/config-files/actions/#setWebpackConfig
// So it's not possible to inject the Sentry properties with that method. Instead, we
// can replace the whole config with the modifications we need.
const finalConfig = injectSentryConfig(getConfig());
actions.replaceWebpackConfig(finalConfig);
};

function injectSentryConfig(config) {
const injectedEntries = {};
// TODO: investigate what entries need the Sentry config injected.
// We may want to skip some.
Object.keys(config.entry).map(prop => {
const value = config.entry[prop];
let injectedValue = value;
if (typeof value === 'string') {
injectedValue = [SENTRY_USER_CONFIG, value];
} else if (Array.isArray(value)) {
injectedValue = [SENTRY_USER_CONFIG, ...value];
} else {
// eslint-disable-next-line no-console
console.error(
`Sentry Logger [Error]: Could not inject SDK initialization code into ${prop}, unexpected format: `,
typeof value,
);
}
injectedEntries[prop] = injectedValue;
});
return { ...config, entry: injectedEntries };
}
74 changes: 71 additions & 3 deletions packages/gatsby/test/gatsby-browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ jest.mock('@sentry/gatsby', () => {
},
};
});
global.console.error = jest.fn();

let tracingAddExtensionMethods = jest.fn();
jest.mock('@sentry/tracing', () => {
Expand Down Expand Up @@ -50,9 +51,76 @@ describe('onClientEntry', () => {
}
});

it('sets window.Sentry', () => {
onClientEntry(undefined, {});
expect((window as any).Sentry).not.toBeUndefined();
describe('inits Sentry once', () => {
afterEach(() => {
delete (window as any).Sentry;
delete (window as any).__SENTRY__;
(global.console.error as jest.Mock).mockClear();
});

function setMockedSentryInWindow() {
const sdkOptions = {
enabled: true,
};
(window as any).__SENTRY__ = {
hub: {
getClient: () => ({
getOptions: () => sdkOptions,
}),
},
};
}

it('initialized in injected config, without pluginParams', () => {
setMockedSentryInWindow();
onClientEntry(undefined, { plugins: [] });
// eslint-disable-next-line no-console
expect(console.error).not.toHaveBeenCalled();
expect(sentryInit).not.toHaveBeenCalled();
expect((window as any).Sentry).toBeDefined();
});

it('initialized in injected config, with pluginParams', () => {
setMockedSentryInWindow();
onClientEntry(undefined, { plugins: [], dsn: 'dsn', release: 'release' });
// eslint-disable-next-line no-console
expect((console.error as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(`
Array [
"Sentry Logger [Error]: The SDK has been disabled because your Sentry config must live in one place.
Consider moving it all to your \`sentry.config.js\`.",
]
`);
expect(sentryInit).not.toHaveBeenCalled();
expect((window as any).__SENTRY__.hub.getClient().getOptions().enabled).toBe(false);
expect((window as any).Sentry).toBeDefined();
});

it('not initialized in injected config, without pluginParams', () => {
onClientEntry(undefined, { plugins: [] });
// eslint-disable-next-line no-console
expect((console.error as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(`
Array [
"Sentry Logger [Error]: No config for the Gatsby SDK was found. Learn how to configure it on
https://docs.sentry.io/platforms/javascript/guides/gatsby/",
]
`);
expect((window as any).Sentry).not.toBeDefined();
});

it('not initialized in injected config, with pluginParams', () => {
onClientEntry(undefined, { plugins: [], dsn: 'dsn', release: 'release' });
// eslint-disable-next-line no-console
expect(console.error).not.toHaveBeenCalled();
expect(sentryInit).toHaveBeenCalledTimes(1);
expect(sentryInit.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"dsn": "dsn",
"plugins": Array [],
"release": "release",
}
`);
expect((window as any).Sentry).toBeDefined();
});
});

it('sets a tracesSampleRate if defined as option', () => {
Expand Down