Skip to content

Commit

Permalink
fix: update plugin for latest sentry
Browse files Browse the repository at this point in the history
  • Loading branch information
farfromrefuge committed Dec 18, 2023
1 parent 95f7754 commit e2e3b07
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 235 deletions.
14 changes: 7 additions & 7 deletions plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@
"url": "https://github.com/nativescript-community/sentry"
},
"dependencies": {
"@sentry/browser": "7.15.0",
"@sentry/core": "7.15.0",
"@sentry/hub": "7.15.0",
"@sentry/integrations": "7.15.0",
"@sentry/tracing": "7.15.0",
"@sentry/types": "7.15.0",
"@sentry/utils": "7.15.0",
"@sentry/browser": "^7.88.0",
"@sentry/core": "^7.88.0",
"@sentry/hub": "^7.88.0",
"@sentry/integrations": "^7.88.0",
"@sentry/tracing": "^7.88.0",
"@sentry/types": "^7.88.0",
"@sentry/utils": "^7.88.0",
"stacktrace-parser": "^0.1.10"
},
"gitHead": "1e799d9f3a3eeb19c0fc4188be82a6cded4ea727"
Expand Down
2 changes: 1 addition & 1 deletion plugin/platforms/android/include.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ android {
}
}
dependencies {
def sentryVersion = project.hasProperty("sentryVersion") ? project.sentryVersion : "6.9.1"
def sentryVersion = project.hasProperty("sentryVersion") ? project.sentryVersion : "7.0.0"
implementation "io.sentry:sentry-android:$sentryVersion"
}
60 changes: 44 additions & 16 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { BrowserClient, makeFetchTransport } from '@sentry/browser';
import { BrowserTransportOptions } from '@sentry/browser/types/transports/types';
import { eventFromException, eventFromMessage,makeFetchTransport } from '@sentry/browser';import { BrowserTransportOptions } from '@sentry/browser/types/transports/types';
import { FetchImpl } from '@sentry/browser/types/transports/utils';
import { BaseClient } from '@sentry/core';

import { ClientReportEnvelope, ClientReportItem, Envelope, Event, EventHint, Outcome, SeverityLevel, Transport, UserFeedback } from '@sentry/types';
import { ClientReportEnvelope, ClientReportItem, Envelope, Event, EventHint, Exception, Outcome, SeverityLevel, Thread, Transport, UserFeedback } from '@sentry/types';
import { SentryError, dateTimestampInSeconds, logger } from '@sentry/utils';

import { alert } from '@nativescript/core';
Expand All @@ -14,6 +13,7 @@ import { createUserFeedbackEnvelope, items } from './utils/envelope';
import { mergeOutcomes } from './utils/outcome';
import { NATIVE } from './wrapper';
import { Screenshot } from './integrations/screenshot';
import { rewriteFrameIntegration } from './sdk';


