Skip to content

feat(feedback): use custom prepare/send, re-use createEventEnvelope from core #9432

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

Merged
merged 11 commits into from
Nov 8, 2023
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type { OfflineStore, OfflineTransportOptions } from './transports/offline
export type { ServerRuntimeClientOptions } from './server-runtime-client';

export * from './tracing';
export { createEventEnvelope } from './envelope';
Copy link
Member Author

Choose a reason for hiding this comment

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

Are we good to export this @mydea?

This also means we'll have to wait for an SDK release before we can release a new version of the SDK

Copy link
Member

Choose a reason for hiding this comment

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

fine by me! 👍

export {
addBreadcrumb,
captureCheckIn,
Expand Down
2 changes: 1 addition & 1 deletion packages/feedback/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { sendFeedbackRequest } from './util/sendFeedbackRequest';
export { sendFeedback } from './sendFeedback';
export { Feedback } from './integration';
18 changes: 1 addition & 17 deletions packages/feedback/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,10 @@
import type { Event, Primitive } from '@sentry/types';
import type { Primitive } from '@sentry/types';

import type { ActorComponent } from '../widget/Actor';
import type { DialogComponent } from '../widget/Dialog';

export type SentryTags = { [key: string]: Primitive } | undefined;

/**
* NOTE: These types are still considered Beta and subject to change.
* @hidden
*/
export interface FeedbackEvent extends Event {
feedback: {
message: string;
url: string;
contact_email?: string;
name?: string;
replay_id?: string;
};
// TODO: Add this event type to Event
// type: 'feedback_event';
}

export interface SendFeedbackData {
feedback: {
message: string;
Expand Down
24 changes: 11 additions & 13 deletions packages/feedback/src/util/handleFeedbackSubmit.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import type { TransportMakeRequestResponse } from '@sentry/types';
import { logger } from '@sentry/utils';

import { sendFeedback } from '../sendFeedback';
import type { FeedbackFormData, SendFeedbackOptions } from '../types';
import type { DialogComponent } from '../widget/Dialog';

/**
* Calls `sendFeedback` to send feedback, handles UI behavior of dialog.
* Handles UI behavior of dialog when feedback is submitted, calls
* `sendFeedback` to send feedback.
*/
export async function handleFeedbackSubmit(
dialog: DialogComponent | null,
feedback: FeedbackFormData,
options?: SendFeedbackOptions,
): Promise<Response | false> {
): Promise<TransportMakeRequestResponse | void> {
if (!dialog) {
// Not sure when this would happen
return false;
return;
}

const showFetchError = (): void => {
Expand All @@ -22,21 +26,15 @@ export async function handleFeedbackSubmit(
dialog.showError('There was a problem submitting feedback, please wait and try again.');
};

dialog.hideError();

try {
dialog.hideError();
const resp = await sendFeedback(feedback, options);

if (!resp) {
// Errored... re-enable submit button
showFetchError();
return false;
}

// Success!
return resp;
} catch {
// Errored... re-enable submit button
} catch (err) {
__DEBUG_BUILD__ && logger.error(err);
showFetchError();
return false;
}
}
23 changes: 7 additions & 16 deletions packages/feedback/src/util/prepareFeedbackEvent.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { Scope } from '@sentry/core';
import { prepareEvent } from '@sentry/core';
import type { Client } from '@sentry/types';

import type { FeedbackEvent } from '../types';
import type { Client, FeedbackEvent } from '@sentry/types';

interface PrepareFeedbackEventParams {
client: Client;
Expand All @@ -17,20 +15,22 @@ export async function prepareFeedbackEvent({
scope,
event,
}: PrepareFeedbackEventParams): Promise<FeedbackEvent | null> {
const eventHint = { integrations: undefined };
const eventHint = {};
if (client.emit) {
client.emit('preprocessEvent', event, eventHint);
}

const preparedEvent = (await prepareEvent(
client.getOptions(),
event,
{ integrations: undefined },
eventHint,
scope,
client,
)) as FeedbackEvent | null;

// If e.g. a global event processor returned null
if (!preparedEvent) {
if (preparedEvent === null) {
// Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions
client.recordDroppedEvent('event_processor', 'feedback', event);
return null;
}

Expand All @@ -39,14 +39,5 @@ export async function prepareFeedbackEvent({
// we need to do this manually.
preparedEvent.platform = preparedEvent.platform || 'javascript';

// extract the SDK name because `client._prepareEvent` doesn't add it to the event
const metadata = client.getSdkMetadata && client.getSdkMetadata();
const { name, version } = (metadata && metadata.sdk) || {};

preparedEvent.sdk = {
...preparedEvent.sdk,
name: name || 'sentry.javascript.unknown',
version: version || '0.0.0',
};
return preparedEvent;
}
141 changes: 73 additions & 68 deletions packages/feedback/src/util/sendFeedbackRequest.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,36 @@
import { getCurrentHub } from '@sentry/core';
import { dsnToString } from '@sentry/utils';
import { createEventEnvelope, getCurrentHub } from '@sentry/core';
import type { FeedbackEvent, TransportMakeRequestResponse } from '@sentry/types';

import type { SendFeedbackData } from '../types';
import { prepareFeedbackEvent } from './prepareFeedbackEvent';

/**
* Send feedback using `fetch()`
* Send feedback using transport
*/
export async function sendFeedbackRequest({
feedback: { message, email, name, replay_id, url },
}: SendFeedbackData): Promise<Response | null> {
}: SendFeedbackData): Promise<void | TransportMakeRequestResponse> {
const hub = getCurrentHub();

if (!hub) {
return null;
}

const client = hub.getClient();
const scope = hub.getScope();
const transport = client && client.getTransport();
const dsn = client && client.getDsn();

if (!client || !transport || !dsn) {
return null;
return;
}

const baseEvent = {
feedback: {
contact_email: email,
name,
message,
replay_id,
url,
const baseEvent: FeedbackEvent = {
contexts: {
feedback: {
contact_email: email,
name,
message,
replay_id,
url,
},
},
// type: 'feedback_event',
type: 'feedback',
};

const feedbackEvent = await prepareFeedbackEvent({
Expand All @@ -42,72 +39,80 @@ export async function sendFeedbackRequest({
event: baseEvent,
});

if (!feedbackEvent) {
// Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions
// client.recordDroppedEvent('event_processor', 'feedback', baseEvent);
return null;
if (feedbackEvent === null) {
return;
}

/*
For reference, the fully built event looks something like this:
{
"data": {
"dist": "abc123",
"type": "feedback",
"event_id": "d2132d31b39445f1938d7e21b6bf0ec4",
"timestamp": 1597977777.6189718,
"dist": "1.12",
"platform": "javascript",
"environment": "production",
"feedback": {
"contact_email": "[email protected]",
"message": "I really like this user-feedback feature!",
"replay_id": "ec3b4dc8b79f417596f7a1aa4fcca5d2",
"url": "https://docs.sentry.io/platforms/javascript/"
"release": 42,
"tags": {"transaction": "/organizations/:orgId/performance/:eventSlug/"},
"sdk": {"name": "name", "version": "version"},
"user": {
"id": "123",
"username": "user",
"email": "[email protected]",
"ip_address": "192.168.11.12",
},
"id": "1ffe0775ac0f4417aed9de36d9f6f8dc",
"platform": "javascript",
"release": "[email protected]",
"request": {
"headers": {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}
},
"sdk": {
"name": "sentry.javascript.react",
"version": "6.18.1"
"url": None,
"headers": {
"user-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15"
},
},
"tags": {
"key": "value"
"contexts": {
"feedback": {
"message": "test message",
"contact_email": "[email protected]",
"type": "feedback",
},
"trace": {
"trace_id": "4C79F60C11214EB38604F4AE0781BFB2",
"span_id": "FA90FDEAD5F74052",
"type": "trace",
},
"replay": {
"replay_id": "e2d42047b1c5431c8cba85ee2a8ab25d",
},
},
"timestamp": "2023-08-31T14:10:34.954048",
"user": {
"email": "[email protected]",
"id": "123",
"ip_address": "127.0.0.1",
"name": "user",
"username": "user2270129"
}
}
}
*/

// Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to
// sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may
// have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid
// of this `delete`, lest we miss putting it back in the next time the property is in use.)
delete feedbackEvent.sdkProcessingMetadata;
const envelope = createEventEnvelope(feedbackEvent, dsn, client.getOptions()._metadata, client.getOptions().tunnel);

let response: void | TransportMakeRequestResponse;

try {
const path = 'https://sentry.io/api/0/feedback/';
const response = await fetch(path, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `DSN ${dsnToString(dsn)}`,
},
body: JSON.stringify(feedbackEvent),
});
if (!response.ok) {
return null;
response = await transport.send(envelope);
} catch (err) {
const error = new Error('Unable to send Feedback');

try {
// In case browsers don't allow this property to be writable
// @ts-expect-error This needs lib es2022 and newer
error.cause = err;
} catch {
// nothing to do
}
throw error;
}

// TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore
if (!response) {
return response;
} catch (err) {
return null;
}

// Require valid status codes, otherwise can assume feedback was not sent successfully
if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {
throw new Error('Unable to send Feedback');
}

return response;
}
Loading