/**
Expand All @@ -24,7 +24,7 @@ import { Screenshot } from './integrations/screenshot';
*/
export class NativescriptClient extends BaseClient<NativescriptClientOptions> {
private _outcomesBuffer: Outcome[];
private readonly _browserClient: BrowserClient;
// private readonly _browserClient: BrowserClient;

/**
* Creates a new React Native SDK instance.
Expand All @@ -45,14 +45,14 @@ export class NativescriptClient extends BaseClient<NativescriptClientOptions> {

this._outcomesBuffer = [];

this._browserClient = new BrowserClient({
dsn: options.dsn,
transport: options.transport,
transportOptions: options.transportOptions,
stackParser: options.stackParser,
integrations: [],
_metadata: options._metadata,
});
// this._browserClient = new BrowserClient({
// dsn: options.dsn,
// transport: options.transport,
// transportOptions: options.transportOptions,
// stackParser: options.stackParser,
// integrations: [],
// _metadata: options._metadata,
// });

this._initNativeSdk();
}
Expand All @@ -65,15 +65,43 @@ export class NativescriptClient extends BaseClient<NativescriptClientOptions> {
if (exception['stackTrace']) {
exception['stacktrace'] = exception['stackTrace'];
}
Screenshot.attachScreenshotToEventHint(hint, this._options);
return this._browserClient.eventFromException(exception, hint);
const hintWithScreenshot = Screenshot.attachScreenshotToEventHint(hint, this._options);
return eventFromException(
this._options.stackParser,
exception,
hintWithScreenshot,
this._options.attachStacktrace,
);
// return this._browserClient.eventFromException(exception, hint);
}

/**
* @inheritDoc
*/
public eventFromMessage(_message: string, _level?: SeverityLevel, _hint?: EventHint): PromiseLike<Event> {
return this._browserClient.eventFromMessage(_message, _level, _hint);
public eventFromMessage(message: string, level?: SeverityLevel, hint?: EventHint): PromiseLike<Event> {
return eventFromMessage(
this._options.stackParser,
message,
level,
hint,
this._options.attachStacktrace,
).then((event: Event) => {
// TMP! Remove this function once JS SDK uses threads for messages
if (!event.exception?.values || event.exception.values.length <= 0) {
return event;
}
const values = event.exception.values.map((exception: Exception): Thread => {
if (exception.stacktrace) {
exception.stacktrace.frames.forEach((frame) => rewriteFrameIntegration._iteratee(frame));
}
return {
stacktrace: exception.stacktrace,
};
});
(event as { threads?: { values: Thread[] } }).threads = { values };
delete event.exception;
return event;
});
}

/**
Expand Down
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ _addTracingExtensions();

import * as Integrations from './integrations';
import { SDK_NAME, SDK_VERSION } from './version';
import { Trace } from '@nativescript/core';
export { NativescriptOptions } from './options';
export { NativescriptClient } from './client';

Expand All @@ -76,3 +77,16 @@ export {
// } from './tracing';

export { Integrations, SDK_NAME, SDK_VERSION };

export const SentryTraceCategory = 'Sentry';

export enum CLogTypes {
log = Trace.messageType.log,
info = Trace.messageType.info,
warning = Trace.messageType.warn,
error = Trace.messageType.error
}

export const CLog = (type: CLogTypes, ...args) => {
Trace.write(args.map((a) => (a && typeof a === 'object' ? JSON.stringify(a) : a)).join(' '), SentryTraceCategory, type);
};
10 changes: 7 additions & 3 deletions src/integrations/debugsymbolicator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import { addEventProcessor, addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import { Event, EventHint, Integration, StackFrame, StackLineParser } from '@sentry/types';
import { logger, stackParserFromStackParserOptions } from '@sentry/utils';

Expand Down Expand Up @@ -122,17 +122,20 @@ export class DebugSymbolicator implements Integration {
* @inheritDoc
*/
public setupOnce(): void {
console.log('setupOnce');
addGlobalEventProcessor(async (event: Event, hint?: EventHint) => {
const self = getCurrentHub().getIntegration(DebugSymbolicator);
console.log('addGlobalEventProcessor', hint.originalException);
if (!self || hint === undefined || hint.originalException === undefined) {
return event;
}
// @ts-ignore
const error: NativescriptError = hint.originalException;
// const parseErrorStack = require('react-native/Libraries/Core/Devtools/parseErrorStack');
const stack = parseErrorStack(error);
console.log('addGlobalEventProcessor', error);
console.log('stack', stack);
console.log('event.exception?.values?.[0].stacktrace', event.exception?.values?.[0].stacktrace);
// console.log('stack', stack);


// Ideally this should go into contexts but android sdk doesn't support it
Expand Down Expand Up @@ -174,7 +177,8 @@ export class DebugSymbolicator implements Integration {
* @param frames StackFrame[]
*/
private _replaceFramesInEvent(event: Event, frames: StackFrame[]): void {
if (event.exception && event.exception.values && event.exception.values[0] && event.exception.values[0].stacktrace) {
console.log('_replaceFramesInEvent');
if (event.exception?.values?.[0].stacktrace) {
event.exception.values[0].stacktrace.frames = frames.reverse();
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/integrations/devicecontext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import { addEventProcessor, addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import { Contexts, Event, Integration } from '@sentry/types';
import { logger } from '@sentry/utils';
import { NATIVE } from '../wrapper';
Expand All @@ -18,7 +18,7 @@ export class DeviceContext implements Integration {
* @inheritDoc
*/
public setupOnce(): void {
addGlobalEventProcessor(async (event: Event) => {
addEventProcessor(async (event: Event) => {
const self = getCurrentHub().getIntegration(DeviceContext);
if (!self) {
return event;
Expand Down
28 changes: 21 additions & 7 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,15 @@ export interface BaseNativescriptOptions {
/** The interval to end a session if the App goes to the background. */
sessionTrackingIntervalMillis?: number;

/** Enable scope sync from Java to NDK on Android */
/** Enable NDK on Android
*
* @default true
*/
enableNdk?: boolean;

/** Enable scope sync from Java to NDK on Android
* Only has an effect if `enableNdk` is `true`.
*/
enableNdkScopeSync?: boolean;

/** When enabled, all the threads are automatically attached to all logged events on Android */
Expand Down Expand Up @@ -85,12 +93,6 @@ export interface BaseNativescriptOptions {
*/
enableOutOfMemoryTracking?: boolean;

/**
* Set data to the inital scope
* @deprecated Use `Sentry.configureScope(...)`
*/
initialScope?: CaptureContext;


/**
* The max cache items for capping the number of envelopes.
Expand Down Expand Up @@ -120,6 +122,18 @@ export interface BaseNativescriptOptions {
* @default 2
*/
appHangsTimeoutInterval?: number;

/**
* The max queue size for capping the number of envelopes waiting to be sent by Transport.
*/
maxQueueSize?: number;
}

export interface ReactNativeTransportOptions extends BrowserTransportOptions {
/**
* @deprecated use `maxQueueSize` in the root of the SDK options.
*/
bufferSize?: number;
}

/**
Expand Down
68 changes: 40 additions & 28 deletions src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,47 +13,47 @@ import { NativescriptErrorHandlersOptions } from './integrations/nativescripterr
import { SdkInfo } from './integrations/sdkinfo';
// import { NativescriptScope } from './scope';
import { NativescriptTracing } from './tracing';
import { makeNativescriptTransport } from './transports/native';
import { DEFAULT_BUFFER_SIZE, makeNativescriptTransport } from './transports/native';
import { makeUtf8TextEncoder } from './transports/TextEncoder';
import { safeFactory, safeTracesSampler } from './utils/safe';
import { NATIVE } from './wrapper';
import { parseErrorStack } from './integrations/debugsymbolicator';
import { Screenshot } from './integrations/screenshot';
import { getDefaultEnvironment } from './utils/environment';


const STACKTRACE_LIMIT = 50;
function stripSentryFramesAndReverse(stack) {
if (!stack.length) {
return [];
}
// const STACKTRACE_LIMIT = 50;
// function stripSentryFramesAndReverse(stack) {
// if (!stack.length) {
// return [];
// }

let localStack = stack;
// let localStack = stack;

const firstFrameFunction = localStack[0].function || '';
const lastFrameFunction = localStack[localStack.length - 1].function || '';
// const firstFrameFunction = localStack[0].function || '';
// const lastFrameFunction = localStack[localStack.length - 1].function || '';

// If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)
if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {
localStack = localStack.slice(1);
}
// // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)
// if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {
// localStack = localStack.slice(1);
// }

// If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)
if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {
localStack = localStack.slice(0, -1);
}
// // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)
// if (lastFrameFunction.indexOf('sentryWrapped') !== -1) {
// localStack = localStack.slice(0, -1);
// }

// The frame where the crash happened, should be the last entry in the array
return localStack
.slice(0, STACKTRACE_LIMIT)
.map(frame => ({
...frame,
filename: frame.filename || localStack[0].filename,
function: frame.function || undefined,
}));
}
// // The frame where the crash happened, should be the last entry in the array
// return localStack
// .slice(0, STACKTRACE_LIMIT)
// .map(frame => ({
// ...frame,
// filename: frame.filename || localStack[0].filename,
// function: frame.function || undefined,
// }));
// }
const defaultStackParser = (stack, skipFirst = 0) => {
let frames = parseErrorStack({ stack } as any);

if (skipFirst) {
frames = frames.slice(skipFirst);
}
Expand All @@ -78,6 +78,8 @@ const DEFAULT_OPTIONS: NativescriptOptions & NativescriptErrorHandlersOptions =
textEncoder: makeUtf8TextEncoder(),
},
sendClientReports: true,
maxQueueSize: DEFAULT_BUFFER_SIZE,
attachStacktrace: true
};

export let rewriteFrameIntegration: {
Expand All @@ -91,6 +93,10 @@ export function init(passedOptions: NativescriptOptions): void {
const NativescriptHub = new Hub(undefined, new Scope());
// const NativescriptHub = new Hub(undefined, new NativescriptScope());
makeMain(NativescriptHub);

const maxQueueSize = passedOptions.maxQueueSize
?? passedOptions.transportOptions?.bufferSize
?? DEFAULT_OPTIONS.maxQueueSize;
const options: NativescriptClientOptions & NativescriptOptions = {
...DEFAULT_OPTIONS,
...passedOptions,
Expand All @@ -99,14 +105,20 @@ export function init(passedOptions: NativescriptOptions): void {
transportOptions: {
...DEFAULT_OPTIONS.transportOptions,
...(passedOptions.transportOptions ?? {}),
bufferSize: maxQueueSize,
},
maxQueueSize ,
integrations: [],
// integrations: getIntegrationsToSetup(passedOptions),
stackParser: stackParserFromStackParserOptions(passedOptions.stackParser || defaultStackParser),
beforeBreadcrumb: safeFactory(passedOptions.beforeBreadcrumb, { loggerMessage: 'The beforeBreadcrumb threw an error' }),
initialScope: safeFactory(passedOptions.initialScope, { loggerMessage: 'The initialScope threw an error' }),
tracesSampler: safeTracesSampler(passedOptions.tracesSampler),
};

if (!('environment' in options)) {
options.environment = getDefaultEnvironment();
}
// As long as tracing is opt in with either one of these options, then this is how we determine tracing is enabled.
const tracingEnabled =
typeof options.tracesSampler !== 'undefined' ||
Expand Down Expand Up @@ -202,7 +214,7 @@ export function nativeCrash(): void {
* Use this before applying any realtime updates such as code-push or expo updates.
* Not yet working on Android
*/
export async function flush(timeout: number): Promise<boolean> {
export async function flush(timeout: number = 0): Promise<boolean> {
try {
const client = getCurrentHub().getClient<NativescriptClient>();

Expand Down
2 changes: 1 addition & 1 deletion src/tracing/nstracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export class NativescriptTracing implements Integration {
} = this.options;

this._getCurrentHub = getCurrentHub;
console.log('NativescriptTracing', this.options);
// console.log('NativescriptTracing', this.options);
if (enableAppStartTracking) {
void this._instrumentAppStart();
}
Expand Down
Loading

0 comments on commit e2e3b07

Please sign in to comment.